using APT.BaseData.Domain.Msg;
using APT.Infrastructure.Core;
using APT.MS.Domain.ApiModel;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices.FM;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

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

namespace APT.FM.WebApi.Controllers.Api.FM
{

    /// <summary>
    /// 用户管理接口
    /// </summary>
    [Route("api/FM/User")]
    public class UserController : AuthorizeApiController<T_FM_USER>
    {
        IFMUserService UserService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="personnelService"></param>
        public UserController(IFMUserService personnelService, IFMDepartmentService departmentService, IFMNotificationTaskService notificationTaskService)
        {
            UserService = personnelService;
            DepartmentService = departmentService;
            NotificationTaskService = notificationTaskService;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_FM_USER>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// 

        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_FM_USER>> OrderEntities([FromBody] KeywordFilter filter)
        {
            var result = WitOrderEntities(null, filter);
            if (result.Data.Count() > 0)
            {
                result.Data = result.Data.Where(t => t.CODE != "admin" && t.ENABLE_STATUS == 0);
            }
            return result;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_FM_USER> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FM_USER> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            if (string.IsNullOrEmpty(pageFilter.Parameter1))
            {
                var result = WitOrderPaged(null, pageFilter);
                if (result.Data.Count() > 0)
                {
                    result.Data = result.Data.Where(t => t.CODE != "admin" && t.ENABLE_STATUS == 0);
                }
                return result;
            }
            else
            {
                var result = WitOrderPaged(t => t.Nav_BelongRoles.Any(i => i.Nav_BelongRole.NAME.Contains(pageFilter.Parameter1)), pageFilter);
                if (result.Data.Count() > 0)
                {
                    result.Data = result.Data.Where(t => t.CODE != "admin" && t.ENABLE_STATUS == 0);
                }
                return result;
            }

        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedNew")]
        public PagedActionResult<T_FM_USER> OrderPagedNew([FromBody] KeywordPageFilter pageFilter)
        {
            Expression<Func<T_FM_USER, bool>> express = t => !t.CODE.Contains("admin");

            if (!string.IsNullOrEmpty(pageFilter.Parameter1))
            {
                express = express.And(t => t.Nav_BelongRoles.Any(i => i.Nav_BelongRole.NAME.Contains(pageFilter.Parameter1)));
            }
            var result = this.WitOrderPaged(express, pageFilter);
            return result;
            //if (string.IsNullOrEmpty(pageFilter.Parameter1))
            //{
            //    var result = WitOrderPaged(null, pageFilter);
            //    if (result.Data.Count() > 0)
            //    {
            //        result.Data = result.Data.Where(t => t.CODE != "admin");
            //    }
            //    return result;
            //}
            //else
            //{
            //    var result = WitOrderPaged(t => t.Nav_BelongRoles.Any(i => i.Nav_BelongRole.NAME.Contains(pageFilter.Parameter1)), pageFilter);
            //    if (result.Data.Count() > 0)
            //    {
            //        result.Data = result.Data.Where(t => t.CODE != "admin");
            //    }
            //    return result;
            //}

        }
        /// <summary>
        /// 查询(当前人员层级及以下层级)
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedAuthority")]
        public PagedActionResult<T_FM_USER> OrderPagedAuthority([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FM_USER>();
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var admiId = this.GetEntity<T_FM_USER>(t => t.CODE == "admin")?.ID;
            if (loginUserId == null || loginUserId == admiId)
            {
                result = WitOrderPaged(null, pageFilter); ;
                if (result.Data.Count() > 0)
                {
                    result.Data = result.Data.Where(t => t.CODE != "admin" && t.ENABLE_STATUS == 0);
                }
            }
            else
            {
                var loginDepartmentId = this.GetEntity<T_FM_USER>(loginUserId.ToString())?.DEPARTMENT_ID;
                List<Guid> departmentId = new List<Guid>();
                departmentId.Add((Guid)loginDepartmentId);
                List<Guid> departmentIds = new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    departmentIds = departmentIds.Distinct().ToList();
                    result = this.WitOrderPaged(t => (t.DEPARTMENT_ID != null && departmentIds.Contains(t.DEPARTMENT_ID.Value)), pageFilter);//|| dataIds.Contains(t.ID)
                    if (result.Data.Count() > 0)
                    {
                        result.Data = result.Data.Where(t => t.CODE != "admin" && t.ENABLE_STATUS == 0);
                    }
                }
                else
                    result.Data = null;
            }
            return result;
        }
        /// <summary>
        /// 重写用户查询接口
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedWithTeam")]
        public PagedActionResult<T_FM_USER> OrderPagedWithTeam([FromBody] KeywordPageFilter pageFilter)
        {
            //pageFilter.Include.Add("Nav_Person.Nav_TeamPersons.Nav_Team");
            //var result =new PagedActionResult<T_FM_USER>();
            return SafeGetPagedData<T_FM_USER>((ret) =>
            {
                Expression<Func<T_FM_USER, bool>> express = t => true;

                if (!string.IsNullOrEmpty(pageFilter.Parameter1))
                {
                    express = express.And(t => t.Nav_BelongRoles.Any(i => i.Nav_BelongRole.NAME.Contains(pageFilter.Parameter1)) && t.ENABLE_STATUS == 0);

                }
                if (!string.IsNullOrEmpty(pageFilter.Parameter2))
                {
                    express = express.And(t => t.Nav_Person.Nav_TeamPersons.Any(i => i.Nav_Team.NAME.Contains(pageFilter.Parameter2)) && t.ENABLE_STATUS == 0);
                }
                var result = this.GetOrderPageEntities<T_FM_USER>(express, pageFilter);
                //var teamPerson = result.Data.Where(t => t.Nav_Person != null && t.Nav_Person.Nav_TeamPersons != null);
                //var teamInfos = new List<T_FM_TEAM>();
                //var departmentInfos = new List<T_FM_DEPARTMENT>();
                //var parentInfos = new List<T_FM_DEPARTMENT>();
                //if (teamPerson != null && teamPerson.Any())
                //{
                //    var teamIds = new List<Guid>();
                //    teamPerson.ForEach(t =>
                //    {
                //        if (t.Nav_Person.Nav_TeamPersons.Count() > 0)
                //            teamIds.Add(t.Nav_Person.Nav_TeamPersons.FirstOrDefault().TEAM_ID);
                //    });
                //    teamInfos=this.GetEntities<T_FM_TEAM>(t => teamIds.Contains(t.ID),new BaseFilter(pageFilter.OrgId)).ToList();

                //    var departmentIds=teamInfos.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                //    departmentInfos = this.GetEntities<T_FM_DEPARTMENT>(t => departmentIds.Contains(t.ID), new BaseFilter(pageFilter.OrgId)).ToList();
                //    var parentIds = departmentInfos.Select(t => t.PARENT_ID).Distinct().ToList();
                //    parentInfos = this.GetEntities<T_FM_DEPARTMENT>(t => parentIds.Contains(t.ID), new BaseFilter(pageFilter.OrgId),new string[] { "Nav_Parent" }).ToList();

                //}
                foreach (var item in result.Data)
                {
                    if (item.Nav_Person?.Nav_TeamPersons != null && item.Nav_Person?.Nav_TeamPersons?.Count > 0)
                    {
                        item.TEAMNAME = string.Join(",", item.Nav_Person.Nav_TeamPersons.Select(i => i.Nav_Team?.NAME));
                        //item.TEAM_ID = item.Nav_Person.Nav_TeamPersons.FirstOrDefault().TEAM_ID;
                    }
                    //if (item.TEAM_ID != null)
                    //{
                    //    var teamInfo = teamInfos.FirstOrDefault(t => t.ID == item.TEAM_ID);
                    //    var departmentInfo = departmentInfos.FirstOrDefault(t => t.ID == teamInfo?.DEPARTMENT_ID);
                    //    var parentInfo = parentInfos.FirstOrDefault(t => t.ID == departmentInfo?.PARENT_ID);
                    //    item.Nav_Department = parentInfo;
                    //    //item.Nav_Department.Nav_Parent = departmentInfo.Nav_Parent;
                    //}
                }
                ret.TotalCount = result.TotalCount;
                ret.Data = result.Data;
                //return result;
            });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Delete")]
        public JsonActionResult<bool> Delete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                var user = this.GetEntity<T_FM_USER>(x => x.ID == new Guid(id), new string[] { "Nav_BelongRoleGroups", "Nav_BelongRoles", "Nav_BelongUserGroups", "Nav_UserPhotoFiles" });
                var belongRoleGroups = user.Nav_BelongRoleGroups.Select(x => x.ID).ToList();
                var belongRoles = user.Nav_BelongRoles.Select(x => x.ID).ToList();
                var belongUserGroups = user.Nav_BelongUserGroups.Select(x => x.ID).ToList();
                var userPhoto = user.Nav_UserPhotoFiles.Select(x => x.ID).ToList();
                this.UnifiedCommit(() =>
                {
                    if (belongRoles.Any())
                    {
                        BantchDeleteEntityNoCommit<T_FM_USER_BELONG_ROLE>(belongRoles);
                    }
                    if (belongRoleGroups.Any())
                    {
                        BantchDeleteEntityNoCommit<T_FM_USER_BELONG_ROLE_GROUP>(belongRoleGroups);
                    }
                    if (belongUserGroups.Any())
                    {
                        BantchDeleteEntityNoCommit<T_FM_USER_BELONG_USER_GROUP>(belongUserGroups);
                    }
                    if (belongRoles.Any())
                    {
                        BantchDeleteEntityNoCommit<T_FM_USER_PHOTO_FILE>(userPhoto);
                    }
                    DeleteEntityNoCommit<T_FM_USER>(id);
                    if (user.PERSON_ID != null)
                        DeleteEntityNoCommit<T_FM_PERSON>(user.PERSON_ID.ToString());
                });

                return true;
            });
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_FM_USER entity)
        {
            return SafeExecute<bool>(() =>
            {
                var isAdd = this.GetEntities<T_FM_USER>(t => t.ID == entity.ID, null);
                var userList = new List<T_FM_USER>();
                entity.CODE = entity.CODE.ToUpper();
                if (entity.ENTRYTIME == DateTime.Parse("0001/1/1 0:00:00"))
                    entity.ENTRYTIME = DateTime.Now.Date;
                T_SE_THREE_LEVEL_SAFE_EDU_CARD eduCard = null;
                List<T_FM_NOTIFICATION_TASK> sendNotice = new List<T_FM_NOTIFICATION_TASK>();
                T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD next_train_record = null;
                if (!isAdd.Any())
                {
                    if (entity.CODE.Length <= 3)
                        this.ThrowError("050003");
                    userList = this.GetEntities<T_FM_USER>(t => (t.CODE == entity.CODE || t.APPROVE_ROLE_ID == entity.APPROVE_ROLE_ID) && t.ORG_ID == entity.ORG_ID, null,"Nav_Department").ToList();
                    var isRepeat = userList.FirstOrDefault(t => t.CODE == entity.CODE);
                    if (isRepeat != null)
                        this.ThrowError("050001");
                    if (!APT.Infrastructure.Api.AppContext.CurrentSession.UserName.Contains("admin"))
                    {
                        #region 新增人员增加三级安全教育
                        eduCard = new T_SE_THREE_LEVEL_SAFE_EDU_CARD();
                        eduCard.ID = Guid.NewGuid();
                        eduCard.ID_CARD_NUMBER = entity.ID_CARD;
                        eduCard.IN_TIME = entity.ENTRYTIME;
                        eduCard.USER_ID = entity.ID;
                        eduCard.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                        eduCard.LAUNCH_TIME = DateTime.Now;
                        eduCard.ORG_ID = entity.ORG_ID;
                        eduCard.POST_ID = entity.Nav_Person.POST_ID;
                        eduCard.STATUS = SEThreeLevelSafeTrainStatus.公司培训;
                        eduCard.LAUNCH_USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        eduCard.LAUNCH_DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                        next_train_record = new T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD
                        {
                            ID = Guid.NewGuid(),
                            EDU_CARD_ID = eduCard.ID,
                            ORG_ID = eduCard.ORG_ID,
                            THREE_LEVEL_SAFE_TRAIN_TYPE = SEThreeLevelSafeTrainType.公司级
                        };
                        next_train_record.THREE_LEVEL_SAFE_TRAIN_TYPE = (SEThreeLevelSafeTrainType)eduCard.STATUS.GetInt();
                        var train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == (SEThreeLevelSafeTrainType)eduCard.STATUS.GetInt());
                        next_train_record.CONTENT_ID = train_contents.ID;
                        var postName = GetEntity<T_FM_USER_POST>(eduCard.POST_ID ?? Guid.Empty)?.NAME;
                        var sendUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                        if (sendUser != null)
                        {
                            sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + entity.NAME + "-" + eduCard.STATUS.GetDescription(), next_train_record.ID, entity.ORG_ID, sendUser.ID, sendUser.NAME, DateTime.Now, entity.ENTRYTIME.AddMonths(1), 1, "SE042"));
                        }
                        #endregion
                    }

                    #region   //wyw 密码初始化  Xyy+code（姓名拼音首字母(第一个大写)  +  工号（取数字）

                    if (!string.IsNullOrEmpty(entity.NAME) && !string.IsNullOrEmpty(entity.CODE))
                    {
                        MD5 md5 = MD5.Create();
                        string code = DataHelper.GetCodeNO(entity.CODE);
                        string nameHead = DataHelper.MkPinyinString(entity.NAME);
                        string NewPwd = DataHelper.MD5Encrypt32(md5, nameHead + code);
                        entity.PASSWORD = NewPwd;
                    }

                    #endregion
                }
                else
                {
                    userList = this.GetEntities<T_FM_USER>(t => (t.CODE == entity.CODE || t.APPROVE_ROLE_ID == entity.APPROVE_ROLE_ID) && t.ID != entity.ID && t.ORG_ID == entity.ORG_ID, null,"Nav_Department").ToList();
                    var isRepeat = userList.FirstOrDefault(t => t.CODE == entity.CODE);
                    if (isRepeat != null)
                        this.ThrowError("050001");
                }
                if (entity.DEPARTMENT_ID == null)
                {
                    throw new Exception("组织结构不允许为空!");
                }
                else
                {
                    var departInfo = this.GetEntity<T_FM_DEPARTMENT>(entity.DEPARTMENT_ID.ToString());
                    if (departInfo != null && departInfo.MineType != null && !isAdd.Any())
                    {
                        var enumList = this.GetEntity<T_FM_ENUMS>(t => t.CODE == "BSMineTypeEnum" && t.VALUE == departInfo.MineType);
                        T_FM_USER_PRODUCTION_UNIT unit = new T_FM_USER_PRODUCTION_UNIT();
                        unit.ORG_ID = entity.ORG_ID; unit.USER_ID = entity.ID; unit.ENUMS_ID = enumList?.ID;
                        unit.Nav_Enums = null;
                        entity.Nav_ProdutionUnit = new List<T_FM_USER_PRODUCTION_UNIT>();
                        entity.Nav_ProdutionUnit.Add(unit);
                    }
                }
                if (entity.DEPARTURETIME == null)
                    entity.DEPARTURETIME = DateTime.Parse("2099-01-01");
                T_FM_PERSON person = null;
                //更新人员信息
                if (entity.PERSON_ID == null)
                {
                    person = new T_FM_PERSON()
                    {
                        CODE = entity.CODE,
                        NAME = entity.NAME,
                        DEPARTMENT_ID = entity.DEPARTMENT_ID,
                        TEL = entity.PHONE,
                        ORG_ID = entity.ORG_ID,
                        POST_ID = entity.Nav_Person.POST_ID,
                        ID = Guid.NewGuid(),
                    };
                    entity.PERSON_ID = person.ID;
                }
                else
                {
                    person = this.GetEntity<T_FM_PERSON>(t => t.ID == entity.PERSON_ID);
                    person.CODE = entity.CODE;
                    person.NAME = entity.NAME;
                    person.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                    person.TEL = entity.PHONE;
                    person.POST_ID = entity.Nav_Person.POST_ID;
                }
                var personTeam = entity.Nav_Person?.Nav_TeamPersons;
                T_FM_TEAM teamInfo = null;
                T_FM_DEPARTMENT departmentInfo = null;
                List<T_FM_TEAM_PERSON> teamPersons = new List<T_FM_TEAM_PERSON>();
                List<Guid> teamPersonIds = new List<Guid>();
                if (entity.Nav_Person.POST_ID == null)
                {
                    throw new Exception("岗位不允许为空!");
                }
                if (entity.DEPARTMENT_ID != null)
                {
                    departmentInfo = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.DEPARTMENT_ID && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用);
                    if (departmentInfo == null)
                        throw new Exception("组织架构已失效，请重新选择!");
                    var teamPersonInfo = this.GetEntity<T_FM_TEAM_PERSON>(t => t.PERSON_ID == entity.PERSON_ID);
                    //if (teamPersonInfo != null)
                    //{
                    //    teamPersonIds.Add(teamPersonInfo.ID);
                    //}
                    if (departmentInfo != null && departmentInfo.DEPARTMENT_TYPE == (int)FMDepartmentType.班组)
                    {
                        teamInfo = this.GetEntity<T_FM_TEAM>(t => t.DEPARTMENT_ID == entity.DEPARTMENT_ID);
                        if (teamInfo != null)
                        {
                            if (teamPersonInfo == null)
                            {
                                T_FM_TEAM_PERSON teamPerson = new T_FM_TEAM_PERSON();
                                teamPerson.PERSON_ID = person.ID;
                                teamPerson.TEAM_ID = teamInfo.ID;
                                teamPerson.ORG_ID = teamInfo.ORG_ID;
                                teamPersons.Add(teamPerson);
                            }
                            else
                            {
                                teamPersonInfo.PERSON_ID = person.ID;
                                teamPersonInfo.TEAM_ID = teamInfo.ID;
                                teamPersons.Add(teamPersonInfo);
                            }
                        }
                        else
                        {
                            if(teamPersonInfo != null)
                                teamPersonIds.Add(teamPersonInfo.ID);
                        }
                        personTeam = teamPersons;
                        //if (entity.APPROVE_ROLE_ID != null)
                        //{
                        //    var isExist = userList.FirstOrDefault(t => t.APPROVE_ROLE_ID == entity.APPROVE_ROLE_ID && t.DEPARTMENT_ID == entity.DEPARTMENT_ID);
                        //    if (isExist != null)
                        //        this.ThrowError("070001");
                        //}
                    }
                    if (entity.APPROVE_ROLE_ID != null)
                    {
                        var isExist = userList.FirstOrDefault(t => t.APPROVE_ROLE_ID == entity.APPROVE_ROLE_ID && t.DEPARTMENT_ID == entity.DEPARTMENT_ID && t.ENABLE_STATUS == 0 && t.Nav_Department!=null && t.Nav_Department.DEPARTMENT_TYPE != 3);
                        if (isExist != null)
                            this.ThrowError("070001");
                        var roleInfo = this.GetEntity<T_PF_APPROVAL_ROLE>(entity.APPROVE_ROLE_ID.ToString());
                        if (roleInfo != null)
                        {
                            if (roleInfo.NAME.Contains("负责人") || roleInfo.NAME.Contains("总经理"))
                            {
                                departmentInfo.USER_ID = entity.ID;
                                if (teamInfo != null)
                                    teamInfo.CHARGE_PERSON_ID = entity.PERSON_ID;
                            }
                            //if (roleInfo.DEPARTMENT_TYPE != departmentInfo.DEPARTMENT_TYPE)
                            //    throw new Exception(departmentInfo.NAME +"不能设置审核角色："+ roleInfo.NAME+",组织层级不一致");
                        }
                    }
                }
                else
                    this.ThrowError("060001");
                var approveRole = this.GetEntities<T_PF_APPROVE_OPERATION_ROLE>(t => t.APPROVAL_ROLE_ID == entity.APPROVE_ROLE_ID, new BaseFilter(entity.ORG_ID));
                //List<T_FM_USER_BELONG_ROLE> roleList = new List<T_FM_USER_BELONG_ROLE>();
                if (approveRole != null && approveRole.Any())
                {
                    approveRole.ForEach(role =>
                    {
                        T_FM_USER_BELONG_ROLE belongRole = new T_FM_USER_BELONG_ROLE();
                        belongRole.USER_ID = entity.ID;
                        belongRole.BELONG_ROLE_ID = (Guid)role.ROLE_ID;
                        belongRole.ORG_ID = entity.ORG_ID;
                        //roleList.Add(belongRole);
                        entity.Nav_BelongRoles.Add(belongRole);
                    });
                }
                else
                {
                    //var role = this.GetEntity<T_FM_ROLE>(t => t.NAME == "作业员");
                    T_FM_USER_BELONG_ROLE belongRole = new T_FM_USER_BELONG_ROLE();
                    belongRole.USER_ID = entity.ID;
                    belongRole.BELONG_ROLE_ID = Guid.Parse("384d2e3b-54a2-47e9-9042-5f18a00efd81");// role.ID;
                    belongRole.ORG_ID = entity.ORG_ID;
                    //roleList.Add(belongRole);
                    entity.Nav_BelongRoles.Add(belongRole);
                }
                var roleIds = entity.Nav_BelongRoles.Select(role => role.BELONG_ROLE_ID).Distinct().ToList();
                var roleGroup = this.GetEntities<T_FM_ROLE_GROUP_BELONG_ROLE>(t => roleIds.Contains(t.BELONG_ROLE_ID), new BaseFilter(entity.ORG_ID));
                //List<T_FM_USER_BELONG_ROLE_GROUP> roleGroupList = new List<T_FM_USER_BELONG_ROLE_GROUP>();
                if (roleGroup != null && roleGroup.Any())
                {
                    roleGroup.ForEach(role =>
                    {
                        T_FM_USER_BELONG_ROLE_GROUP belongRole = new T_FM_USER_BELONG_ROLE_GROUP();
                        belongRole.USER_ID = entity.ID;
                        belongRole.BELONG_ROLE_GROUP_ID = (Guid)role.ROLE_GROUP_ID;
                        belongRole.ORG_ID = entity.ORG_ID;
                        //roleGroupList.Add(belongRole);
                        entity.Nav_BelongRoleGroups.Add(belongRole);
                    });
                }
                var belongRoleGroups = entity.Nav_BelongRoleGroups;//roleGroupList;
                var belongRoles = entity.Nav_BelongRoles;//roleList;
                var belongUserGroups = entity.Nav_BelongUserGroups;
                var userPhoto = entity.Nav_UserPhotoFiles;
                var userSign = entity.Nav_UserSignFiles;
                var productionUnit = entity.Nav_ProdutionUnit;
                entity.Nav_BelongRoleGroups = null;
                entity.Nav_BelongRoles = null;
                entity.Nav_BelongUserGroups = null;
                entity.Nav_UserPhotoFiles = null;
                entity.Nav_Person = null;
                entity.Nav_ProdutionUnit = null;
                if (belongUserGroups != null && belongUserGroups.Count > 0)
                    belongUserGroups.ForEach(t => t.USER_ID = entity.ID);
                if (belongRoleGroups != null && belongRoleGroups.Any())
                    belongRoleGroups.ForEach(t => t.USER_ID = entity.ID);
                if (belongRoles != null && belongRoles.Any())
                    belongRoles.ForEach(t => t.USER_ID = entity.ID);
                if (userPhoto != null && userPhoto.Any())
                    userPhoto.ForEach(t => t.USER_ID = entity.ID);
                if (userSign != null && userSign.Any())
                    userSign.ForEach(t => t.USER_ID = entity.ID);
                if (personTeam != null && personTeam.Count > 0)
                    personTeam.ForEach(i => i.PERSON_ID = person.ID);
                if (productionUnit != null && productionUnit.Any())
                {
                    var enumIds = productionUnit.Select(t => t.ENUMS_ID).Distinct().ToList();
                    var enumList = this.GetEntities<T_FM_ENUMS>(t => enumIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                    var enumValues = new List<string>();
                    productionUnit.ForEach(t =>
                    {
                        t.USER_ID = entity.ID; t.Nav_Enums = null;
                        var value = enumList.FirstOrDefault(m => m.ID == t.ENUMS_ID)?.VALUE.ToString();
                        enumValues.Add(value);
                    });
                }
                List<Guid> deleteBelongRoleIds = new List<Guid>();
                List<Guid> deleteBelongRoleGroupIds = new List<Guid>();
                List<Guid> deleteBelongUserGroupsIds = new List<Guid>();
                List<Guid> deletePhotoFileIds = new List<Guid>();
                List<Guid> deleteSignFileIds = new List<Guid>();
                List<Guid> deleteProductionIds = new List<Guid>();

                var dbEntity = this.GetEntity<T_FM_USER>(entity.ID.ToString(), new string[] { "Nav_BelongRoleGroups",
                    "Nav_BelongRoles", "Nav_BelongUserGroups", "Nav_UserPhotoFiles","Nav_UserSignFiles","Nav_ProdutionUnit" });
                if (dbEntity != null)
                {
                    if (dbEntity.Nav_UserPhotoFiles != null)
                    {
                        dbEntity.Nav_UserPhotoFiles.ForEach(item =>
                        {
                            deletePhotoFileIds.Add(item.ID);
                        });
                    }
                    if (dbEntity.Nav_UserSignFiles != null)
                    {
                        dbEntity.Nav_UserSignFiles.ForEach(item =>
                        {
                            deleteSignFileIds.Add(item.ID);
                        });
                    }
                    if (dbEntity.Nav_BelongRoleGroups != null)
                    {
                        dbEntity.Nav_BelongRoleGroups.ForEach(item =>
                        {
                            if (belongRoleGroups == null || !belongRoleGroups.Any(i => i.ID == item.ID))
                                deleteBelongRoleGroupIds.Add(item.ID);
                        });
                    }
                    if (dbEntity.Nav_BelongRoles != null)
                    {
                        dbEntity.Nav_BelongRoles.ForEach(item =>
                        {
                            if (belongRoles == null || !belongRoles.Any(i => i.ID == item.ID))
                                deleteBelongRoleIds.Add(item.ID);
                        });
                    }
                    if (dbEntity.Nav_BelongUserGroups != null)
                    {
                        dbEntity.Nav_BelongUserGroups.ForEach(item =>
                        {
                            if (belongUserGroups == null || !belongUserGroups.Any(i => i.ID == item.ID))
                                deleteBelongUserGroupsIds.Add(item.ID);
                        });
                    }
                    if (dbEntity.Nav_ProdutionUnit != null)
                    {
                        dbEntity.Nav_ProdutionUnit.ForEach(item =>
                        {
                            if (productionUnit == null || !productionUnit.Any(i => i.ID == item.ID))
                                deleteProductionIds.Add(item.ID);
                        });
                    }
                }

                UnifiedCommit(() =>
                {
                    if (person != null)
                        this.UpdateEntityNoCommit(person);
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (teamInfo != null)
                        this.UpdateEntityNoCommit(teamInfo);
                    if (departmentInfo != null)
                        this.UpdateEntityNoCommit(departmentInfo);
                    if (belongRoleGroups != null && belongRoleGroups.Any())
                        this.BantchSaveEntityNoCommit(belongRoleGroups);
                    if (belongRoles != null && belongRoles.Any())
                        this.BantchSaveEntityNoCommit(belongRoles);
                    if (belongUserGroups != null && belongUserGroups.Any())
                        this.BantchSaveEntityNoCommit(belongUserGroups);
                    if (userPhoto != null && userPhoto.Any())
                        this.BantchSaveEntityNoCommit(userPhoto);
                    if (userSign != null && userSign.Any())
                        this.BantchSaveEntityNoCommit(userSign);
                    if (personTeam != null && personTeam.Any())
                        this.BantchSaveEntityNoCommit(personTeam);
                    if (productionUnit != null && productionUnit.Any())
                        this.BantchSaveEntityNoCommit(productionUnit);

                    if (deleteBelongRoleIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_BELONG_ROLE>(t => deleteBelongRoleIds.Contains(t.ID));
                    if (deleteBelongRoleGroupIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_BELONG_ROLE_GROUP>(t => deleteBelongRoleGroupIds.Contains(t.ID));
                    if (deleteBelongUserGroupsIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_BELONG_USER_GROUP>(t => deleteBelongUserGroupsIds.Contains(t.ID));
                    if (deletePhotoFileIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_PHOTO_FILE>(t => deletePhotoFileIds.Contains(t.ID));
                    if (deleteSignFileIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_SIGN_FILE>(t => deleteSignFileIds.Contains(t.ID));
                    if (deleteProductionIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_PRODUCTION_UNIT>(t => deleteProductionIds.Contains(t.ID));
                    if (eduCard != null)
                        AddEntityNoCommit(eduCard);
                    if (sendNotice != null)
                        BantchAddEntityNoCommit(sendNotice);
                    if (next_train_record != null)
                        AddEntityNoCommit(next_train_record);
                    if (teamPersonIds.Any())
                        this.DeleteEntityNoCommit<T_FM_TEAM_PERSON>(t => teamPersonIds.Contains(t.ID));
                });
                return true;
            });
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet, Route("BatchDelete")]
        public JsonActionResult<bool> BatchDelete(string ids)
        {
            return WitRealBatchDelete(ids);
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_FM_USER> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }
        /// <summary>
        /// 获取人员角色信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRolesByUser")]
        public JsonActionResult<UserRoleModel> GetRolesByUser([FromBody] KeywordFilter filter)
        {
            return SafeExecute<UserRoleModel>(() =>
           {
               string userId = filter.Keyword;
               if (string.IsNullOrEmpty(userId))
                   userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserId;
               if (string.IsNullOrEmpty(userId))
                   throw new Exception("请设置用户ID");
               return UserService.GetRolesByUser(new Guid(userId), filter);
           });
        }
        /// <summary>变更用户密码</summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdatePwd")]
        public JsonActionResult<bool> UpdatePwd([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                string userId = filter.Keyword;
                if (string.IsNullOrEmpty(userId))
                    userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserId;
                if (string.IsNullOrEmpty(userId))
                    throw new Exception("请设置用户ID");

                string oldPwd = filter.Parameter1;//原密码
                string newPwd = filter.Parameter2;//新密码
                var user = this.GetEntity<T_FM_USER>(userId);
                if (oldPwd != "8dcf2476c1216bab8f86e352a34b9029")
                {
                    if (string.Compare(user.PASSWORD, oldPwd, true) != 0)
                        throw new Exception("请输入正确的原密码");
                }
                user.PASSWORD = newPwd;
                this.UpdateEntity(user);
                return true;
            });
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("ReSetPwd")]
        public JsonActionResult<bool> ReSetPwd([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {


                string userId = filter.Keyword;
                if (string.IsNullOrEmpty(userId))
                    userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserId;
                if (string.IsNullOrEmpty(userId))
                    throw new Exception(ErrMsg.CM_NOEXIT_USER);
                var user = this.GetEntity<T_FM_USER>(userId);
                user.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";//默认密码123456
                this.UpdateEntity(user);
                return true;
            });
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SetPrint")]
        public JsonActionResult<bool> SetPrint([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                string userId = filter.Keyword;
                if (string.IsNullOrEmpty(userId))
                    userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserId;
                if (string.IsNullOrEmpty(userId))
                    throw new Exception(ErrMsg.CM_NOEXIT_USER);
                var user = this.GetEntity<T_FM_USER>(userId);
                string print = filter.Parameter1;
                if (string.IsNullOrEmpty(print))
                {
                    user.PRINTER_ID = null;
                }
                else
                {
                    user.PRINTER_ID = new Guid(print);
                }
                this.UpdateEntity(user);
                return true;
            });
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FM_USER_POST entity)
        {
            return SafeExecute<bool>(() =>
            {
                var postusers = entity.Nav_UserTests;
                entity.Nav_UserTests = null;
                UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    if (postusers != null && postusers.Any())
                        this.BantchSaveEntityNoCommit(postusers);
                });
                return true;
            });
        }


        /// <summary>
        /// 验证签名照是否有上传
        /// </summary>
        /// 
        /// <returns></returns>
        [HttpPost, Route("UserSign")]
        public JsonActionResult<bool> UserSign()
        {
            return SafeExecute<bool>(() =>
            {
                bool b = false;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var USign = GetEntity<T_FM_USER_SIGN_FILE>(b => b.USER_ID == userID);
                if (USign == null) b = true;
                return b;
            });
        }
        /// <summary>
        /// 更新用户状态
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("updateStatus")]
        public JsonActionResult<bool> updateStatus([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var userID = filter.Parameter2;
                var userIDGUID = new Guid(userID);
                var OrgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                BaseFilter BaseFilter = new BaseFilter(OrgId);
                var user = this.GetEntity<T_FM_USER>(userID, new string[] { "Nav_Person" });
                var department = GetEntity<T_FM_DEPARTMENT>(filter.Parameter3);

                if (filter.Parameter1.Equals("1"))
                {
                    user.ENABLE_STATUS = 0;
                }
                else
                {
                    user.ENABLE_STATUS = 1;
                }
                T_FM_TEAM_PERSON teamPerson = new T_FM_TEAM_PERSON();
                if (user.ENABLE_STATUS == 0 && department.DEPARTMENT_TYPE == (int)FMDepartmentType.班组)
                {
                    var teamInfo = this.GetEntity<T_FM_TEAM>(t => t.DEPARTMENT_ID == new Guid(filter.Parameter3));
                    if (teamInfo == null)
                        throw new Exception("请先到组织架构添加班组");
                    teamPerson.ORG_ID = OrgId;
                    teamPerson.ID = Guid.NewGuid();
                    teamPerson.TEAM_ID = teamInfo.ID;//new Guid(filter.Parameter3);
                    teamPerson.PERSON_ID = user.Nav_Person.ID;
                }
                this.UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(user);
                    if (user.ENABLE_STATUS == 0 && department.DEPARTMENT_TYPE == (int)FMDepartmentType.班组)
                    {
                        this.AddEntityNoCommit(teamPerson);
                    }
                    else
                    {
                        this.DeleteEntityNoCommit<T_FM_TEAM_PERSON>(i => i.Nav_Person.Nav_User.ID == userIDGUID);
                        this.DeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(i => i.Nav_Person.Nav_User.ID == userIDGUID && i.Nav_DepartmentScheduling.DATE_TIME >= DateTime.Now.Date);
                    }
                });
                return true;
            });
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetProductionUnit")]
        public JsonActionResult<T_FM_USER> GetProductionUnit([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_FM_USER>(() =>
            {
                T_FM_USER user = null;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var productionUnit = new List<T_FM_USER_PRODUCTION_UNIT>();
                    var department = this.GetEntity<T_FM_DEPARTMENT>(filter.Keyword, new string[] { "Nav_ProdutionUnit.Nav_Enums" });//, new string[] { "Nav_ProdutionUnit.Nav_Unit" }
                    //if (department != null) 
                    //{
                    //    user = new T_FM_USER();
                    //    user.MineType = department.MineType.ToString();
                    //}
                    if (department != null && department.Nav_ProdutionUnit != null && department.Nav_ProdutionUnit.Any())
                    {
                        user = new T_FM_USER();
                        department.Nav_ProdutionUnit.ForEach(t =>
                        {
                            T_FM_USER_PRODUCTION_UNIT unit = new T_FM_USER_PRODUCTION_UNIT();
                            unit.ORG_ID = t.ORG_ID;
                            unit.ENUMS_ID = t.ENUMS_ID;
                            unit.Nav_Enums = t.Nav_Enums;
                            productionUnit.Add(unit);
                        });
                        user.Nav_ProdutionUnit = productionUnit;
                    }
                }
                else
                    throw new Exception("组织架构错误,请联系管理员");
                return user;
            });
        }
    }
}
