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
{
    /// 
    /// 用户管理接口
    /// 
    [Route("api/FM/User")]
    public class UserController : AuthorizeApiController
    {
        IFMUserService UserService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        /// 
        /// 
        /// 
        /// 
        public UserController(IFMUserService personnelService, IFMDepartmentService departmentService, IFMNotificationTaskService notificationTaskService)
        {
            UserService = personnelService;
            DepartmentService = departmentService;
            NotificationTaskService = notificationTaskService;
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost, Route("Entities")]
        public JsonActionResult> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderEntities")]
        public JsonActionResult> 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;
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost, Route("Paged")]
        public PagedActionResult Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult 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;
            }
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderPagedNew")]
        public PagedActionResult OrderPagedNew([FromBody] KeywordPageFilter pageFilter)
        {
            Expression> 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;
            //}
        }
        /// 
        /// 查询(当前人员层级及以下层级)
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderPagedAuthority")]
        public PagedActionResult OrderPagedAuthority([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult();
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var admiId = this.GetEntity(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(loginUserId.ToString())?.DEPARTMENT_ID;
                List departmentId = new List();
                departmentId.Add((Guid)loginDepartmentId);
                List departmentIds = new List() { 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;
        }
        /// 
        /// 重写用户查询接口
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderPagedWithTeam")]
        public PagedActionResult OrderPagedWithTeam([FromBody] KeywordPageFilter pageFilter)
        {
            //pageFilter.Include.Add("Nav_Person.Nav_TeamPersons.Nav_Team");
            //var result =new PagedActionResult();
            return SafeGetPagedData((ret) =>
            {
                Expression> 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(express, pageFilter);
                //var teamPerson = result.Data.Where(t => t.Nav_Person != null && t.Nav_Person.Nav_TeamPersons != null);
                //var teamInfos = new List();
                //var departmentInfos = new List();
                //var parentInfos = new List();
                //if (teamPerson != null && teamPerson.Any())
                //{
                //    var teamIds = new List();
                //    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 => teamIds.Contains(t.ID),new BaseFilter(pageFilter.OrgId)).ToList();
                //    var departmentIds=teamInfos.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                //    departmentInfos = this.GetEntities(t => departmentIds.Contains(t.ID), new BaseFilter(pageFilter.OrgId)).ToList();
                //    var parentIds = departmentInfos.Select(t => t.PARENT_ID).Distinct().ToList();
                //    parentInfos = this.GetEntities(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;
            });
        }
        /// 
        /// 删除
        /// 
        /// 
        /// 
        [HttpGet, Route("Delete")]
        public JsonActionResult Delete(string id)
        {
            return SafeExecute(() =>
            {
                var user = this.GetEntity(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(belongRoles);
                    }
                    if (belongRoleGroups.Any())
                    {
                        BantchDeleteEntityNoCommit(belongRoleGroups);
                    }
                    if (belongUserGroups.Any())
                    {
                        BantchDeleteEntityNoCommit(belongUserGroups);
                    }
                    if (belongRoles.Any())
                    {
                        BantchDeleteEntityNoCommit(userPhoto);
                    }
                    DeleteEntityNoCommit(id);
                    if (user.PERSON_ID != null)
                        DeleteEntityNoCommit(user.PERSON_ID.ToString());
                });
                return true;
            });
        }
        /// 
        /// 更新
        /// 
        /// 
        /// 
        [HttpPost, Route("Update")]
        public JsonActionResult Update([FromBody] T_FM_USER entity)
        {
            return SafeExecute(() =>
            {
                var isAdd = this.GetEntities(t => t.ID == entity.ID, null);
                var userList = new List();
                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 sendNotice = new List();
                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 => (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 => t.THREE_LEVEL_SAFE_TRAIN_TYPE == (SEThreeLevelSafeTrainType)eduCard.STATUS.GetInt());
                        next_train_record.CONTENT_ID = train_contents.ID;
                        var postName = GetEntity(eduCard.POST_ID ?? Guid.Empty)?.NAME;
                        var sendUser = GetEntity(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;
                    //}
                    entity.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";
                    #endregion
                }
                else
                {
                    userList = this.GetEntities(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(entity.DEPARTMENT_ID.ToString());
                    if (departInfo != null && departInfo.MineType != null && !isAdd.Any())
                    {
                        var enumList = this.GetEntity(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();
                        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 => 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 teamPersons = new List();
                List teamPersonIds = new List();
                if (entity.Nav_Person.POST_ID == null)
                {
                    throw new Exception("岗位不允许为空!");
                }
                if (entity.DEPARTMENT_ID != null)
                {
                    departmentInfo = this.GetEntity(t => t.ID == entity.DEPARTMENT_ID && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用);
                    if (departmentInfo == null)
                        throw new Exception("组织架构已失效,请重新选择!");
                    var teamPersonInfo = this.GetEntity(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 => 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(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 => t.APPROVAL_ROLE_ID == entity.APPROVE_ROLE_ID, new BaseFilter(entity.ORG_ID));
                //List roleList = new List();
                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 => 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 => roleIds.Contains(t.BELONG_ROLE_ID), new BaseFilter(entity.ORG_ID));
                //List roleGroupList = new List();
                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 => enumIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                    var enumValues = new List();
                    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 deleteBelongRoleIds = new List();
                List deleteBelongRoleGroupIds = new List();
                List deleteBelongUserGroupsIds = new List();
                List deletePhotoFileIds = new List();
                List deleteSignFileIds = new List();
                List deleteProductionIds = new List();
                var dbEntity = this.GetEntity(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 => deleteBelongRoleIds.Contains(t.ID));
                    if (deleteBelongRoleGroupIds.Any())
                        this.DeleteEntityNoCommit(t => deleteBelongRoleGroupIds.Contains(t.ID));
                    if (deleteBelongUserGroupsIds.Any())
                        this.DeleteEntityNoCommit(t => deleteBelongUserGroupsIds.Contains(t.ID));
                    if (deletePhotoFileIds.Any())
                        this.DeleteEntityNoCommit(t => deletePhotoFileIds.Contains(t.ID));
                    if (deleteSignFileIds.Any())
                        this.DeleteEntityNoCommit(t => deleteSignFileIds.Contains(t.ID));
                    if (deleteProductionIds.Any())
                        this.DeleteEntityNoCommit(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 => teamPersonIds.Contains(t.ID));
                });
                return true;
            });
        }
        /// 
        /// 批量删除
        /// 
        /// 
        /// 
        [HttpGet, Route("BatchDelete")]
        public JsonActionResult BatchDelete(string ids)
        {
            return WitRealBatchDelete(ids);
        }
        /// 
        /// 获得单条实体数据
        /// 
        /// 
        /// 
        [HttpPost, Route("Get")]
        public JsonActionResult Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }
        /// 
        /// 获取人员角色信息
        /// 
        /// 
        /// 
        [HttpPost, Route("GetRolesByUser")]
        public JsonActionResult GetRolesByUser([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
           {
               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);
           });
        }
        /// 变更用户密码
        /// 
        /// 
        [HttpPost, Route("UpdatePwd")]
        public JsonActionResult UpdatePwd([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                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(userId);
                if (oldPwd != "8dcf2476c1216bab8f86e352a34b9029")
                {
                    if (string.Compare(user.PASSWORD, oldPwd, true) != 0)
                        throw new Exception("请输入正确的原密码");
                }
                user.PASSWORD = newPwd;
                this.UpdateEntity(user);
                return true;
            });
        }
        /// 
        /// 重置密码
        /// 
        /// 
        /// 
        [HttpPost, Route("ReSetPwd")]
        public JsonActionResult ReSetPwd([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                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(userId);
                user.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";//默认密码123456
                this.UpdateEntity(user);
                return true;
            });
        }
        /// 
        /// 重置密码
        /// 
        /// 
        /// 
        [HttpPost, Route("SetPrint")]
        public JsonActionResult SetPrint([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                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(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;
            });
        }
        /// 
        /// 重置密码
        /// 
        /// 
        /// 
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult FullUpdate([FromBody] T_FM_USER_POST entity)
        {
            return SafeExecute(() =>
            {
                var postusers = entity.Nav_UserTests;
                entity.Nav_UserTests = null;
                UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    if (postusers != null && postusers.Any())
                        this.BantchSaveEntityNoCommit(postusers);
                });
                return true;
            });
        }
        /// 
        /// 验证签名照是否有上传
        /// 
        /// 
        /// 
        [HttpPost, Route("UserSign")]
        public JsonActionResult UserSign()
        {
            return SafeExecute(() =>
            {
                bool b = false;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var USign = GetEntity(b => b.USER_ID == userID);
                if (USign == null) b = true;
                return b;
            });
        }
        /// 
        /// 更新用户状态
        /// 
        /// 
        /// 
        [HttpPost, Route("updateStatus")]
        public JsonActionResult updateStatus([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                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(userID, new string[] { "Nav_Person" });
                var department = GetEntity(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 => 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(i => i.Nav_Person.Nav_User.ID == userIDGUID);
                        this.DeleteEntityNoCommit(i => i.Nav_Person.Nav_User.ID == userIDGUID && i.Nav_DepartmentScheduling.DATE_TIME >= DateTime.Now.Date);
                    }
                });
                return true;
            });
        }
        /// 
        /// 获得单条实体数据
        /// 
        /// 
        /// 
        [HttpPost, Route("GetProductionUnit")]
        public JsonActionResult GetProductionUnit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_FM_USER user = null;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var productionUnit = new List();
                    var department = this.GetEntity(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;
            });
        }
    }
}