using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Entities.PF;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.IServices.OP;
using APT.BaseData.Domain.Msg;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.MS.Domain.ApiModel;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.SC.PT;
using APT.MS.Domain.Entities.SC.SC;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Entities.SK;
using APT.MS.Domain.Enums;
using APT.Utility;
using Castle.Core.Internal;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;

namespace APT.FM.WebApi.Controllers.Api.FM
{
    /// <summary>
    /// 用户转移管理接口
    /// </summary>
    [Route("api/FM/FMUserTransfer")]
    public class FMUserTransferController : AuthorizeApiController<T_FM_USER_TRANSFER>
    {
        //IFMUserService UserService { get; set; }
        //IFMDepartmentService DepartmentService { get; set; }
        //IFMNotificationTaskService NotificationTaskService { get; set; }
        //IOPTenantDBConnService OPTenantDBConnService { get; set; }
        IOPTenantDBConnService TenantDBConnService { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tenantDBConnService"></param>
        public FMUserTransferController(IOPTenantDBConnService tenantDBConnService)
        {
            //IFMUserService personnelService, IFMDepartmentService departmentService, IFMNotificationTaskService notificationTaskService, IOPTenantDBConnService opTenantDBConnService
            //UserService = personnelService;
            //DepartmentService = departmentService;
            //NotificationTaskService = notificationTaskService;
            //OPTenantDBConnService = opTenantDBConnService;
            TenantDBConnService = tenantDBConnService;
        }

        /// <summary>
        /// 公司级人员调整
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetUserInfoByCode")]
        public JsonActionResult<T_FM_USER_TRANSFER> GetUserInfoByCode([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                if (string.IsNullOrEmpty(filter.Keyword))
                {
                    return null;
                }
                T_OP_ALLUSER modelAllUser = null;
                using (var context = new MigrationContext())
                {
                    modelAllUser = context.GetEntity<T_OP_ALLUSER>(e => e.CODE == filter.Keyword && !e.IS_DELETED, null, null);
                }
                if (modelAllUser == null)
                {
                    return null;//没找到此登录账号
                }
                if (!modelAllUser.ORG_ID.HasValue)
                {
                    throw new Exception("用户信息异常！");
                }
                T_FM_USER_TRANSFER result = null;
                string connOld = TenantDBConnService.GetConnByORGID(modelAllUser.ORG_ID.Value);
                T_FM_USER modelU = null;
                T_FM_DEPARTMENT modelDep = null;
                T_FM_DEPARTMENT modelDepCom = null;
                T_FM_USER_POST modelPost = null;

                using (var context = new MigrationContext(connOld))
                {
                    modelU = context.GetEntity<T_FM_USER>(e => e.CODE == filter.Keyword && !e.IS_DELETED, null, null);

                    if (modelU == null)
                    {
                        throw new Exception("数据异常");
                    }
                    if (modelU.PERSON_ID.HasValue)
                    {
                        var person = context.GetEntity<T_FM_PERSON>(e => e.ID == modelU.PERSON_ID.Value, null, "Nav_DepartMent", "Nav_Post");
                        modelDep = person.Nav_DepartMent;
                        modelPost = person.Nav_Post;
                    }

                    if (modelDep != null && !modelDep.PARENT_ID.HasValue && modelDep.DEPARTMENT_TYPE == 5)
                    {
                        modelDepCom = modelDep;
                    }
                    else
                    {
                        modelDepCom = context.GetEntity<T_FM_DEPARTMENT>(e => e.DEPARTMENT_TYPE == 5 && !e.PARENT_ID.HasValue, null, null);
                    }
                }
                result = new T_FM_USER_TRANSFER();
                if (modelDepCom != null)
                {
                    result.COMPANYNAME_OLD = modelDepCom.NAME;
                }
                if (modelDep != null)
                {
                    result.DEPARTMENTNAME_OLD = modelDep.NAME;
                    result.DEPARTMENT_ID_OLD = modelDep.ID;
                }
                if (modelPost != null)
                {
                    result.POST_ID_OLD = modelPost.ID;
                    result.POSTNAME_OLD = modelPost.NAME;
                }
                result.NAME = modelU.NAME;
                result.CODE = modelU.CODE;
                result.USER_ID_OLD = modelU.ID;
                result.ORG_ID_OLD = modelU.ORG_ID;
                return result;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedDEP")]
        public PagedActionResult<T_FM_DEPARTMENT> OrderPagedDEP([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_DEPARTMENT> result)
            {
                Guid ORGIDNEW = Guid.Empty;
                string NAME = string.Empty;
                if (pageFilter.FilterGroup != null && pageFilter.FilterGroup.Rules.Count() > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "Parameter22" && item.Value != null)
                        {
                            try
                            {
                                ORGIDNEW = new Guid(item.Value.ToString());
                            }
                            catch { ORGIDNEW = Guid.Empty; }
                        }
                        else if (item.Field == "NAME" && item.Value != null)
                        {
                            NAME = item.Value.ToString();
                        }
                    }
                }
                if (string.IsNullOrEmpty(NAME) && pageFilter.FilterGroup.Groups.Count() > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Groups)
                    {
                        foreach (var itemu in item.Rules)
                        {
                            if (itemu.Field == "NAME" && itemu.Value != null)
                            {
                                NAME = itemu.Value.ToString();
                            }
                        }
                    }
                }
                if (ORGIDNEW == Guid.Empty)
                {
                    throw new Exception("请先选择转入公司后再选择！");
                }

                string conn = TenantDBConnService.GetConnByORGID(ORGIDNEW);
                using (var context = new MigrationContext(conn))
                {
                    Dictionary<string, DbOrder> dic = new Dictionary<string, DbOrder>();
                    dic.Add("DEPARTMENT_TYPE", DbOrder.ASC);
                    Expression<Func<T_FM_DEPARTMENT, bool>> expression = e => !e.IS_DELETED && e.ENABLE_STATUS == 0;
                    if (!string.IsNullOrEmpty(NAME))
                    {
                        expression = expression.And(e => e.NAME.Contains(NAME));
                    }
                    var data = context.GetOrderEntities<T_FM_DEPARTMENT>(expression, dic, null, null);
                    result.Data = data.Skip(pageFilter.Start).Take(pageFilter.Limit).ToList();
                    result.TotalCount = data.Count();
                }
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedUPost")]
        public PagedActionResult<T_FM_USER_POST> OrderPagedUPost([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_USER_POST> result)
            {
                Guid ORGIDNEW = Guid.Empty;
                string NAME = string.Empty;
                if (pageFilter.FilterGroup != null && pageFilter.FilterGroup.Rules.Count() > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "Parameter22" && item.Value != null)
                        {
                            try
                            {
                                ORGIDNEW = new Guid(item.Value.ToString());
                            }
                            catch { ORGIDNEW = Guid.Empty; }
                        }
                        else if (item.Field == "NAME" && item.Value != null)
                        {
                            NAME = item.Value.ToString();
                        }
                    }
                }
                if (string.IsNullOrEmpty(NAME) && pageFilter.FilterGroup.Groups.Count() > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Groups)
                    {
                        foreach (var itemu in item.Rules)
                        {
                            if (itemu.Field == "NAME" && itemu.Value != null)
                            {
                                NAME = itemu.Value.ToString();
                            }
                        }
                    }
                }
                if (ORGIDNEW == Guid.Empty)
                {
                    throw new Exception("请先选择转入公司后再选择！");
                }

                string conn = TenantDBConnService.GetConnByORGID(ORGIDNEW);
                using (var context = new MigrationContext(conn))
                {
                    Dictionary<string, DbOrder> dic = new Dictionary<string, DbOrder>();
                    dic.Add("NAME", DbOrder.ASC);
                    Expression<Func<T_FM_USER_POST, bool>> expression = e => !e.IS_DELETED;
                    if (!string.IsNullOrEmpty(NAME))
                    {
                        expression = expression.And(e => e.NAME.Contains(NAME));
                    }
                    var data = context.GetOrderEntities(expression, dic, null, null);
                    result.Data = data.Skip(pageFilter.Start).Take(pageFilter.Limit).ToList();
                    result.TotalCount = data.Count();
                }
            });
        }


        /// <summary>
        /// 检查更新 （分为主要检查人/非主要检查人 ） 更新 审批流参考  EvaluvationPlanController AddFullUpdate 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FM_USER_TRANSFER entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    throw new Exception("工号不能为空！");
                }
                if (entity.REMARK != null && entity.REMARK.Length > 200)
                {
                    throw new Exception("请精简备注到200字以内！");
                }
                //if (entity.STATUS == PFStandardStatus.Draft)
                //{
                //    entity.CREATE_TIME = DateTime.Now;
                //    entity.USERNAME_TRANSFER = APT.Infrastructure.Api.AppContext.CurrentSession.UserName;
                //    this.UnifiedCommit(() =>
                //    {
                //        UpdateEntityNoCommit(entity);
                //    });
                //    return true;
                //}
                if (string.IsNullOrEmpty(entity.COMPANYNAME))
                {
                    throw new Exception("请选择转入公司");
                }
                if (string.IsNullOrEmpty(entity.DEPARTMENTNAME) || entity.DEPARTMENT_ID == Guid.Empty)
                {
                    throw new Exception("请选择新组织");
                }

                if (entity.ORG_ID_OLD == Guid.Empty || entity.ORG_ID_NEW == Guid.Empty)
                {
                    throw new Exception("获取数据异常，请重新操作");
                }
                else if (entity.ORG_ID_OLD == entity.ORG_ID_NEW)
                {
                    throw new Exception("公司内部的转移请勿在此处操作！");
                }

                //人员组织调动
                //判断 工号 新公司 是否存在 

                //原公司 账户禁用  T_FM_USER  T_FM_PERSON
                //数据 变更 ORGID 存入 新组织  配置基础权限
                // ops T_OP_ALLUSER TENANT 修改
                //保存本次的操作数据
                Guid guidAdmid = new Guid("11111111-1111-1111-1111-111111111111");
                string connOld = TenantDBConnService.GetConnByORGID(entity.ORG_ID_OLD.Value);
                string connNEW = TenantDBConnService.GetConnByORGID(entity.ORG_ID_NEW.Value);

                T_FM_TEAM modelT = null;
                if (entity.DEPARTMENT_ID.HasValue)
                {
                    using (var context = new MigrationContext(connNEW))
                    {
                        var modelND = context.GetEntity<T_FM_DEPARTMENT>(e => e.ID == entity.DEPARTMENT_ID.Value, null, null);
                        if (modelND.DEPARTMENT_TYPE == 20)
                        {
                            modelT = context.GetEntity<T_FM_TEAM>(e => e.DEPARTMENT_ID == entity.DEPARTMENT_ID.Value, null, null);
                            if (modelT == null)
                            {
                                throw new Exception("请先到转入组织架构添加班组！");
                            }
                        }
                    }
                }


                T_FM_USER modelNwe = null;
                IEnumerable<T_FM_USER> listUserCheck = null;
                using (var context = new MigrationContext(connNEW))
                {
                    listUserCheck = context.GetEntities<T_FM_USER>(e => e.CODE == entity.CODE, null, null);
                }
                if (listUserCheck != null && listUserCheck.Count() > 0)
                {
                    //如果有 并且名字一样 直接启用
                    //否则 直接提示 然后需要管理员操作
                    var userNCheck = listUserCheck.FirstOrDefault(e => e.ENABLE_STATUS == 0);
                    if (userNCheck != null)
                    {
                        throw new Exception("转入公司该账号【" + entity.CODE + "】有对应启用用户，请联系管理员！");
                    }

                    userNCheck = listUserCheck.FirstOrDefault(e => e.NAME == entity.NAME);//工号 姓名相同 定位为同一个人
                    if (userNCheck != null)
                    {
                        entity.USER_ID = userNCheck.ID;//账号重新被启用
                        modelNwe = userNCheck;
                    }
                }

                T_FM_USER modelUOld = null;
                T_FM_PERSON modelPOld = null;// 有  新组织需要新增  无（新公司有数据 人员信息无需处理）
                using (var context = new MigrationContext(connOld))
                {
                    modelUOld = context.GetEntity<T_FM_USER>(e => e.ID == entity.USER_ID_OLD, null, "Nav_Person");
                    modelPOld = modelUOld.Nav_Person;

                    if (entity.USER_ID == Guid.Empty && modelPOld == null)
                    {
                        throw new Exception("获取信息有误！");
                    }

                    modelUOld.Nav_Person = null;
                    modelUOld.ENABLE_STATUS = 1;
                    modelUOld.APPROVE_ROLE_ID = null;
                    modelUOld.TEAM_ID = null;
                    modelUOld.PROJECT_ID = null;
                    modelUOld.USER_TYPE_ID = null;

                    modelUOld.ISTRANSFER = true;//处理信息
                    modelUOld.MODIFY_TIME = DateTime.Now;
                    modelUOld.MODIFIER_ID = guidAdmid; //APT.Infrastructure.Api.AppContext.CurrentSession.UserID;

                    context.Update(modelUOld);
                    context.SaveChanges();
                }

                //用户信息
                if (entity.USER_ID == Guid.Empty)
                {
                    modelUOld.CREATER_ID = guidAdmid;
                    modelPOld.CREATER_ID = guidAdmid;
                    modelUOld.CREATE_TIME = DateTime.Now;
                    modelPOld.CREATE_TIME = DateTime.Now;
                }
                modelUOld.ENABLE_STATUS = 0;
                modelUOld.ORG_ID = entity.ORG_ID_NEW;
                modelUOld.MODIFY_TIME = DateTime.Now;
                modelUOld.MODIFIER_ID = guidAdmid; //APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                modelUOld.DEPARTMENT_ID = entity.DEPARTMENT_ID;


                //人员信息
                modelPOld.ORG_ID = entity.ORG_ID_NEW;
                modelPOld.MODIFY_TIME = DateTime.Now;
                modelPOld.MODIFIER_ID = guidAdmid; //APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                modelPOld.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                modelPOld.POST_ID = entity.POST_ID;
                string nameCom = string.Empty;
                using (var context = new MigrationContext(connNEW))
                {
                    var depC = context.GetEntity<T_FM_DEPARTMENT>(e => e.DEPARTMENT_TYPE == 5 && !e.IS_DELETED && e.ENABLE_STATUS == 0, null, null);
                    if (depC != null)
                    {
                        nameCom = depC.NAME;
                    }
                    modelUOld.ISTRANSFER = false;
                    if (entity.USER_ID != Guid.Empty)
                    {
                        context.Update(modelUOld);
                        context.Update(modelPOld);
                    }
                    else
                    {
                        var lisrRole = context.GetEntities<T_FM_ROLE>(e => e.ISDEFAULT && !e.ISDEFAULT, null, null);
                        List<T_FM_USER_BELONG_ROLE> listRole = null;
                        if (lisrRole != null && lisrRole.Count() > 0)
                        {
                            listRole = new List<T_FM_USER_BELONG_ROLE>();
                            foreach (var item in lisrRole)
                            {
                                listRole.Add(new T_FM_USER_BELONG_ROLE()
                                {
                                    ID = Guid.NewGuid(),
                                    ORG_ID = modelUOld.ORG_ID,
                                    USER_ID = modelUOld.ID,
                                    BELONG_ROLE_ID = item.ID,
                                    CREATE_TIME = DateTime.Now,
                                    CREATER_ID = guidAdmid,
                                    MODIFIER_ID = guidAdmid
                                });
                            }
                        }

                        //如果是班组级 有 T_FM_TEAM 表 直接添加 T_FM_TEAM_PERSON 表
                        T_FM_TEAM_PERSON teamPerson = null;
                        if (modelT != null)
                        {
                            teamPerson = new T_FM_TEAM_PERSON();
                            teamPerson.ORG_ID = modelUOld.ORG_ID;
                            teamPerson.ID = Guid.NewGuid();
                            teamPerson.TEAM_ID = modelT.ID;//new Guid(filter.Parameter3);
                            teamPerson.PERSON_ID = modelPOld.ID;
                            teamPerson.CREATE_TIME = DateTime.Now;
                            teamPerson.CREATER_ID = guidAdmid;
                            teamPerson.MODIFIER_ID = guidAdmid;
                        }

                        if (teamPerson != null)
                            context.Add(teamPerson);
                        context.Add(modelUOld);
                        context.Add(modelPOld);
                        if (listRole != null)
                            context.AddEntities(listRole);
                    }
                    context.SaveChanges();
                }

                using (var context = new MigrationContext())
                {
                    var modelAll = context.GetEntity<T_OP_ALLUSER>(e => e.CODE == entity.CODE, null, null);
                    modelAll.ORG_ID = entity.ORG_ID_NEW;
                    modelAll.TENANT = entity.ORG_ID_NEW.Value.ToString().Substring(0, 3);
                    modelAll.MODIFY_TIME = DateTime.Now;
                    modelAll.MODIFIER_ID = guidAdmid;
                    context.Update(modelAll);
                    context.SaveChanges();
                }

                ////保存单数据  
                ////检查数据 isCheck=false 不然获取数据可能会有问题
                if (!string.IsNullOrEmpty(nameCom))
                {
                    entity.COMPANYNAME = nameCom;
                }
                entity.USER_ID = modelUOld.ID;
                entity.CREATE_TIME = DateTime.Now;
                entity.USERNAME_TRANSFER = APT.Infrastructure.Api.AppContext.CurrentSession.UserName;
                this.UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                });
                return true;
            });
        }

    }
}
