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 APT.MS.Domain.Entities.SC.PT;
using Microsoft.Extensions.DependencyModel;
using APT.MS.Domain.Entities.SK;
using APT.BaseData.Domain.IServices.OP;
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; }
        IOPTenantDBConnService OPTenantDBConnService { get; set; }
        /// 
        /// 
        /// 
        /// 
        public UserController(IFMUserService personnelService, IFMDepartmentService departmentService, IFMNotificationTaskService notificationTaskService, IOPTenantDBConnService opTenantDBConnService)
        {
            UserService = personnelService;
            DepartmentService = departmentService;
            NotificationTaskService = notificationTaskService;
            OPTenantDBConnService = opTenantDBConnService;
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [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.NAME.Contains("管理员") && t.ENABLE_STATUS == 0);
            }
            return result;
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost, Route("Paged")]
        public PagedActionResult Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderPagedOld")]
        public PagedActionResult OrderPagedOld([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.NAME.Contains("管理员") && 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.NAME.Contains("管理员") && t.ENABLE_STATUS == 0);
                }
                return result;
            }
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value;
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
            var selectDepatmentIds = new List();
            var result = new PagedActionResult();
            if (string.IsNullOrEmpty(pageFilter.Parameter1))
            {
                if (orgId.ToString() == "8B3C41AA-51B1-7CE9-1879-248A038C1B5C".ToLower() && (loginDepartmentId.ToString() == "5FD3781B-FF53-9872-D694-85A0BDE11611".ToLower()
                    || loginDepartmentId.ToString() == "2F670ECC-FAFC-8845-6602-9E079D407B8F".ToLower() || loginDepartmentId.ToString() == "26294323-C18D-C660-B812-E101D7C04D6D".ToLower()))
                {
                    pageFilter.FilterGroup.Rules.Clear();
                    selectDepatmentIds.Add(Guid.Parse("5FD3781B-FF53-9872-D694-85A0BDE11611"));
                    selectDepatmentIds.Add(Guid.Parse("2F670ECC-FAFC-8845-6602-9E079D407B8F"));
                    selectDepatmentIds.Add(Guid.Parse("26294323-C18D-C660-B812-E101D7C04D6D"));
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && t.ENABLE_STATUS == 0 && !t.PROJECT_ID.HasValue && selectDepatmentIds.Contains(t.DEPARTMENT_ID.Value), pageFilter);
                }
                else
                {
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && !t.PROJECT_ID.HasValue && t.ENABLE_STATUS == 0, pageFilter);
                }
                return result;
            }
            else
            {
                if (orgId.ToString() == "8B3C41AA-51B1-7CE9-1879-248A038C1B5C".ToLower() && (loginDepartmentId.ToString() == "5FD3781B-FF53-9872-D694-85A0BDE11611".ToLower()
                    || loginDepartmentId.ToString() == "2F670ECC-FAFC-8845-6602-9E079D407B8F".ToLower() || loginDepartmentId.ToString() == "26294323-C18D-C660-B812-E101D7C04D6D".ToLower()))
                {
                    pageFilter.FilterGroup.Rules.Clear();
                    selectDepatmentIds.Add(Guid.Parse("5FD3781B-FF53-9872-D694-85A0BDE11611"));
                    selectDepatmentIds.Add(Guid.Parse("2F670ECC-FAFC-8845-6602-9E079D407B8F"));
                    selectDepatmentIds.Add(Guid.Parse("26294323-C18D-C660-B812-E101D7C04D6D"));
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && t.ENABLE_STATUS == 0 && !t.PROJECT_ID.HasValue && selectDepatmentIds.Contains(t.DEPARTMENT_ID.Value) && t.Nav_BelongRoles.Any(i => i.Nav_BelongRole.NAME.Contains(pageFilter.Parameter1)), pageFilter);
                }
                else
                {
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && t.ENABLE_STATUS == 0 && !t.PROJECT_ID.HasValue && 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.NAME.Contains("管理员") && !t.PROJECT_ID.HasValue && t.ENABLE_STATUS == 0);
                //}
                return result;
            }
        }
        [HttpPost, Route("OrderPagedFO")]
        public PagedActionResult OrderPagedFO([FromBody] KeywordPageFilter pageFilter)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value;
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
            var selectDepatmentIds = new List();
            var result = new PagedActionResult();
            if (string.IsNullOrEmpty(pageFilter.Parameter1))
            {
                if (orgId.ToString() == "8B3C41AA-51B1-7CE9-1879-248A038C1B5C".ToLower())
                {
                    pageFilter.FilterGroup.Rules.Clear();
                    var departs = this.GetEntities(t => t.ENABLE_STATUS == 0, new BaseFilter(orgId));
                    var depart = departs.FirstOrDefault(t => t.ID == loginDepartmentId);
                    if (depart != null && depart.DEPARTMENT_TYPE == 2)
                    {
                        selectDepatmentIds = departs.Where(t => t.PARENT_ID == depart.PARENT_ID).Select(m => m.ID).ToList();
                    }
                    else
                    { selectDepatmentIds.Add(loginDepartmentId); }
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && t.ENABLE_STATUS == 0 && !t.PROJECT_ID.HasValue && selectDepatmentIds.Contains(t.DEPARTMENT_ID.Value), pageFilter);
                }
                else
                {
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && !t.PROJECT_ID.HasValue && t.ENABLE_STATUS == 0, pageFilter);
                }
                return result;
            }
            else
            {
                if (orgId.ToString() == "8B3C41AA-51B1-7CE9-1879-248A038C1B5C".ToLower())
                {
                    pageFilter.FilterGroup.Rules.Clear();
                    var departs = this.GetEntities(t => t.ENABLE_STATUS == 0, new BaseFilter(orgId));
                    var depart = departs.FirstOrDefault(t => t.ID == loginDepartmentId);
                    if (depart != null && depart.DEPARTMENT_TYPE == 2)
                    {
                        selectDepatmentIds = departs.Where(t => t.PARENT_ID == depart.PARENT_ID).Select(m => m.ID).ToList();
                    }
                    else
                    { selectDepatmentIds.Add(loginDepartmentId); }
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && t.ENABLE_STATUS == 0 && !t.PROJECT_ID.HasValue && selectDepatmentIds.Contains(t.DEPARTMENT_ID.Value) && t.Nav_BelongRoles.Any(i => i.Nav_BelongRole.NAME.Contains(pageFilter.Parameter1)), pageFilter);
                }
                else
                {
                    result = WitOrderPaged(t => !t.NAME.Contains("管理员") && t.ENABLE_STATUS == 0 && !t.PROJECT_ID.HasValue && 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.NAME.Contains("管理员") && !t.PROJECT_ID.HasValue && 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)));
            }
            YesNoEnum? projEnum = null;
            if (pageFilter.FilterGroup.Rules.Any())
            {
                var listRules = pageFilter.FilterGroup.Rules.ToList();
                var ProjSet = listRules.FirstOrDefault(e => e.Field == "IS_PROJECT");//是否外包工程
                if (ProjSet != null)
                {
                    listRules.Remove(ProjSet);
                    pageFilter.FilterGroup.Rules = listRules;
                    switch (ProjSet.Value.ToString())
                    {
                        case "20":
                            projEnum = YesNoEnum.No;
                            break;
                        case "10":
                            projEnum = YesNoEnum.Yes;
                            break;
                        default:
                            break;
                    }
                }
            }
            if (projEnum.HasValue)
            {
                if (projEnum == YesNoEnum.Yes)
                    express = express.And(e => e.PROJECT_ID.HasValue);
                else
                    express = express.And(e => !e.PROJECT_ID.HasValue);
            }
            var result = this.WitOrderPaged(express, pageFilter);
            if (result.Data.Count() > 0)
            {
                var userIds = result.Data.Select(t => t.ID).ToList();
                var signs = this.GetEntities(t => userIds.Contains(t.USER_ID), new BaseFilter(pageFilter.OrgId));
                result.Data.ForEach(t =>
                {
                    var temp = signs.FirstOrDefault(m => m.USER_ID == t.ID);
                    if (temp != null)
                    {
                        t.IS_SIGN = "是";
                    }
                    else
                    {
                        t.IS_SIGN = "否";
                    }
                });
            }
            return result;
            //if (string.IsNullOrEmpty(pageFilter.Parameter1))
            //{
            //    var result = WitOrderPaged(null, pageFilter);
            //    if (result.Data.Count() > 0)
            //    {
            //        result.Data = result.Data.Where(t => !t.NAME.Contains("管理员"));
            //    }
            //    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.NAME.Contains("管理员"));
            //    }
            //    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;
            var AH = GetEntity(t => t.NAME != null && t.ID == loginUserId && t.Nav_Department != null && (t.Nav_Department.DEPARTMENT_TYPE == 0 || t.Nav_Department.DEPARTMENT_TYPE == 3) && (t.Nav_Department.NAME.Contains("安全环保") || t.Nav_Department.NAME.Contains("安环")));
            if (loginUserId == null || loginUserId == admiId || AH != null)
            {
                result = WitOrderPaged(null, pageFilter); ;
                if (result.Data.Count() > 0)
                {
                    result.Data = result.Data.Where(t => !t.NAME.Contains("管理员") && 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.NAME.Contains("管理员") && t.ENABLE_STATUS == 0);
                    }
                }
                else
                    result.Data = null;
            }
            return result;
        }
        /// 
        /// 除车间级班组级向下查询,其他层级查所有人
        /// 
        /// 
        /// 
        [HttpPost, Route("OrderPagedWithLevel")]
        public PagedActionResult OrderPagedWithLevel([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData((ret) =>
            {
                var departId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentId;
                var departIdType = this.GetEntity(departId.ToString())?.DEPARTMENT_TYPE;
                Expression> express = t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin");
                if (departIdType != null && (departIdType == 15 || departIdType == 20))
                {
                    List departmentId = new List();
                    departmentId.Add(Guid.Parse(departId.ToString()));
                    List departmentIds = new List() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                    DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                    express = express.And(t => t.DEPARTMENT_ID != null && departmentIds.Contains((Guid)t.DEPARTMENT_ID));
                }
                var result = this.GetOrderPageEntities(express, pageFilter);
                ret.TotalCount = result.TotalCount;
                ret.Data = result.Data;
            });
        }
        /// 
        /// 重写用户查询接口
        /// 
        /// 
        /// 
        [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 allUsers = this.GetEntities(t => t.IS_DELETED == false, null, "Nav_ApproveRole");
                var isAdd = allUsers.Where(t => t.ID == entity.ID);
                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;
                T_OG_SAFE_PDT_SIGNED signRecord = null;
                T_OG_SAFE_PDT_SIGNED_POST signPost = null;
                T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL library = null;
                T_FM_NOTIFICATION_TASK noticeToday = null;
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    throw new Exception("工号不允许为空!");
                }
                if (entity.CODE.Length <= 3)
                    this.ThrowError("050003");
                if (string.IsNullOrEmpty(entity.NAME))
                {
                    throw new Exception("姓名不允许为空!");
                }
                if (entity.Nav_Person.POST_ID == null)
                {
                    throw new Exception("岗位不允许为空!");
                }
                if (!isAdd.Any())
                {
                    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 (entity.ORG_ID != Guid.Parse("b043b28b-bbc3-c452-6052-4fba1457abfa"))
                    {
                        #region    //
                        #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.公司级
                        //};
                        //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 != null && t.Nav_ApproveRole.NAME == "安环部安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                        //if (sendUser != null)
                        //{
                        //    var endTime = entity.ENTRYTIME.AddMonths(1);
                        //    var newEndTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59);
                        //    sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + entity.NAME + "-" + eduCard.STATUS.GetDescription(), next_train_record.ID, entity.ORG_ID, sendUser.ID, sendUser.NAME, DateTime.Now, newEndTime, 1, "SE042"));
                        //}
                        #endregion
                        #region //新增人员触发安全生产责任制
                        //var post = GetEntity(t => t.Nav_Dept.DEPARTMENT_ID == entity.DEPARTMENT_ID && t.DEPOST_ID == entity.Nav_Person.POST_ID, new string[] { "Nav_Dept.Nav_Post" });
                        //if (post != null)
                        //{
                        //    var standardCreate = GetEntity(t => t.POST_ID == post.Nav_Dept.POST_ID && t.STATUS == SCSystemEditStatus.已归档 && t.FILE_STATUS == SCSystemFileStatus.有效);
                        //    if (standardCreate != null)
                        //    {
                        //        var chargeUser = GetEntity(t => t.DEPARTMENT_ID == post.Nav_Dept.Nav_Post.DEPARTMENT_ID && t.Nav_Person.POST_ID == post.Nav_Dept.Nav_Post.DEPOST_ID && t.ENABLE_STATUS == 0);
                        //        if (chargeUser != null)
                        //        {
                        //            signRecord = new T_OG_SAFE_PDT_SIGNED
                        //            {
                        //                ID = Guid.NewGuid(),
                        //                ORG_ID = entity.ORG_ID,
                        //                STATUS = (int)PFStandardStatus.Draft,
                        //                TRIGGER_TYPE = OGPersonalSignedTriggerType.新员工触发,
                        //                //TRIGGER_TYPE = OGPersonalSignedTriggerType.手动新增,
                        //                STANDARD_ID = standardCreate.ID,
                        //                FILE_CONTENT = standardCreate.FILE_CONTENT,
                        //                DEPARTMENT_ID = entity.DEPARTMENT_ID,
                        //                ANNUAL = DateTime.Now.Year
                        //            };
                        //            if (chargeUser != null)
                        //            {
                        //                signRecord.CHARGE_USER_ID = chargeUser.ID;
                        //            }
                        //            signPost = new T_OG_SAFE_PDT_SIGNED_POST
                        //            {
                        //                SAFE_PDT_SIGNED_ID = signRecord.ID,
                        //                ID = Guid.NewGuid(),
                        //                ORG_ID = entity.ORG_ID,
                        //                USER_ID = entity.ID,
                        //                POST_ID = entity.Nav_Person.POST_ID,
                        //                CHARGE_USER_ID = signRecord.CHARGE_USER_ID
                        //            };
                        //            sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel(DateTime.Now.ToShortDateString() + "安全生产责任制个人签订表", signRecord.ID, entity.ORG_ID, entity.ID, entity.NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "OG001_SHOWPRINT"));
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    if (sendUser != null)
                        //    {
                        //        sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel("请为《" + postName + "》绑定责任制岗位并上传责任状", entity.ID, entity.ORG_ID, sendUser.ID, sendUser.NAME, DateTime.Now, DateTime.Now.AddDays(7), (int)FMNoticeTypeEnum.今日提醒, "PF135"));
                        //    }
                        //}
                        #endregion 
                        #endregion
                    }
                    //#region 增加新增人员到ops表
                    //using (var context = new MigrationContext(ConfigurationManager.ConnectionStrings["default"]))
                    //{
                    //    var tennant = context.GetEntity(t => t.ID == entity.ORG_ID, new string[] { "CODE" }).CODE;
                    //    T_OP_ALLUSER alluser = new T_OP_ALLUSER();
                    //    alluser.ID = entity.ID;
                    //    alluser.CODE = entity.CODE;
                    //    alluser.TENANT = tennant;
                    //    alluser.ORG_ID = entity.ORG_ID;
                    //    alluser.PHONE = entity.PHONE;
                    //    context.AddEntity(alluser);
                    //    context.SaveChanges();
                    //}
                    //#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 => (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);
                        entity.MineType = departInfo.MineType.ToString();
                        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);
                    }
                    ///同步目标指标库
                    library = this.GetEntity(t => t.USER_ID == entity.ID);
                    if (library != null)
                    {
                        library.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                        library.Nav_Contents = null;
                    }
                }
                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 (!string.IsNullOrEmpty(entity.PHONE) && entity.PHONE.Length != 11)
                {
                    throw new Exception("手机号码应该为11位!");
                }
                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 != 3 && roleInfo.DEPARTMENT_TYPE != departmentInfo.DEPARTMENT_TYPE)
                            {
                                var param = ((FMDepartmentType)departmentInfo.DEPARTMENT_TYPE).GetDescription();
                                var param2 = ((FMDepartmentType)roleInfo.DEPARTMENT_TYPE).GetDescription();
                                throw new Exception(departmentInfo.NAME + "是" + param + "," + roleInfo.NAME + "是" + param2 + ",组织层级不一致");
                            }
                        }
                    }
                }
                else
                    this.ThrowError("060001");
                //else
                //{
                //    //查双控库是否有该辨识岗位,没有的话触发今日提醒给安全员
                //    var postFirst = this.GetEntity(t => t.POST_ID == entity.Nav_Person.POST_ID);
                //    if (postFirst == null)
                //    {
                //        var userPostFirst = this.GetEntity(t => t.ID == entity.Nav_Person.POST_ID);
                //        var sendUser = allUsers.FirstOrDefault(t => t.DEPARTMENT_ID == departmentInfo.ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                //        if (departmentInfo.DEPARTMENT_TYPE == 2)
                //        {
                //            sendUser = allUsers.FirstOrDefault(t => t.ID == departmentInfo.USER_ID);
                //        }
                //        if (departmentInfo.DEPARTMENT_TYPE == 1 )
                //        {
                //            sendUser = allUsers.FirstOrDefault(t => t.DEPARTMENT_ID == departmentInfo.ID && t.Nav_ApproveRole!=null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                //            if (sendUser == null)
                //            {
                //                sendUser = allUsers.FirstOrDefault(t => t.DEPARTMENT_ID == departmentInfo.PARENT_ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                //            }
                //        }
                //        if (departmentInfo.DEPARTMENT_TYPE == 3)
                //        {
                //            sendUser = allUsers.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安环部安全员"));
                //        }
                //        if (sendUser != null && entity.ORG_ID != Guid.Parse("d9871ba8-0eec-9e4a-bb87-7d5a540d8913"))
                //            //发送今日提醒
                //            noticeToday = NotificationTaskService.InsertUserNoticeTaskModel(entity.NAME +"的岗位“" + userPostFirst.NAME + "”在库中找不到,请到双重预防机制企业库维护对应的检查内容", entity.ID, entity.ORG_ID, sendUser.ID, sendUser.NAME, DateTime.Now, DateTime.Now.AddDays(30), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                //    }
                //}
                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 =>
                    {
                        var isExsis = entity.Nav_BelongRoles.FirstOrDefault(t => t.BELONG_ROLE_ID == role.ROLE_ID);
                        if (isExsis == null)
                        {
                            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 role1 = this.GetEntity(t => t.NAME == "作业员");
                    var role2 = this.GetEntity(t => t.NAME == "APP用户");
                    if (role1 != null)
                    {
                        var isExsis = entity.Nav_BelongRoles.FirstOrDefault(t => t.BELONG_ROLE_ID == role1.ID);
                        if (isExsis == null)
                        {
                            T_FM_USER_BELONG_ROLE belongRole = new T_FM_USER_BELONG_ROLE();
                            belongRole.USER_ID = entity.ID;
                            belongRole.BELONG_ROLE_ID = role1.ID;
                            belongRole.ORG_ID = entity.ORG_ID;
                            entity.Nav_BelongRoles.Add(belongRole);
                        }
                    }
                    if (role2 != null)
                    {
                        var isExsis1 = entity.Nav_BelongRoles.FirstOrDefault(t => t.BELONG_ROLE_ID == role2.ID);
                        if (isExsis1 == null)
                        {
                            T_FM_USER_BELONG_ROLE belongRole = new T_FM_USER_BELONG_ROLE();
                            belongRole.USER_ID = entity.ID;
                            belongRole.BELONG_ROLE_ID = role2.ID;
                            belongRole.ORG_ID = entity.ORG_ID;
                            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; t.Nav_ImgFile = null; });
                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);
                    });
                    entity.MineType = string.Join(",", enumValues);
                }
                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);
                        });
                    }
                }
                var isHead = HeadHelper.GetIsHead(this.Request.Headers);
                Dictionary dicConn = null;
                if (isHead)
                {
                    dicConn = OPTenantDBConnService.GetConnDictionary(entity.ORG_ID);
                    if (dicConn == null)
                    {
                        throw new Exception("获取子公司链接失败,请关闭页面刷新后再试");
                    }
                }
                #region   总用户库添加
                if (!isAdd.Any())
                {
                    using (var context = new MigrationContext(ConfigurationManager.ConnectionStrings["default"]))
                    {
                        var tennant = context.GetEntity(t => t.ID == entity.ORG_ID, new string[] { "CODE" }).CODE;
                        T_OP_ALLUSER alluser = new T_OP_ALLUSER();
                        alluser.ID = entity.ID;
                        alluser.CODE = entity.CODE;
                        alluser.TENANT = tennant;
                        alluser.ORG_ID = entity.ORG_ID;
                        alluser.PHONE = entity.PHONE;
                        context.AddEntity(alluser);
                        context.SaveChanges();
                    }
                }
                #endregion
                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 (personTeam != null && personTeam.Any())
                        this.BantchSaveEntityNoCommit(personTeam);
                    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 (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 (productionUnit != null && productionUnit.Any())
                        this.BantchSaveEntityNoCommit(productionUnit);
                    if (eduCard != null)
                        AddEntityNoCommit(eduCard);
                    if (sendNotice != null)
                        BantchAddEntityNoCommit(sendNotice);
                    if (next_train_record != null)
                        AddEntityNoCommit(next_train_record);
                    if (signRecord != null)
                        AddEntityNoCommit(signRecord);
                    if (signPost != null)
                        AddEntityNoCommit(signPost);
                    if (library != null)
                        this.UpdateEntityNoCommit(library);
                    if (teamPersonIds.Any())
                        this.DeleteEntityNoCommit(t => teamPersonIds.Contains(t.ID));
                    if (noticeToday != null)
                        this.UpdateEntityNoCommit(noticeToday);
                });
                #region    wyw  如果是总部  人员信息同步到子公司
                if (isHead)
                {
                    entity.Nav_Department = null;
                    entity.Nav_BelongRoles = null;
                    entity.Nav_BelongRoleGroups = null;
                    entity.Nav_BelongUserGroups = null;
                    entity.Nav_UserPhotoFiles = null;
                    entity.Nav_UserSignFiles = null;
                    entity.TEAM_ID = null;
                    entity.Nav_ApproveRole = null;
                    entity.PROJECT_ID = null;
                    entity.PRINTER_ID = null;
                    person.Nav_DepartMent = null;
                    person.Nav_Post = null;
                    person.POST_ID = null;
                    person.Nav_TeamPersons = null;
                    person.Nav_PersonWorks = null;
                    person.Nav_PersonSkills = null;
                    person.Nav_PersonIDCardFiles = null;
                    person.Nav_PersonEducationFiles = null;
                    person.Nav_PersonCertificateFiles = null;
                    int EditC = 0;
                    foreach (var item in dicConn)
                    {
                        try
                        {
                            entity.ORG_ID = item.Key;
                            person.ORG_ID = item.Key;
                            using (var context = new MigrationContext(item.Value))
                            {
                                EditC = context.GetCount(e => e.ID == entity.ID);
                                entity.DEPARTMENT_ID = context.GetEntity(e => e.PARENT_ID == null && !e.IS_DELETED && e.DEPARTMENT_TYPE == 5, null).ID;
                                person.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                                if (EditC > 0)
                                {
                                    context.UpdateEntity(entity);
                                    context.UpdateEntity(person);
                                    context.SaveChanges();
                                }
                                else
                                {
                                    context.AddEntity(person);
                                    context.AddEntity(entity);
                                    context.SaveChanges();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                #endregion
                return true;
            });
        }
        /// 
        /// 用户权限更新
        /// 
        /// 
        /// 
        [HttpPost, Route("UpdateAuth")]
        public JsonActionResult UpdateAuth([FromBody] T_FM_USER entity)
        {
            return SafeExecute(() =>
            {
                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));
                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;
                entity.Nav_BelongRoleGroups = null;
                entity.Nav_BelongRoles = null;
                entity.Nav_BelongUserGroups = 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);
                List deleteBelongRoleIds = new List();
                List deleteBelongRoleGroupIds = new List();
                List deleteBelongUserGroupsIds = new List();
                var dbEntity = this.GetEntity(entity.ID.ToString(), new string[] { "Nav_BelongRoleGroups",
                    "Nav_BelongRoles", "Nav_BelongUserGroups"    });
                if (dbEntity != null)
                {
                    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);
                        });
                    }
                }
                UnifiedCommit(() =>
                {
                    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 (belongRoleGroups != null && belongRoleGroups.Any())
                        this.BantchSaveEntityNoCommit(belongRoleGroups);
                    if (belongRoles != null && belongRoles.Any())
                        this.BantchSaveEntityNoCommit(belongRoles);
                    if (belongUserGroups != null && belongUserGroups.Any())
                        this.BantchSaveEntityNoCommit(belongUserGroups);
                });
                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);
                string pwd = "";
                if (!string.IsNullOrEmpty(user.NAME) && !string.IsNullOrEmpty(user.CODE))
                {
                    MD5 md5 = MD5.Create();
                    string code = DataHelper.GetCodeNO(user.CODE);
                    string nameHead = DataHelper.MkPinyinString(user.NAME);
                    pwd = nameHead + code;
                    string NewPwd = DataHelper.MD5Encrypt32(md5, nameHead + code);
                    user.PASSWORD = NewPwd;
                }
                else
                {
                    pwd = "123456";
                    user.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";//默认密码123456
                }
                this.UpdateEntity(user);
                return pwd;
            });
        }
        /// 
        /// 重置密码
        /// 
        /// 
        /// 
        [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.Class)
                {
                    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.Class)
                    {
                        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;
            });
        }
    }
}