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;

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"));

        /// <summary>
        /// 登录验证 获取token
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult login(LoginModel login)
        {
            bool appResult = LoodLoop();
            if (appResult)
            {
                Model.T_Sys_UserAccount loginUser = new BLL.T_Sys_UserAccount().LoginGetModel(login.Username, login.Password);

                if (loginUser != null)
                {
                    string deptcode = "";
                    Model.T_Sys_Department deptModel = new BLL.T_Sys_Department().GetModel(loginUser.F_DeptId);
                    if (deptModel != null)
                    {
                        deptcode = deptModel.F_DeptCode;
                    }
                    //写入登录日志
                    new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                    {
                        F_LoginName = loginUser.F_UserName,
                        F_LoginId = loginUser.F_UserId,
                        F_Result = "登录成功",
                        F_LoginIP = Common.DTRequest.GetIP(),
                        F_Hostname = Common.DTRequest.GetIP(),
                        F_LoginDate = DateTime.Now,
                        F_Remark = "",
                        F_State = 0
                    });
                    Dictionary<string, string> Dic = new Dictionary<string, string>();
                    Dic.Add("F_UserCode", loginUser.F_UserCode);
                    Dic.Add("F_RoleId", loginUser.F_RoleId.ToString());
                    Dic.Add("F_DeptId", loginUser.F_DeptId.ToString());

                    var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_UserCode"], Dic);
                    return Success("登录成功", new
                    {
                        token,
                        date = Configs.GetValue("AuthDate"),
                        days = CallCenter.Utility.Common.CommonHelper.GetRemainingDay()
                    });
                }
                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("授权过期，请联系系统厂家。");
            }
        }

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

        public ActionResult Authority(string token = "", string url = "")
        {
                var roleId = CurrentUser.UserData.F_RoleId;
                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_ModuleFunctions().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 UnAuthorized("未授权");

        }



        /// <summary>
        /// 验证授权
        /// </summary>
        /// <returns></returns>
        private bool LoodLoop()
        {
            bool result = CheckValid();
            //return true;
            if (result)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 判断是否超时
        /// </summary>
        /// <returns></returns>
        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);
        }
    }
}