using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Msg;
using APT.Infrastructure.Api;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Core;
using APT.PF.WebApi.Models;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;

namespace APT.OP.WebApi.Controllers.Api.OP
{
    /// <summary>登入</summary>
    [Route("api/OP/Login")]
    public class LoginController : APTApiController<T_OP_CLIENT>
    {

        /// <summary>
        /// 登入
        /// </summary>
        /// <param name="filter">
        /// Keyword：用户ID
        /// Parameter1：用户Code
        /// Parameter2：密码
        /// Parameter3：平台类型
        /// Parameter4：Orgid
        /// Parameter5：//表单配置版本，取消
        /// Parameter6：验证码
        /// Parameter7：随机数
        /// </param>
        /// <returns></returns>
        [HttpPost, Route("Login")]
        public JsonActionResult<OPUserLoginBaseModel> Login([FromBody] KeywordFilter filter)
        {
            return base.SafeExecute(() =>
            {

                OPUserLoginBaseModel result = new OPUserLoginModel();
                var orgFilter = new BaseFilter();
                orgFilter.IgnoreOrgRule = true;
                #region 验证码验证
                if (!string.IsNullOrEmpty(filter.Parameter6) && !string.IsNullOrEmpty(filter.Parameter7))
                {
                    var verCode = CsRedisManager.StringGet(SessionKey.VERIFY_CODE + filter.Parameter7);
                    if (verCode == null)
                    {
                        this.ThrowError("020010");
                    }
                    if (filter.Parameter6.ToUpper() != verCode.ToUpper())
                    {
                        this.ThrowError("020004");
                    }
                }
                #endregion
                string userId = filter == null ? string.Empty : filter.Keyword;
                int platformType = filter == null ? (int)PFPlatTypeEnum.后台 : string.IsNullOrEmpty(filter.Parameter3)
                ? (int)PFPlatTypeEnum.后台 : Convert.ToInt32(filter.Parameter3);
                //bool ingoreLoginLog = LibUtils.ToBoolean(filter.Parameter7);//是否忽略登入日志
                //bool isPlatformLogin = LibUtils.ToBoolean(filter.Parameter8);//是否平台登录
                //int formConfigVersion = LibUtils.ToInt(filter.Parameter5);//当前表单配置版本
                string orgId = filter.Parameter4;
                if (string.IsNullOrEmpty(orgId))
                {
                    throw new Exception(ErrMsg.FM_NO_ORG);
                }
                #region 校验账号密码
                if (string.IsNullOrEmpty(userId))
                {
                    string userCode = filter.Parameter1;
                    string userPassword = filter.Parameter2.ToUpper();
                    string userPasswordLower = filter.Parameter2.ToLower();
                    if (string.IsNullOrEmpty(userCode))
                    {
                        throw new Exception(ErrMsg.FM_NO_USER);
                    }
                    if (string.IsNullOrEmpty(userPassword))
                    {
                        throw new Exception(ErrMsg.FM_NO_PWD);
                    }
                    orgFilter.SelectField = new string[] { "CODE" };
                    var user = this.GetEntity<T_OP_USER>(t => ((t.CODE == userCode && (
                    t.PASSWORD == userPassword || t.PASSWORD == userPasswordLower))), orgFilter);
                    if (user == null)
                        throw new Exception(ErrMsg.PM_PSD_ERROR);
                    userId = user.ID.ToString();

                }
                #endregion
                //暂时无角色
                //var userService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IOPUserService>();
                //var useRoleModel = userService.GetRolesByUser(new Guid(userId), new Guid(orgId));

                //if (useRoleModel == null)
                //    return null;
                //if (useRoleModel.User.ENABLE_STATUS == (int)FMEnableStatusEnum.禁用)
                //    throw new Exception(ErrMsg.FM_USER_UNABLE);            
                //if (useRoleModel.User.CODE.Contains("System"))
                //    throw new Exception("不允许系统账号手动登入");
                //if (useRoleModel.User.Nav_Org != null && useRoleModel.User.Nav_Org.ENABLE_STATUS == 1)
                //    throw new Exception("当前组织已停用不允许登入");

                //if (platformType == (int)PFPlatTypeEnum.客户端)
                //    result = new UserClientLoginModel();
                //else if (platformType == (int)PFPlatTypeEnum.APP)
                //    result = new UserAppLoginModel();            
                var useModel = this.GetEntities<T_OP_USER>(x => x.ID == new Guid(userId), orgFilter).FirstOrDefault(); ;
                if (useModel.ENABLE_STATUS == (int)FMEnableStatusEnum.禁用)
                {
                    throw new Exception(ErrMsg.FM_USER_UNABLE);
                }
                result.User = useModel;
                result.BaseConfig = this.GetEntitiesByRedis<T_FM_BASE_CONFIG>(new BaseFilter(new Guid(orgId))).FirstOrDefault();

                result.Nav_RolePerm = new RolePerm();

                // List<T_FM_ROLE> roleList = new List<T_FM_ROLE>();
                List<Guid> menuIds = new List<Guid>();
                //获取角色信息
                //if (useRoleModel.Roles != null && useRoleModel.Roles.Any())
                //{
                //    foreach (var item in useRoleModel.Roles)
                //    {
                //        if (item.PLATFORM_TYPE != platformType) continue;
                //        if (item.ROLE_TYPE == (int)FMRoleTypeEnum.管理角色)
                //        {
                //            result.UserType = (int)PFUserTypeEnum.管理员;
                //            menuIds.Clear();
                //            break;
                //        }
                //        else if (item.Nav_MenuPermissions != null && item.Nav_MenuPermissions.Count != 0)
                //        {
                //            var menus = item.Nav_MenuPermissions.Select(i => i.MENU_ID ?? Guid.Empty).Distinct().ToList();
                //            menuIds.AddRange(menus);
                //            menuIds = menuIds.Distinct().ToList();                           
                //        }                      
                //        roleList.Add(item);
                //    }
                //}
                // result.Roles = roleList;
                //result.CanMenuRework = roleList.Any(t => t.CAN_CHANGE_REWORK);

                //获取授权信息
                //if (useRoleModel.Nav_RolePerm != null)
                //{
                //    var srcRolePerm = useRoleModel.Nav_RolePerm;
                //    RolePerm rolePerm = new RolePerm();
                //    if (srcRolePerm.Nav_RolePermForms != null && srcRolePerm.Nav_RolePermForms.Any())
                //    {
                //        var tmpList = srcRolePerm.Nav_RolePermForms.Where(t => t.Nav_PermForm != null && t.Nav_PermForm.PLATFORM_TYPE == platformType).ToList();
                //        if (tmpList.Any())
                //            tmpList.ForEach(t => rolePerm.Nav_RolePermForms.Add(t));
                //    }

                //    if (srcRolePerm.Nav_RolePermPanels != null && srcRolePerm.Nav_RolePermPanels.Any())
                //        srcRolePerm.Nav_RolePermPanels.ForEach(t => rolePerm.Nav_RolePermPanels.Add(t));
                //    if (srcRolePerm.Nav_RolePermWorkStages != null && srcRolePerm.Nav_RolePermWorkStages.Any())
                //        srcRolePerm.Nav_RolePermWorkStages.ForEach(t => rolePerm.Nav_RolePermWorkStages.Add(t));
                //    result.Nav_RolePerm = rolePerm;
                //}
                BaseFilter baseFilter = new BaseFilter();
                baseFilter.IgnoreOrgRule = true;
                baseFilter.Sort = "NUM";
                baseFilter.Order = DbOrder.ASC;
                baseFilter.OrgType = FilterOrgTypeEnum.仅本组织;
                baseFilter.Level = -1;
                baseFilter.IsParentData = true;
                if (platformType == (int)PFPlatTypeEnum.后台)
                {

                    //baseFilter.Level = -1;

                    OPUserLoginModel tmp = result as OPUserLoginModel;
                    //tmp.WorkStages = stages;
                    Expression<Func<T_OP_MENU, bool>> expression = t => t.ORG_ID == result.User.ORG_ID
                    && t.ENABLE_STATUS != (int)FMEnableStatusEnum.禁用;
                    //if (result.UserType != (int)PFUserTypeEnum.管理员)
                    //{
                    //    expression = expression.And(t => menuIds.Contains(t.ID));
                    //}

                    var menuList = this.GetTreeOrderEntities<T_OP_MENU>(expression, baseFilter, new string[] { "Nav_MenuForm" }).ToList();
                    RemoveDisable(menuList);

                    tmp.Menus = menuList;
                    var keyPer = "Style_";
                    if (CsRedisManager.KeyExists(keyPer + userId.ToString()))
                    {
                        result.ShowStyle = CsRedisManager.StringGet<int>(keyPer + userId.ToString());
                    }
                    else
                    {
                        result.ShowStyle = 0;
                    }
                }
                result.UserType = 99;
                //else if (platformType == (int)PFPlatTypeEnum.客户端)
                //{
                //    UserClientLoginModel tmp = result as UserClientLoginModel;
                //    if (useRoleModel.User.PERSON_ID != null)
                //    {
                //        var team = this.GetEntity<T_FM_TEAM>(i => i.Nav_TeamPersons.Any(x => x.PERSON_ID == useRoleModel.User.PERSON_ID),
                //            "Nav_TeamNodes.Nav_MeterNode");
                //        tmp.Team = team;
                //    }
                //    //tmp.WorkStages = stages;
                //    Expression<Func<T_PF_CLIENT_MENU, bool>> expression = t => t.ORG_ID == result.User.ORG_ID
                //    && t.IS_LEAF
                //    && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
                //    if (result.UserType != (int)PFUserTypeEnum.管理员)
                //        expression = expression.And(t => menuIds.Contains(t.ID));
                //    var menuList = this.GetTreeOrderEntities<T_PF_CLIENT_MENU>(expression, baseFilter, new string[] { "Nav_MenuForm" }).ToList();
                //    tmp.Menus = menuList;
                //    RemoveDisable(menuList);
                //    if (menuList != null && menuList.Any())
                //    {
                //    }

                //}
                //else if (platformType == (int)PFPlatTypeEnum.APP)
                //{
                //    UserAppLoginModel tmp = result as UserAppLoginModel;
                //    //tmp.WorkStages = stages;
                //    Expression<Func<T_PF_APPMENU, bool>> expression = t => t.ORG_ID == result.User.ORG_ID
                //    && t.ENABLE_STATUS != (int)FMEnableStatusEnum.禁用;
                //    if (result.UserType != (int)PFUserTypeEnum.管理员)
                //        expression = expression.And(t => menuIds.Contains(t.ID));
                //    var menuList = this.GetTreeOrderEntities<T_PF_APPMENU>(expression, baseFilter, new string[] { "Nav_MenuForm" }).ToList();
                //    tmp.Menus = menuList;
                //    RemoveDisable(menuList);                  
                //}
                return result;
            });
        }

        //public RolePerm GetRolePerm()
        //{
        //    RolePerm rolePerm = new RolePerm();
        //    foreach (var item in collection)
        //    {
        //        RolePermForm form = new RolePermForm();
        //        form.PermFormId = menu.PERMISSION_FORM_ID;
        //        form.MenuId = menu.MENU_ID ?? Guid.Empty;
        //        form.Nav_PermForm = menu.Nav_PermissionForm;
        //        rolePerm.Nav_RolePermForms.Add(form);
        //    }

        //    return rolePerm;
        //}
        private static void RemoveDisable(IList<TreeNode<T_OP_MENU>> menuList)
        {
            for (var x = menuList.Count - 1; x >= 0; x--)
            {
                if (menuList[x].Node.ENABLE_STATUS == (int)FMEnableStatusEnum.禁用)
                {
                    menuList.RemoveAt(x);
                }
                else
                {
                    if (menuList[x].Children != null && menuList[x].Children.Any())
                    {
                        RemoveDisable(menuList[x].Children);
                    }
                }
            }
        }


        
    }
}
