using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using CallCenterApi.Interface.Controllers.Base;
using System.Data;
using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Model;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.DB;
using System.Web.Caching;

namespace CallCenterApi.Interface.Controllers
{
    public class LoginController : BaseController
    {
        private BLL.T_Sys_RoleFunction roleFunctionBLL = new BLL.T_Sys_RoleFunction();
        public DateTime ExpiredTime = DateTime.Now.AddDays(1);// Convert.ToDateTime(ReadFile(HttpRuntime.AppDomainAppPath + "tools\\hykj.hy"));
        [HttpPost]
        public ActionResult login(LoginModel login)
        {
            

            bool appResult = LoodLoop();
            if (appResult)
            {
                DataTable dt = new DataTable();
                try
                {
                    Dictionary<string, string> paras = new Dictionary<string, string>();
                    string sql = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode and F_PassWord=@F_PassWord";
                    paras.Add("@F_UserCode", login.Username);
                    paras.Add("@F_PassWord", login.Password);

                    dt = DbHelperSQL.Query(sql, paras).Tables[0];
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            if (dt.Rows[0]["F_DeleteFlag"] != null && dt.Rows[0]["F_DeleteFlag"].ToString() == "1")
                            {
                                int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                    F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                    F_Result = "禁用账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });

                                return Error("此账号已经被禁用");
                            }
                            Dictionary<string, string> Dic = new Dictionary<string, string>();
                            Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToString());
                            Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToString());
                            Dic.Add("F_DeptId", dt.Rows[0]["F_DeptId"].ToString());
                            Dic.Add("F_UserName", dt.Rows[0]["F_UserName"].ToString());
                            Dic.Add("F_Telephone", dt.Rows[0]["F_Telephone"].ToString());
                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());
                            Dic.Add("F_SeatFlag", dt.Rows[0]["F_SeatFlag"].ToString());

                            if (dt.Rows[0]["F_GroupId"].ToString() != null)
                            {
                                Dic.Add("F_GroupId", dt.Rows[0]["F_GroupId"].ToString());
                            }
                            if (dt.Rows[0]["F_SeatRight"].ToString() != null)
                            {
                                Dic.Add("F_SeatRight", dt.Rows[0]["F_SeatRight"].ToString());
                            }
                            if (!string.IsNullOrEmpty(login.ExtensionPhone))
                            {
                                Dic.Add("F_ExtensionNumber", login.ExtensionPhone);
                            }
                            else
                            {
                                Dic.Add("F_ExtensionNumber", "");
                            }
                            Dic.Add("F_WorkNumber", dt.Rows[0]["F_WorkNumber"].ToString());

                            //CookieUtil.SetCookie("BaseCallCenter_T_User", Dic);
                            //写入登录日志
                            new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                F_Result = "登录成功",
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                            var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_UserCode"], Dic);
                           
                            //放入缓存
                            CacheHelper.Insert(token, Dic, 1440, System.Web.Caching.CacheItemPriority.NotRemovable, onRemove);

                            return Success("登录成功", new
                            {
                                token = token
                            });

                        }
                        else
                        {
                            //写入登录日志
                            DataTable dt1 = new CallCenterApi.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + login.Username + "'").Tables[0];
                            if (dt1.Rows.Count > 0)
                            {
                                int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                    F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                    F_Result = "登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                            }
                            else
                            {
                                int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = login.Username,
                                    F_LoginId = -1,
                                    F_Result = "登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                            }
                            return Error("账号或密码错误，请重新登录");
                        }



                    }
                    else
                    {
                        return Error("账号或密码错误，请重新登录");
                    }
                }
                catch (Exception ex)
                {
                    return Error("错误:" + ex.Message);
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            else
            {
                return Error("授权过期，请联系系统厂家。");
            }

        }

        [HttpPost]
        public ActionResult applogin(LoginModel login)
        {
            bool appResult = LoodLoop();
            if (appResult)
            {
                DataTable dt = new DataTable();
                try
                {
                    Dictionary<string, string> paras = new Dictionary<string, string>();
                    string sql = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode and F_PassWord=@F_PassWord and F_DeleteFlag=0";
                    paras.Add("@F_UserCode", login.Username);
                    paras.Add("@F_PassWord", login.Password);

                    dt = DbHelperSQL.Query(sql, paras).Tables[0];

                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["F_DeleteFlag"] != null && dt.Rows[0]["F_DeleteFlag"].ToString() == "1")
                        {
                            int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                F_Result = "禁用账号登录：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });

                            return Error("此账号已经被禁用");
                        }

                        string rid = dt.Rows[0]["F_RoleID"].ToString();
                        var role = new BLL.T_Sys_RoleInfo().GetModel(Int32.Parse(rid));
                        if (role.F_RoleCode == "WLDW" || role.F_RoleCode == "ZXLD" || role.F_RoleCode == "ZXLDGLY" || role.F_RoleCode == "GLY")
                        {
                            Dictionary<string, string> Dic = new Dictionary<string, string>();
                            Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToString());
                            Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToString());
                            Dic.Add("F_DeptId", dt.Rows[0]["F_DeptId"].ToString());
                            Dic.Add("F_UserName", dt.Rows[0]["F_UserName"].ToString());
                            Dic.Add("F_Telephone", dt.Rows[0]["F_Telephone"].ToString());
                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());
                            Dic.Add("F_SeatFlag", dt.Rows[0]["F_SeatFlag"].ToString());

                            if (dt.Rows[0]["F_GroupId"].ToString() != null)
                            {
                                Dic.Add("F_GroupId", dt.Rows[0]["F_GroupId"].ToString());
                            }
                            if (dt.Rows[0]["F_SeatRight"].ToString() != null)
                            {
                                Dic.Add("F_SeatRight", dt.Rows[0]["F_SeatRight"].ToString());
                            }
                            if (!string.IsNullOrEmpty(login.ExtensionPhone))
                            {
                                Dic.Add("F_ExtensionNumber", login.ExtensionPhone);
                            }
                            else
                            {
                                Dic.Add("F_ExtensionNumber", "");
                            }
                            Dic.Add("F_WorkNumber", dt.Rows[0]["F_WorkNumber"].ToString());

                            //CookieUtil.SetCookie("BaseCallCenter_T_User", Dic);
                            //写入登录日志
                            new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                F_Result = "APP登录成功",
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                          
                            var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_UserCode"], Dic);

                            //放入缓存
                            CacheHelper.Insert(token, Dic, 1440, System.Web.Caching.CacheItemPriority.NotRemovable);
                            return Success("登录成功", new
                            {
                                token = token
                            });
                            
                        }
                        else
                        {
                            return Error("权限不足");
                        }
                    }
                    else
                    {
                        //写入登录日志
                        DataTable dt1 = new CallCenterApi.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + login.Username + "'").Tables[0];
                        if (dt1.Rows.Count > 0)
                        {
                            int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                F_Result = "APP登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }
                        else
                        {
                            int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = login.Username,
                                F_LoginId = -1,
                                F_Result = "APP登录失败：帐号-" + login.Username + ";分机号-" + login.ExtensionPhone,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }
                        return Error("账号或密码错误，请重新登录");
                    }
                }
                catch (Exception ex)
                {
                    return Error("错误:" + ex.Message);
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            else
            {
                return Error("授权过期，请联系系统厂家。");
            }
        }

        public ActionResult Logout(string token = "")
        {
            if (Request.IsAuthenticated)
            {
                CacheHelper.Remove(token);
            }
            return Success("退出成功");
        }

        [Authority]
        public ActionResult Authority(string token = "", string url = "")
        {
            var roleId = Utils.StrToInt(User.UserData["F_RoleID"], 0);
            var role = new BLL.T_Sys_RoleInfo().GetModel(roleId);
            if (role != null)
            {
                //var roleFunctionList = roleFunctionBLL.DataTableToList(roleFunctionBLL.GetList(" F_RoleId=" + role.F_RoleId).Tables[0]);
                //var moduleFunction = new BLL.T_Sys_Function().GetModel(url);
                //if (moduleFunction != null)
                //{
                //    var single = roleFunctionList.SingleOrDefault(x => x.F_FunctionId == moduleFunction.F_FunctionId);
                //    if (single != null)
                //    {
                //        return Success("", moduleFunction.F_OptUrl);
                //    }
                //}
                return Success("成功");
            }
            return UnAuthorized("未授权");

        }

        /// <summary>
        /// 移除缓存后调用
        /// </summary>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="reason"></param>
        public void onRemove(string key, object val, CacheItemRemovedReason reason)
        {
            var obj = new
            {
                key = key,
                val = val,
                reason = reason
            };
            Warn(obj.ToJson());
        }

        /// <summary>
        /// 验证授权
        /// </summary>
        /// <returns></returns>
        private bool LoodLoop()
        {
            bool result = CheckValid();
            //return true;
            if (result)
                return true;
            else
                return false;
        }
        private bool CheckValid()
        {
            return DateTime.Now < ExpiredTime;
        }
        private static string ReadFile(string filepath)
        {
            string str = System.IO.File.ReadAllText(filepath, Encoding.UTF8);
            return DESEncrypt.Decrypt(str);
        }
    }
}