using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities.BD;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.PF;
using APT.Utility;
using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.FM.WebApi.Controllers.Api.FM
{
    [Route("api/FM/Department")]
    public class DepartmentController : AuthorizeTreeApiController<T_FM_DEPARTMENT>
    {
        IFMDepartmentService DepartmentService { get; set; }
        public DepartmentController(IFMDepartmentService departmentService)
        {
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_FM_DEPARTMENT>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// 

        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_FM_DEPARTMENT>> OrderEntities([FromBody] KeywordFilter filter)
        {
            filter.FilterGroup.Rules.Add(new FilterRule() { Field = "ENABLE_STATUS", Operate = FilterOperate.Equal, Value = 0 });
            filter.FilterGroup.Rules.Add(new FilterRule() { Field = "CATEGORY", Operate = FilterOperate.NotEqual, Value = 15 });
            var result = WitOrderEntities(null, filter);
            if (result.Data.Count() > 0)
            {
                var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && !t.CODE.Contains("admin"), new BaseFilter(filter.OrgId)).ToList();
                foreach (var item in result.Data)
                {
                    List<Guid> outPartmentIds = new List<Guid>();
                    List<Guid> inputIds = new List<Guid>() { item.ID };
                    GetDepartmentIds(filter.OrgId.Value, inputIds, ref outPartmentIds);
                    outPartmentIds.Add(item.ID);
                    var userCount = users.Count(t => t.DEPARTMENT_ID != null && outPartmentIds.Contains((Guid)t.DEPARTMENT_ID));
                    item.NAME = item.NAME + "(" + userCount + ")";
                }
            }
            return result;
        }
        /// <summary>
        /// 返回所有下级部门节点
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="listDepIDInt"></param>
        /// <param name="departmentIdPs"></param>
        public void GetDepartmentIds(Guid orgId, List<Guid> listDepIDInt, ref List<Guid> departmentIdPs)
        {
            var listDep = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.PARENT_ID.HasValue && listDepIDInt.Contains(e.PARENT_ID.Value), new BaseFilter(orgId));

            if (listDep != null && listDep.Any())
            {
                listDepIDInt = listDep.Select(e => e.ID).ToList();
                departmentIdPs.AddRange(listDepIDInt);
                GetDepartmentIds(orgId, listDepIDInt, ref departmentIdPs);
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_FM_DEPARTMENT> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FM_DEPARTMENT> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            bool isAdd = false;
            if (pageFilter.FilterGroup.Rules == null)
                isAdd = true;
            if (!isAdd)
            {
                var c = pageFilter.FilterGroup.Rules.FirstOrDefault(e => e.Field == "CATEGORY");
                if (c == null)
                    isAdd = true;
            }
            if (isAdd)
            {
                if (pageFilter.FilterGroup.Rules == null)
                    pageFilter.FilterGroup.Rules = new List<FilterRule>();
                //默认非外包
                FilterRule filterRule = new FilterRule();
                filterRule.Field = "CATEGORY";
                filterRule.Value = FMCATEGORY.WB;
                filterRule.IsSysParamRule = false;
                filterRule.Operate = FilterOperate.NotEqual;
                pageFilter.FilterGroup.Rules.Add(filterRule);
            }

            FilterRule filterRuleDelete = new FilterRule();
            filterRuleDelete.Field = "IS_DELETED";
            filterRuleDelete.Value = "false";
            filterRuleDelete.IsSysParamRule = false;
            filterRuleDelete.Operate = FilterOperate.Equal;

            FilterRule filterRuleENABLE = new FilterRule();
            filterRuleENABLE.Field = "ENABLE_STATUS";
            filterRuleENABLE.Value = "0";
            filterRuleENABLE.IsSysParamRule = false;
            filterRuleENABLE.Operate = FilterOperate.Equal;
            if (pageFilter.FilterGroup.Rules == null)
            {
                pageFilter.FilterGroup.Rules = new List<FilterRule>();
                pageFilter.FilterGroup.Rules.Add(filterRuleDelete);
                pageFilter.FilterGroup.Rules.Add(filterRuleENABLE);
            }
            else
            {
                pageFilter.FilterGroup.Rules.Add(filterRuleDelete);
                pageFilter.FilterGroup.Rules.Add(filterRuleENABLE);
            }
            return WitOrderPaged(null, pageFilter);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Delete")]
        public JsonActionResult<bool> Delete(string id)
        {
            return WitRealDelete(id);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_FM_DEPARTMENT entity)
        {
            return WitUpdate(entity);
        }

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


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_FM_DEPARTMENT> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FM_DEPARTMENT entity)
        {
            return SafeExecute<bool>(() =>
            {
                var deptUser = entity.Nav_UserDeparts;
                entity.Nav_UserDeparts = null;
                this.UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    if (deptUser != null)
                    {
                        this.BantchSaveEntityNoCommit(deptUser);
                    }
                });
                return true;
            });
        }

        /// <summary>
        /// 部门列表
        /// </summary>
        /// <param name="filter">过滤条件</param>
        /// <returns></returns>
        [HttpPost, Route("WorkShopTreeData")]
        public JsonActionResult<IEnumerable<TreeNode<T_FM_DEPARTMENT>>> WorkShopTreeData([FromBody] KeywordFilter filter)
        {
            return WitTreeOrderEntities(i => i.DEPARTMENT_TYPE == (int)FMDepartmentType.Workshop, filter);
        }


        /// <summary>
        /// 保存生产日历配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CalendarUpdate")]
        public JsonActionResult<bool> CalendarUpdate([FromBody] T_FM_DEPARTMENT entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity != null && entity.Nav_DepartmentScheduling != null && entity.ORG_ID != null)
                {
                    //var shiftList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.ORG_ID == entity.ORG_ID && s.DEPARTMENT_ID == entity.ID && s.DATE_TIME == entity
                    //.Nav_DepartmentScheduling.FirstOrDefault().DATE_TIME, filter);
                    //var sIds = shiftList.Select(s => s.ID);

                    //排除不存在数据库中并且是删除状态的数据
                    List<T_FM_DEPARTMENT_SCHEDULING> nodeSchedulingList = entity.Nav_DepartmentScheduling.Where(i => !i.IS_DELETED).Select(e => new T_FM_DEPARTMENT_SCHEDULING
                    {
                        ORG_ID = entity.ORG_ID,
                        ID = Guid.NewGuid(),
                        DEPARTMENT_ID = entity.ID,
                        //DEPARTMENT_CALENDAR_CONFIG_ID = e.DEPARTMENT_CALENDAR_CONFIG_ID,
                        DATE_TIME = e.DATE_TIME,
                        CLASS_ID = e.CLASS_ID,
                        TEAM_ID = e.TEAM_ID,
                        ENABLE_STATUS = e.ENABLE_STATUS
                    }).ToList();
                    //删除原本的人员排班计划
                    var teamIds = entity.Nav_DepartmentScheduling.Select(i => i.TEAM_ID).ToList();
                    var filter = new BaseFilter(entity.ORG_ID);
                    filter.SelectField = new string[] { "ID", "TEAM_ID", "PERSON_ID" };
                    var classPersons = this.GetEntities<T_FM_TEAM_PERSON>(i => teamIds.Contains(i.TEAM_ID), filter);
                    List<T_FM_DEPARTMENT_SCHEDULING_DETAIL> departmentSchedulingDetails = new List<T_FM_DEPARTMENT_SCHEDULING_DETAIL>();
                    foreach (var e in nodeSchedulingList)
                    {
                        var classPerson = classPersons.Where(i => i.TEAM_ID == e.TEAM_ID).ToList();
                        foreach (var t in classPerson)
                        {
                            T_FM_DEPARTMENT_SCHEDULING_DETAIL sd = new T_FM_DEPARTMENT_SCHEDULING_DETAIL()
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = e.ORG_ID,
                                PERSON_ID = t.PERSON_ID,
                                DEPARTMENT_SCHEDULING_ID = e.ID,
                            };
                            departmentSchedulingDetails.Add(sd);
                        }
                    }
                    this.UnifiedCommit(() =>
                    {
                        this.DeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(i => i.Nav_DepartmentScheduling.DEPARTMENT_ID == entity.ID
                      && i.Nav_DepartmentScheduling.DATE_TIME == entity.Nav_DepartmentScheduling.FirstOrDefault().DATE_TIME);
                        this.DeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING>(i => i.DEPARTMENT_ID == entity.ID
                        && i.DATE_TIME == entity.Nav_DepartmentScheduling.FirstOrDefault().DATE_TIME);
                        if (nodeSchedulingList.Count > 0)
                            this.BantchAddEntityNoCommit(nodeSchedulingList);
                        if (departmentSchedulingDetails.Count > 0)
                            this.BantchAddEntityNoCommit(departmentSchedulingDetails);
                    });
                }
                else
                    this.ThrowError("040001");
                return true;
            });
        }

        /// <summary>
        /// 应用当日所有节点
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("ApplyAll")]
        public JsonActionResult<bool> ApplyAll([FromBody] T_FM_DEPARTMENT entity)
        {
            return SafeExecute<bool>(() =>
            {
                KeywordFilter filter = new KeywordFilter();
                if (entity != null && entity.ID != null && entity.ORG_ID != null && entity.Nav_DepartmentScheduling != null)
                {
                    var shiftList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.ORG_ID == entity.ORG_ID
                    && s.DATE_TIME == entity.Nav_DepartmentScheduling.FirstOrDefault().DATE_TIME, filter);

                    //获取当前排班单元排班配置
                    var sIds = shiftList.Where(s => s.DEPARTMENT_ID == entity.ID).Select(s => s.ID);

                    //排除不存在数据库中并且是删除状态的数据
                    List<T_FM_DEPARTMENT_SCHEDULING> nodeSchedulingList = entity.Nav_DepartmentScheduling.Select(e => new T_FM_DEPARTMENT_SCHEDULING
                    {
                        ORG_ID = entity.ORG_ID,
                        ID = e.ID,
                        DEPARTMENT_ID = e.DEPARTMENT_ID,
                        DEPARTMENT_CALENDAR_CONFIG_ID = e.DEPARTMENT_CALENDAR_CONFIG_ID,
                        DATE_TIME = e.DATE_TIME,
                        CLASS_ID = e.CLASS_ID,
                        TEAM_ID = e.TEAM_ID,
                        IS_DELETED = e.IS_DELETED,
                        ENABLE_STATUS = e.ENABLE_STATUS
                    }).Where(n => !(!sIds.Contains(n.ID) && n.IS_DELETED == true)).ToList();

                    //获取所有排班单元（排除当前配置项）
                    var spanList = this.GetEntities<T_FM_DEPARTMENT>(n => n.DEPARTMENT_TYPE == (int)FMDepartmentType.Workshop && n.ID != entity.ID, filter);
                    //获取要删除的排班信息（排除当前排班单元）
                    var delIds = shiftList.Where(s => s.DEPARTMENT_ID != entity.ID).Select(d => d.ID).ToList();
                    //获取要删除排班明细表的数据
                    var delDetailIds = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(x => delIds.Contains(x.DEPARTMENT_SCHEDULING_ID), filter).Select(x => x.ID).ToList();

                    var batchData = nodeSchedulingList.Where(b => b.IS_DELETED == false);
                    List<T_FM_DEPARTMENT_SCHEDULING> batchDataList = new List<T_FM_DEPARTMENT_SCHEDULING>();
                    foreach (var item in spanList)
                    {
                        var shiftSpanList = batchData.Select(b => new T_FM_DEPARTMENT_SCHEDULING
                        {
                            ORG_ID = entity.ORG_ID,
                            ID = new Guid(),
                            DEPARTMENT_ID = item.ID,
                            DEPARTMENT_CALENDAR_CONFIG_ID = b.DEPARTMENT_CALENDAR_CONFIG_ID,
                            DATE_TIME = b.DATE_TIME,
                            CLASS_ID = b.CLASS_ID,
                            TEAM_ID = b.TEAM_ID,
                            CREATE_TIME = DateTime.Now,
                            MODIFY_TIME = DateTime.Now,
                            IS_DELETED = b.IS_DELETED,
                            ENABLE_STATUS = b.ENABLE_STATUS
                        });
                        batchDataList.AddRange(shiftSpanList);
                    }


                    //保存当前配置
                    this.UnifiedCommit(() =>
                    {
                        //保存当前配置
                        this.BantchSaveEntityNoCommit(nodeSchedulingList);
                        //先清空明细表数据
                        this.BantchDeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(delDetailIds);
                        //清空其它排班
                        this.BantchDeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING>(delIds);
                        //重新创建新的排班
                        this.BantchAddEntityNoCommit(batchDataList);
                    });

                }
                else
                    this.ThrowError("040001");
                return true;
            });
        }

        /// <summary>
        /// 部门保存(新增安全员子表)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdateAll")]
        public JsonActionResult<bool> UpdateAll([FromBody] T_FM_DEPARTMENT entity)
        {
            return SafeExecute<bool>(() =>
            {
                //var safeUser = entity==null?null:entity.Nav_SafeUser;
                //entity.Nav_SafeUser = null;
                T_FM_TEAM addTeamInfo = null;
                T_FM_TEAM updateTeamInfo = null;
                var teamInfos = new List<T_FM_TEAM>();
                if (entity.DEPARTMENT_TYPE == (int)FMDepartmentType.Class)
                {
                    var teamInfo = this.GetEntity<T_FM_TEAM>(t => t.DEPARTMENT_ID == entity.ID);
                    if (teamInfo == null)
                    {
                        addTeamInfo = new T_FM_TEAM()
                        {
                            NAME = entity.NAME,
                            DEPARTMENT_ID = entity.ID,
                            //CHARGE_PERSON_ID = entity.USER_ID,
                            ORG_ID = entity.ORG_ID,
                            ID = Guid.NewGuid(),
                        };
                    }
                    else
                    {
                        teamInfo.NAME = entity.NAME;
                        teamInfo.DEPARTMENT_ID = entity.ID;
                        //teamInfo.CHARGE_PERSON_ID = entity.USER_ID;
                        updateTeamInfo = teamInfo;
                    }
                }
                //判断组织下是否有人
                bool haveUser = false;
                string message = "";
                //List<T_FM_DEPARTMENT_PRODUCTION_UNIT> productionUnit = null;
                entity.Nav_ProdutionUnit = null;
                //if (productionUnit != null && productionUnit.Any())
                //{
                //    productionUnit.ForEach(t =>
                //    {
                //        t.ORG_ID = entity.ORG_ID; t.DEPARTMENT_ID = entity.ID;
                //        t.Nav_Enums = null;
                //    });
                //}
                var unitList = new List<T_FM_DEPARTMENT_PRODUCTION_UNIT>();
                var userUnitList = new List<T_FM_USER_PRODUCTION_UNIT>();
                var departUpdateList = new List<T_FM_DEPARTMENT>();
                var entityUpdateList = new List<T_FM_DEPARTMENT>();
                var userUpdateList = new List<T_FM_USER>();
                var userList = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID), "Nav_ProdutionUnit").ToList();
                var deleteDepartIds = new List<Guid>();
                var deleteUserIds = new List<Guid>();
                if (entity.PRODUCTION_UNIT_ID != null)
                {
                    //var enumIds = productionUnit.Select(t => t.ENUMS_ID).Distinct().ToList();
                    //var enumList = this.GetEntity<T_FM_ENUMS>(t => t.CODE == "BSMineTypeEnum" && t.VALUE == entity.MineType);
                    //查所有下级部门组织
                    List<Guid> departmentId = new List<Guid>();
                    departmentId.Add(entity.ID);
                    List<Guid> departmentIds = new List<Guid>();
                    var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value;
                    DepartmentService.GetDepartmentIds(orgId, departmentId, ref departmentIds);
                    var departmentList = this.GetEntities<T_FM_DEPARTMENT>(t => departmentIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(orgId), "Nav_ProdutionUnit").ToList();
                    foreach (var t in departmentList)
                    {
                        t.ENABLE_STATUS = entity.ENABLE_STATUS;
                        t.IS_DELETED = entity.IS_DELETED;
                        t.MineType = entity.MineType;
                        t.PRODUCTION_UNIT_ID = entity.PRODUCTION_UNIT_ID;
                        if (entity.ENABLE_STATUS == 1)
                        {
                            t.IS_DELETED = true;
                        }
                        departUpdateList.Add(t);
                        var userFirst = userList.FirstOrDefault(m => m.DEPARTMENT_ID == t.ID);
                        if (userFirst != null && entity.ENABLE_STATUS == 1)
                        {
                            haveUser = true;
                            message = "当前组织的下级组织存在人员，请先到用户列表修改对应组织";
                        }
                        T_FM_DEPARTMENT_PRODUCTION_UNIT unit = new T_FM_DEPARTMENT_PRODUCTION_UNIT();
                        unit.ORG_ID = t.ORG_ID; unit.DEPARTMENT_ID = t.ID; //unit.ENUMS_ID = enumList?.ID;
                        unit.Nav_Enums = null; unit.DEPART_UNIT_ID = entity.PRODUCTION_UNIT_ID;
                        unitList.Add(unit);
                        if (t.Nav_ProdutionUnit != null && t.Nav_ProdutionUnit.Any())
                        {
                            var ids = t.Nav_ProdutionUnit.Select(t => t.ID).ToList();
                            deleteDepartIds.AddRange(ids);
                        }
                    }
                    //departmentList.ForEach(t => t.MineType = entity.MineType);
                    var userListTemp = userList.Where(t => t.DEPARTMENT_ID != null && departmentIds.Contains(t.DEPARTMENT_ID.Value)).ToList();
                    userListTemp.ForEach(t =>
                    {
                        //var enumValues = new List<string>();
                        //productionUnit.ForEach(t1 =>
                        //{
                        //    T_FM_USER_PRODUCTION_UNIT unit = new T_FM_USER_PRODUCTION_UNIT();
                        //    unit.ORG_ID = t.ORG_ID; unit.USER_ID = t.ID; unit.ENUMS_ID = t1.ENUMS_ID;
                        //    unit.Nav_Enums = null;
                        //    userUnitList.Add(unit);
                        //    var value = enumList.FirstOrDefault(m => m.ID == t1.ENUMS_ID)?.VALUE.ToString();
                        //    enumValues.Add(value);
                        //});
                        //t.MineType = string.Join(",", enumValues);
                        userUpdateList.Add(t);
                        T_FM_USER_PRODUCTION_UNIT unit = new T_FM_USER_PRODUCTION_UNIT();
                        unit.ORG_ID = t.ORG_ID; unit.USER_ID = t.ID; //unit.ENUMS_ID = enumList?.ID;
                        unit.Nav_Enums = null; unit.PRODUCTION_UNIT_ID = entity.PRODUCTION_UNIT_ID;
                        userUnitList.Add(unit);
                        if (t.Nav_ProdutionUnit != null && t.Nav_ProdutionUnit.Any())
                        {
                            var ids = t.Nav_ProdutionUnit.Select(t => t.ID).ToList();
                            deleteUserIds.AddRange(ids);
                        }
                    });
                }
                if (entity.USER_ID != null)
                {
                    var user = userList.FirstOrDefault(t => t.ID == entity.USER_ID);
                    if (addTeamInfo != null)
                        addTeamInfo.CHARGE_PERSON_ID = user.PERSON_ID;
                    if (updateTeamInfo != null)
                        updateTeamInfo.CHARGE_PERSON_ID = user.PERSON_ID;
                }
                if (entity.CATEGORY == FMCATEGORY.VIRTUAL)
                {
                    var userFirst = userList.FirstOrDefault(t => t.DEPARTMENT_ID == entity.ID);
                    if (userFirst != null)
                    {
                        haveUser = true;
                        message = "当前组织存在人员，不可配置虚拟组织，请先到用户列表修改人员组织";
                    }
                }
                if (entity.ENABLE_STATUS == 1)
                {
                    entity.IS_DELETED = true;
                    var userFirst = userList.FirstOrDefault(t => t.DEPARTMENT_ID == entity.ID);
                    if (userFirst != null)
                    {
                        haveUser = true;
                        message = "当前组织存在人员，请先到用户列表修改对应组织";
                    }
                    if (updateTeamInfo != null)
                    {
                        updateTeamInfo.ENABLE_STATUS = 1;
                        updateTeamInfo.IS_DELETED = true;
                        teamInfos.Add(updateTeamInfo);
                    }
                }
                entityUpdateList.Add(entity);
                foreach (var item in departUpdateList)
                {
                    item.Nav_User = null; item.Nav_ProdutionUnit = null; item.Nav_Unit = null; item.Nav_Parent = null; item.Nav_DepartmentUser = null;
                }
                foreach (var item in entityUpdateList)
                {
                    item.Nav_User = null; item.Nav_ProdutionUnit = null; item.Nav_Unit = null; item.Nav_Parent = null; item.Nav_DepartmentUser = null;
                }
                if (haveUser)
                {
                    throw new Exception(message);
                }

                var listDepChange = new List<T_FM_DEPARTMENT>();
                if (entityUpdateList != null && entityUpdateList.Count() > 0)
                {
                    var listDepID = entityUpdateList.Select(e => e.ID);
                    listDepChange = GetEntities<T_FM_DEPARTMENT>(e => listDepID.Contains(e.ID), null).ToList();
                    //listDepChange = listDepChange.Where(e => !e.IS_DELETED).ToList();
                }
                this.UnifiedCommit(() =>
                {
                    //BantchUpdateEntity_noneBase
                    //if (safeUser != null && safeUser.Any())
                    //    this.BantchSaveEntityNoCommit(safeUser);
                    if (addTeamInfo != null)
                        this.UpdateEntityNoCommit(addTeamInfo);
                    if (deleteDepartIds != null && deleteDepartIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FM_DEPARTMENT_PRODUCTION_UNIT>(deleteDepartIds);
                    if (deleteUserIds != null && deleteUserIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FM_USER_PRODUCTION_UNIT>(deleteUserIds);
                    if (userUpdateList != null && userUpdateList.Any())
                        this.BantchSaveEntityNoCommit(userUpdateList);
                    if (unitList != null && unitList.Any())
                        this.BantchSaveEntityNoCommit(unitList);
                    if (userUnitList != null && userUnitList.Any())
                        this.BantchSaveEntityNoCommit(userUnitList);
                    if (departUpdateList != null && departUpdateList.Any())
                        this.BantchUpdateEntity_noneBase(departUpdateList);
                    if (teamInfos != null && teamInfos.Any())
                        this.BantchUpdateEntity_noneBase(teamInfos);
                    if (listDepChange != null && listDepChange.Any())
                    {
                        this.BantchUpdateEntity_noneBase(entityUpdateList);
                    }
                    else
                    {
                        this.UpdateEntityNoCommit(entity);
                    }
                    //if (listDepChange != null && listDepChange.Any())
                    //    BantchSaveEntityNoCommit(listDepChange);
                    //if (entity != null)
                    //    this.UpdateEntityNoCommit(entity);
                });
                return true;
            });
        }

        /// <summary>
        /// 获得单条实体数据(新增部门人员子表)
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAll")]
        public JsonActionResult<T_FM_DEPARTMENT> GetAll([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_FM_DEPARTMENT main = new T_FM_DEPARTMENT();
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (!string.IsNullOrEmpty(id))
                {
                    var entity = this.GetEntity<T_FM_DEPARTMENT>(id, false, "Nav_SafeUser", "Nav_DepartmentUser", "Nav_Parent", "Nav_ChargeUser", "Nav_Unit",
                        "Nav_SafeUser.Nav_User", "Nav_DepartmentUser.Nav_User", "Nav_DepartmentUser.Nav_User.Nav_ApproveRole", "Nav_User", "Nav_Person", "Nav_Person.Nav_Post", "Nav_ProdutionUnit.Nav_Enums");
                    if (entity != null)
                    {
                        main = entity;
                        if (entity.Nav_DepartmentUser != null && entity.Nav_DepartmentUser.Any())
                        {
                            main.Nav_DepartmentUser = entity.Nav_DepartmentUser.Where(t => !t.Nav_User.CODE.Contains("admin")).OrderBy(m => m.Nav_User.NUM).ToList();
                        }
                        else
                        {
                            //List<Guid> departmentIds = new List<Guid>();
                            //List<Guid> departmentId = new List<Guid>();
                            //departmentId.Add(main.ID);
                            //GetAllDepartmentId(departmentId, ref departmentIds);
                            var users = this.GetEntities<T_FM_USER>(t => main.ID == t.DEPARTMENT_ID && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && !t.CODE.Contains("admin"), new BaseFilter(main.ORG_ID), new string[] { "Nav_ApproveRole", "Nav_Person.Nav_Post" }).ToList();
                            if (users.Any() && users != null)
                            {
                                List<T_FM_DEPARTMENT_USER> departmentUser = new List<T_FM_DEPARTMENT_USER>();
                                users.ForEach(u =>
                                {
                                    T_FM_DEPARTMENT_USER us = new T_FM_DEPARTMENT_USER();
                                    us.DEPARTMENT_ID = u.DEPARTMENT_ID;
                                    us.USER_ID = u.ID;
                                    us.Nav_User = u;
                                    departmentUser.Add(us);
                                });
                                //main.Nav_DepartmentUser = departmentUser.OrderByDescending(e => e.Nav_User.APPROVE_ROLE_ID).ToList();//wyw 有审批角色的显示再前面
                                main.Nav_DepartmentUser = departmentUser.OrderBy(t => t.Nav_User?.NUM).ThenByDescending(e => e.Nav_User.Nav_ApproveRole?.CODE).ToList();
                            }
                        }
                    }
                }
                return main;
            });
        }
        /// <summary>
        /// 返回所有部门节点
        /// <returns></returns>
        private void GetAllDepartmentId(List<Guid> departmentId, ref List<Guid> allDepartmentIds)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            allDepartmentIds.AddRange(departmentId);
            var department = GetEntities<T_FM_DEPARTMENT>(t => departmentId.Contains((Guid)t.PARENT_ID), new BaseFilter(orgId));
            if (department != null && department.Any())
            {
                var departmentIds = department.Select(u => u.ID).ToList();
                GetAllDepartmentId(departmentIds, ref allDepartmentIds);
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedPost")]
        public PagedActionResult<T_FM_USER_POST> OrderPagedPost([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_USER_POST> result)
            {
                Guid DEPARTMENT_ID = Guid.Empty;
                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Any())
                {
                    var rules = pageFilter.FilterGroup.Rules;
                    foreach (var rule in rules)
                    {
                        if (rule.Field == "DEPARTMENT_ID")
                        {
                            DEPARTMENT_ID = new Guid(rule.Value.ToString());
                            rules.Remove(rule);
                            break;
                        }
                    }
                    pageFilter.FilterGroup.Rules = rules;
                }
                else if (pageFilter.FilterGroup.Groups != null && pageFilter.FilterGroup.Groups.Any())
                {
                    var rules = pageFilter.FilterGroup.Groups.ToList()[0].Rules;
                    foreach (var rule in rules)
                    {
                        if (rule.Field == "DEPARTMENT_ID")
                        {
                            DEPARTMENT_ID = new Guid(rule.Value.ToString());
                            rules.Remove(rule);
                            break;
                        }
                    }
                    //pageFilter.FilterGroup.Groups = rules;
                }

                if (DEPARTMENT_ID != Guid.Empty)
                {
                    List<Guid> listPersonID = new List<Guid>();
                    var IListPersons = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == DEPARTMENT_ID && e.PERSON_ID.HasValue && !e.IS_DELETED && e.ENABLE_STATUS == 0, null, null);
                    if (IListPersons != null && IListPersons.Any())
                    {
                        foreach (var item in IListPersons)
                        {
                            listPersonID.Add(item.PERSON_ID.Value);
                        }
                    }
                    //var listPersonID = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == DEPARTMENT_ID && e.PERSON_ID.HasValue, null, null).ToList().Select(e => e.PERSON_ID);

                    if (listPersonID != null && listPersonID.Any())
                    {
                        var IlistPerson = GetEntities<T_FM_PERSON>(e => e.POST_ID.HasValue && listPersonID.Contains(e.ID), null, null);
                        if (IlistPerson != null && IlistPerson.Any())
                        {
                            List<Guid> listPostID = new List<Guid>();
                            foreach (var item in IlistPerson)
                            {
                                listPostID.Add(item.POST_ID.Value);
                            }

                            if (listPostID.Any())
                            {
                                Expression<Func<T_FM_USER_POST, bool>> expression = e => !e.IS_DELETED && e.STATUS == 1 && listPostID.Contains(e.ID);
                                PagedActionResult<T_FM_USER_POST> orderPageEntities = this.GetOrderPageEntities<T_FM_USER_POST>(expression, pageFilter, null);
                                result.Data = orderPageEntities.Data;
                                result.TotalCount = orderPageEntities.TotalCount;
                            }
                        }

                    }
                }
                else
                {
                    result.Data = new List<T_FM_USER_POST>();
                    result.TotalCount = 0;
                }
            });
        }
        /// <summary>
        /// 根据部门和人员返回人员信息
        /// </summary>
        /// <param name="userModel"></param>
        /// <returns></returns>
        [HttpPost, Route("GetSelectUsers")]
        public JsonActionResult<List<UserModel>> GetSelectUsers([FromBody] SelectUsersModel userModel)
        {
            return SafeExecute<List<UserModel>>(() =>
            {
                Expression<Func<T_FM_USER, bool>> express = t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
                Expression<Func<T_FM_USER, bool>> selectExpress = t => false;
                if (userModel == null || (!userModel.UserIds.Any() && !userModel.DepartmentIds.Any()))
                {
                    return new List<UserModel>();
                }
                else
                {

                    if (userModel.UserIds.Any())
                    {
                        var userIds = userModel.UserIds.Select(i => Guid.Parse(i));
                        selectExpress = selectExpress.Or(item => userIds.Contains(item.ID));
                    }
                    if (userModel.DepartmentIds.Any())
                    {
                        var departmentIds = userModel.DepartmentIds.Select(i => Guid.Parse(i));
                        selectExpress = selectExpress.Or(item => departmentIds.Contains(item.DEPARTMENT_ID ?? Guid.Empty));
                    }
                }
                express = express.And(selectExpress);
                var filter = new BaseFilter(Guid.Parse(userModel.OrgId));
                filter.SelectField = new string[] { "ID", "NAME" };
                var deUsers = this.GetEntities<T_FM_USER>(express, filter);
                return deUsers.Select(u => new UserModel { UserId = u.ID.ToString(), UserName = u.NAME }).ToList();
            });
        }

        /// <summary>
        /// 获取部门和安全员信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("DepartmentAndUserEntities")]
        public JsonActionResult<IEnumerable<T_FM_DEPARTMENT>> DepartmentAndUserEntities([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                bool? isMaster = null;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    isMaster = Convert.ToBoolean(filter.Keyword);
                }
                filter.FilterGroup.Rules.Add(new FilterRule() { Field = "ENABLE_STATUS", Operate = FilterOperate.Equal, Value = 0 });
                var result = GetOrderEntities<T_FM_DEPARTMENT>(null, filter, null);
                if (result.Count() > 0 && isMaster.HasValue)
                {
                    IEnumerable<Guid> listUserID = null;
                    T_FM_USER userCheck = null;
                    //Nav_UserList 
                    if (isMaster.Value)
                    {
                        //负责人
                        result = result.Where(e => e.USER_ID.HasValue);
                        listUserID = result.Select(e => e.USER_ID.Value).Distinct();
                        if (listUserID != null && listUserID.Any())
                        {
                            var listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
                            foreach (var item in result)
                            {
                                //找负责人 
                                userCheck = listUser.FirstOrDefault(e => e.ID == item.USER_ID.Value);
                                if (userCheck != null)
                                {
                                    item.Nav_UserList = new List<T_FM_USER>() { userCheck };
                                }
                            }
                        }
                    }
                    else
                    {
                        //安全员
                        var listDepID = result.Select(e => e.ID);
                        var rows = GetEntities<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安全"), null, null);
                        IEnumerable<Guid> listRoleID = null;
                        if (rows != null && rows.Any())
                        {
                            listRoleID = rows.Select(e => e.ID);
                        }
                        if (listRoleID != null && listRoleID.Any())
                        {
                            var listUser = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && listDepID.Contains(e.DEPARTMENT_ID.Value) && e.APPROVE_ROLE_ID.HasValue && listRoleID.Contains(e.APPROVE_ROLE_ID.Value), null, null);
                            foreach (var item in result)
                            {
                                userCheck = listUser.FirstOrDefault(e => e.DEPARTMENT_ID == item.ID);
                                if (userCheck != null)
                                {
                                    item.Nav_UserList = new List<T_FM_USER>() { userCheck };
                                }
                            }

                        }
                    }
                }
                result = result.Where(e => e.Nav_UserList != null && e.Nav_UserList.Any());
                return result;
            });
        }


        #region      外包单位 组织

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateWB")]
        public JsonActionResult<bool> FullUpdateWB([FromBody] T_FM_DEPARTMENT entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (!entity.ORG_ID.HasValue)
                {
                    throw new Exception("获取传参失败！");
                }
                T_FM_DEPARTMENT modelP = null;
                if (entity.PARENT_ID == null || entity.PARENT_ID == Guid.Empty)
                {
                    List<EnumsResult> list = APT.Utility.DataHelper.GetEnum("FilePathHead");
                    modelP = GetEntity<T_FM_DEPARTMENT>(e => e.NAME == "外包虚拟组织" && e.CATEGORY == FMCATEGORY.WB);

                    if (modelP == null)
                    {
                        //新增外包初始节点 
                        var root = GetEntity<T_FM_DEPARTMENT>(e => e.DEPARTMENT_TYPE == 5 && e.ENABLE_STATUS == 0);

                        string depID = "1BBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB";
                        string ORG_ID = entity.ORG_ID.Value.ToString().ToUpper();
                        //if (ORG_ID == FilePathHead.XLK.GetDescription())
                        //{
                        //    depID = "1BBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB";
                        //}
                        //else if (ORG_ID == FilePathHead.LYXT.GetDescription())
                        //{
                        //    depID = "2BBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB";
                        //}
                        //else if (ORG_ID == FilePathHead.LYYL.GetDescription())
                        //{
                        //    depID = "3BBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB";
                        //}
                        //else if (ORG_ID == FilePathHead.DCJD.GetDescription())
                        //{
                        //    depID = "4BBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB";
                        //}
                        //else if (ORG_ID == FilePathHead.GXBB.GetDescription())
                        //{
                        //    depID = "5BBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB";
                        //}
                        //else if (ORG_ID == FilePathHead.SPSD.GetDescription())
                        //{
                        //    depID = "8BBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB";
                        //}

                        modelP = new T_FM_DEPARTMENT();
                        modelP.ID = new Guid(depID);
                        modelP.NAME = "外包虚拟组织";
                        modelP.CODE = "WB";
                        modelP.ORG_ID = entity.ORG_ID;
                        modelP.CATEGORY = FMCATEGORY.WB;
                        modelP.NUM = 1000;
                        modelP.DEPARTMENT_TYPE = 0;//所有的外包定位在一个部门里面

                        modelP.PARENT_ID = root.ID;//绑在公司下级

                    }
                    entity.PARENT_ID = modelP.ID;
                }

                entity.DEPARTMENT_TYPE = 1;//默认到车间级别
                entity.CATEGORY = FMCATEGORY.WB;//操作的都是外包的
                entity.Nav_UserDeparts = null;



                #region    外包管理员 添加 组织权限

                var role = GetEntity<T_FM_ROLE>(e => e.NAME == "外包管理员");
                bool isAddRole = false;
                if (role == null)
                {
                    isAddRole = true;
                    role = new T_FM_ROLE();
                    role.ID = Guid.NewGuid();
                    role.ORG_ID = entity.ORG_ID;
                    role.CODE = "WBGL";
                    role.NAME = "外包管理员";
                    role.NAME_ACRONYM = ";";
                    role.PLATFORM_TYPE = 0;
                    role.REMARK = "系统自动添加外包管理员";
                }
                List<T_FM_ROLE_DEPARTMENT> listRoleDep = new List<T_FM_ROLE_DEPARTMENT>();
                List<Guid> listDepID = new List<Guid>() { entity.ID };
                if (entity.PARENT_ID.HasValue)
                {
                    listDepID.Add(entity.PARENT_ID.Value);
                }
                var lisrRDCheck = GetEntities<T_FM_ROLE_DEPARTMENT>(e => e.ROLE_ID == role.ID && listDepID.Contains(e.DEPARTMENT_ID), null, null);
                T_FM_ROLE_DEPARTMENT check = null;
                foreach (var item in listDepID)
                {
                    check = lisrRDCheck.FirstOrDefault(e => e.DEPARTMENT_ID == item);
                    if (check == null)
                    {
                        listRoleDep.Add(new T_FM_ROLE_DEPARTMENT()
                        {
                            ID = Guid.NewGuid(),
                            ORG_ID = entity.ORG_ID,
                            DEPARTMENT_ID = item,
                            ROLE_ID = role.ID,
                        });
                    }
                }
                #endregion

                this.UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    if (modelP != null)
                        this.UpdateEntityNoCommit(modelP);
                    if (isAddRole)//添加角色
                        this.UpdateEntityNoCommit(role);
                    if (listRoleDep != null && listRoleDep.Any())
                        this.BantchSaveEntityNoCommit(listRoleDep);
                });
                return true;
            });
        }

        #endregion
    }
}
