using APT.BaseData.Domain.Entities;
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.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.SC
{
    [Route("api/SC/SCMTMeeting")]
    public class SCMTMeetingController : AuthorizeApiController<T_SC_MT_MEETING>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMUserService FMUserService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IPFCodeRuleService PFCodeRuleService { get; set; }
        IFMNotificationTaskService FMNotificActionTaskService { get; set; }
        IFMNoticeService FMNoticeService { get; set; }
        public SCMTMeetingController(IFMUserService fMUserService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IPFCodeRuleService pFCodeRuleService, IFMNotificationTaskService fMNotificActionTaskService, IFMNoticeService noticeService)
        {
            FMUserService = fMUserService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            PFCodeRuleService = pFCodeRuleService;
            FMNotificActionTaskService = fMNotificActionTaskService;
            FMNoticeService = noticeService;
        }

        /// <summary>
        /// 根据会议类型获取参会人员信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetPAll")]
        public JsonActionResult<List<T_SC_MT_MEETING_PALL>> GetPAll([FromBody] KeywordFilter filter)
        {
            //2023-12-29 
            //安委会 取配置人员 
            //否则 按 发起人  发起部门 会议类型 取上次 会议的参会人
            return SafeExecute<List<T_SC_MT_MEETING_PALL>>(() =>
            {
                List<T_SC_MT_MEETING_PALL> listResult = new List<T_SC_MT_MEETING_PALL>();
                List<T_FM_USER> listUsers = new List<T_FM_USER>();
                //基层安全会按部门 / 车间 / 班组点选或模糊查询，默认部门所有人员向下包含
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    BaseFilter fiterMT = new BaseFilter(filter.OrgId);
                    fiterMT.Order = DbOrder.DESC;
                    fiterMT.Orders.Add(new DataOrder() { Field = "CREATE_TIME", Order = DbOrder.DESC });
                    SCMEETINGTYPE MEETINGTYPE = (SCMEETINGTYPE)int.Parse(filter.Parameter1);
                    if (MEETINGTYPE == SCMEETINGTYPE.SafetyBoard)
                    {
                        //安委会 取 配置的人
                        var listAgency = GetEntities<T_OG_AGENCY>(e => !e.IS_DELETED && e.NAME == "安全生产委员会", null, null);
                        if (listAgency != null && listAgency.Any())
                        {
                            var AGENCY_ID = listAgency.Select(e => e.ID).ToList()[0];
                            var users = GetEntities<T_OG_AGENCY_USER>(e => e.AGENCY_ID == AGENCY_ID, null, "Nav_User");
                            if (users != null && users.Any())
                            {
                                foreach (var item in users)
                                {
                                    listUsers.Add(item.Nav_User);
                                }
                            }
                        }
                        //系统管理>安全生产组织保障配置>机构表 安全生产委员会（待优化）
                        if (listUsers.Count < 1)
                        {
                            //部门级负责人 安全员
                            //FMDepartmentType.部门 =0
                            var listDep0 = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.DEPARTMENT_TYPE == 0, null, null);
                            var listApprovreRole = GetEntities<T_PF_APPROVAL_ROLE>(e => !e.IS_DELETED && (e.NAME == "部门负责人" || e.NAME == "部门安全员" || e.NAME == "安环部负责人" || e.NAME == "安环部安全员"), null, null);
                            if (listDep0 != null && listDep0.Any() && listApprovreRole != null && listApprovreRole.Any())
                            {
                                List<Guid> ids = listDep0.Select(e => e.ID).ToList();
                                List<Guid> idsApprove = listApprovreRole.Select(e => e.ID).ToList();
                                var users = GetEntities<T_FM_USER>(e => !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.DEPARTMENT_ID.HasValue && ids.Contains(e.DEPARTMENT_ID.Value) && e.APPROVE_ROLE_ID.HasValue && idsApprove.Contains(e.APPROVE_ROLE_ID.Value), null, new string[] { "Nav_Department", "Nav_Person.Nav_Post" });
                                if (users != null && users.Any())
                                {
                                    listUsers = users.OrderBy(e => e.DEPARTMENT_ID).ToList();
                                }
                            }
                        }
                    }
                    else
                    {
                        //找上次
                        var meetLast = GetEntity<T_SC_MT_MEETING>(e => e.USER_ID_ORIGINATOR == LoginID && e.MEETINGTYPE == MEETINGTYPE && e.PLANSET_ID.HasValue && !e.IS_DELETED && e.Nav_ListPAll != null && e.Nav_ListPAll.Any(), fiterMT, "Nav_ListPAll");
                        if (meetLast != null && meetLast.Nav_ListPAll != null && meetLast.Nav_ListPAll.Any())
                        {
                            var listUserId = meetLast.Nav_ListPAll.Where(e => e.PERSONNATURE == PersonNature.JOIN).Select(e => e.USER_ID).Distinct();
                            listUsers = GetEntities<T_FM_USER>(e => listUserId.Contains(e.ID) && !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.DEPARTMENT_ID.HasValue, null, "Nav_Department", "Nav_Person.Nav_Post").OrderBy(e => e.DEPARTMENT_ID).ToList();
                        }
                        else
                        {
                            //第一次 基层安委会
                            var loginInfo = GetEntity<T_FM_USER>(LoginID.Value, new string[] { "Nav_Department", "Nav_Person.Nav_Post" });
                            if (MEETINGTYPE == SCMEETINGTYPE.BasicSecurity)
                            {
                                ////基层安全会按部门/车间/班组点选或模糊查询，默认部门所有人员向下包含 
                                ////获取 层级 及以下 所有人
                                //listUsers = FMUserService.GetDownUser(loginInfo.DEPARTMENT_ID.Value, new string[] { "Nav_Department", "Nav_Person.Nav_Post" });

                                //部门负责人发起，参会人员为：部门内所属人员 + 车间安全员及负责人
                                //车间负责人发起，参会人员为：车间内所属人员 + 班组长
                                //班组负责人发起，参会人员为：班组内成员

                                //FMDepartmentType 部门 = 0, 车间 = 1, 班组 = 2, 公司 = 3
                                switch (loginInfo.Nav_Department.DEPARTMENT_TYPE)
                                {
                                    case 0:
                                    case 1:
                                        listUsers = FMUserService.GetUserContentNextHead(loginInfo.DEPARTMENT_ID.Value);
                                        break;
                                    case 2:
                                    case 3:
                                        //班组 = 2, 公司 = 3
                                        listUsers = FMUserService.GetDownUser(loginInfo.DEPARTMENT_ID.Value, new string[] { "Nav_Department", "Nav_Person.Nav_Post" });
                                        break;
                                    default:
                                        break;
                                }
                            }
                            else
                            {
                                //别的会议 第一次 自己选人
                            }
                        }
                    }

                    if (listUsers != null && listUsers.Any() && (listUsers[0].Nav_Department == null || listUsers[0].Nav_Person == null))
                    {
                        var listDepID = listUsers.Where(e => e.DEPARTMENT_ID.HasValue).Select(e => e.DEPARTMENT_ID.Value).Distinct();
                        var listPersonID = listUsers.Where(e => e.PERSON_ID.HasValue).Select(e => e.PERSON_ID.Value).Distinct();

                        if (listDepID.Any() && listPersonID.Any())
                        {
                            var listDep = GetEntities<T_FM_DEPARTMENT>(e => listDepID.Contains(e.ID), null);
                            var listPer = GetEntities<T_FM_PERSON>(e => listPersonID.Contains(e.ID), null, "Nav_Post");
                            foreach (var item in listUsers)
                            {
                                if (item.DEPARTMENT_ID.HasValue)
                                    item.Nav_Department = listDep.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID);
                                if (item.PERSON_ID.HasValue)
                                    item.Nav_Person = listPer.FirstOrDefault(e => e.ID == item.PERSON_ID);
                            }
                        }
                    }

                    var MEETING_ID = new Guid(filter.Keyword);
                    for (int i = 0; i < listUsers.Count; i++)
                    {
                        T_SC_MT_MEETING_PALL temp = new T_SC_MT_MEETING_PALL();
                        temp.ID = Guid.NewGuid();
                        temp.MEETING_ID = MEETING_ID;
                        temp.USER_ID = listUsers[i].ID;
                        temp.Nav_User = listUsers[i];
                        temp.ORG_ID = filter.OrgId;
                        temp.PERSONTYPE = SCMEETINGPERSONTYPE.ALL;
                        listResult.Add(temp);
                    }
                }
                return listResult;
            });
        }


        /// <summary>
        /// 根据会议内容 获取 会议意见
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetListContent")]
        public JsonActionResult<List<T_SC_MT_MEETING_CONTENT>> GetListContent([FromBody] KeywordFilter filter)
        {
            return SafeExecute<List<T_SC_MT_MEETING_CONTENT>>(() =>
            {
                List<T_SC_MT_MEETING_CONTENT> listResult = new List<T_SC_MT_MEETING_CONTENT>();
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    List<Guid> ids = (from i in filter.Keyword.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                      select new Guid(i)).ToList();

                    var MEETING_ID = new Guid(filter.Parameter1);
                    var content = GetEntities<T_SC_MT_CONTENT_NAME>(e => ids.Contains(e.ID), null, null).OrderBy(e => e.ID);

                    if (content.Any())
                    {
                        List<T_SC_MT_CONTENT_NAME> listContentName = content.ToList();
                        for (int i = 0; i < listContentName.Count; i++)
                        {
                            T_SC_MT_MEETING_CONTENT temp = new T_SC_MT_MEETING_CONTENT();
                            temp.ID = Guid.NewGuid();
                            temp.MEETING_ID = MEETING_ID;
                            temp.Nav_ContentName = listContentName[i];
                            listResult.Add(temp);
                        }
                    }
                }
                return listResult;
            });
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SC_MT_MEETING entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.DEPARTMENT_ID == Guid.Empty)
                {
                    throw new Exception("会议部门不能为空或者超级管理员不能发布会议！");
                }
                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                if (entity.USER_ID_ORIGINATOR != Guid.Empty && entity.USER_ID_ORIGINATOR != LoginID)
                {
                    string OriginatorName = entity.Nav_User_Originator != null ? entity.Nav_User_Originator.NAME : GetEntity<T_FM_USER>(entity.USER_ID_ORIGINATOR).NAME;
                    throw new Exception("您不是" + OriginatorName + "不能操作此会议通知！");
                }
                if (entity.STATUS != PFStandardStatus.Draft && entity.STATUS != PFStandardStatus.Approving)
                {
                    throw new Exception("获取操作方式有误！");
                }
                if (entity.MEETINGTYPE == 0)
                {
                    throw new Exception("请选择会议类型！");
                }

                if (entity.Nav_Department == null)
                {
                    entity.Nav_Department = GetEntity<T_FM_DEPARTMENT>(entity.DEPARTMENT_ID);
                }
                if (entity.LEVELVALUE == null)//entity.CheckLevel_ENUMS_ID == null || 
                {
                    if (entity.MEETINGTYPE == SCMEETINGTYPE.SafetyBoard)
                    {
                        //安委会 公司级
                        entity.LEVELVALUE = 3;
                    }
                    else
                    {
                        var enums = GetEntity<T_FM_ENUMS>(e => e.CODE == "HMLevleEnum" && e.VALUE == entity.Nav_Department.DEPARTMENT_TYPE);
                        entity.CheckLevel_ENUMS_ID = enums.ID;
                        entity.LEVELVALUE = enums.VALUE;
                    }
                }

                var all = entity.Nav_ListPAll;
                entity.Nav_ListPAll = null;

                if (all != null && all.Any())
                {
                    List<Guid> listUserID = new List<Guid>();
                    int i = 0;
                    foreach (var item in all)
                    {
                        if (item.IS_DELETED)
                            continue;

                        i++;
                        if (listUserID.Contains(item.USER_ID))
                            throw new Exception("参会人员：行" + i + "重复！");
                        else
                            listUserID.Add(item.USER_ID);
                    }
                }

                var contentName = entity.Nav_ListMeetingContent;
                if (contentName != null)
                {
                    foreach (var item in contentName)
                    {
                        item.Nav_ContentName = null;
                    }
                }

                entity.Nav_ListMeetingContent = null;
                var filesOffice = entity.Nav_FilesOfficialseal;
                entity.Nav_FilesOfficialseal = null;
                var files = entity.Nav_Files;
                entity.Nav_Files = null;
                var PReView = entity.Nav_ListPReView;
                entity.Nav_ListPReView = null;
                if (entity.BEGIN_TIME.HasValue)
                {
                    if (entity.BEGIN_TIME.Value <= DateTime.Now)//.AddMinutes(-10)
                    {
                        throw new Exception("会议时间不能小于当前时间！");
                    }
                }

                var listThemes = entity.Nav_ListThemes;
                if (entity.MEETINGTYPE == SCMEETINGTYPE.SafetyBoard || entity.MEETINGTYPE == SCMEETINGTYPE.BasicSecurity)
                {
                    if (listThemes == null || !listThemes.Any())
                    {
                        throw new Exception("请选择会议主题！");
                    }
                    else
                    {
                        entity.THEME = String.Join(",", entity.Nav_ListThemes.Select(e => e.Nav_MeetingTheme.NAME).ToList());
                        entity.Nav_ListThemes = null;
                        foreach (var item in listThemes)
                        {
                            item.Nav_MeetingTheme = null;
                        }
                    }
                }

                if (!entity.USER_ID_HOST.HasValue)
                {
                    throw new Exception("请选择主持人！");
                }

                if (entity.STATUS == PFStandardStatus.Draft)
                {
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表 NoCommit
                        if (listThemes != null && listThemes.Any())//安委会主题
                            BantchSaveEntityNoCommit(listThemes);
                        if (all != null && all.Any())//参会人员
                            BantchSaveEntityNoCommit(all);
                        if (PReView != null && PReView.Any())//审批人员
                            BantchSaveEntityNoCommit(PReView);
                        if (contentName != null && contentName.Any())//意见
                            BantchSaveEntityNoCommit(contentName);
                        if (filesOffice != null && filesOffice.Any())//会议通知加盖公章
                            BantchSaveEntityNoCommit(filesOffice);
                        if (files != null && files.Any())//附件
                            BantchSaveEntityNoCommit(files);
                    });
                }
                else if (entity.STATUS == PFStandardStatus.Approving)
                {
                    //保存并发送
                    if (!entity.BEGIN_TIME.HasValue)
                    {
                        throw new Exception("请选择会议时间！");
                    }
                    if (entity.MEETINGTYPE == SCMEETINGTYPE.FileReView && (PReView == null || !PReView.Any()))
                    {
                        throw new Exception("文件审核会中，评审人员不能未空！");
                    }

                    //var sysFilter = new SystemCodeFilter();
                    //sysFilter.CodeType = (int)PFCodeRuleType.会议通知;
                    //sysFilter.Count = 1;
                    //sysFilter.OrgId = entity.ORG_ID;
                    //var serialCode = CodeRuleService.NewGenSerial(sysFilter);

                    if (entity.USER_ID_RECORDER == null)
                    {
                        throw new Exception("请选择记录人！");
                    }
                    //if (filesOffice == null)
                    //{
                    //    throw new Exception("请上传附件【加盖公章会议通知】！");
                    //}
                    if (all == null || !all.Any())
                    {
                        throw new Exception("请选择参会人员！");
                    }

                    //if (all == null || !all.Any())
                    //{
                    //    throw new Exception("参会人员不能未空！");
                    //}

                    //if (PReView != null && PReView.Any())
                    //{
                    //    foreach (var item in PReView)
                    //    {
                    //        var check = all.Where(e => e.USER_ID == item.USER_ID);
                    //        if (check != null && check.Any())
                    //        {
                    //        }
                    //    }
                    //}



                    var listAllJoin = all.ToList();
                    List<Guid> listUserId = new List<Guid>();
                    for (int i = listAllJoin.Count - 1; i > -1; i--)
                    {
                        if (listAllJoin[i].IS_DELETED)
                            continue;

                        if (listUserId.Contains(listAllJoin[i].USER_ID))
                        {
                            //姓名重复 删除
                            all.Remove(listAllJoin[i]);
                        }
                        else
                        {
                            listUserId.Add(listAllJoin[i].USER_ID);
                        }
                    }

                    //评审人 添加到参加人员中
                    if (PReView != null && PReView.Any())
                    {
                        foreach (var item in PReView)
                        {
                            item.Nav_User = null;
                        }

                        var Review = PReView.ToList();
                        //评审人员 加入到 所有人员中
                        for (int i = 0; i < Review.Count; i++)
                        {
                            //不能和参会人 重复
                            var check = all.Where(e => e.USER_ID == Review[i].USER_ID && !e.IS_DELETED);
                            if (check != null && check.Any())
                            {
                                var reUser = GetEntity<T_FM_USER>(Review[i].USER_ID);
                                throw new Exception("评审人员不能和参会人员重复【" + reUser.NAME + "】！");
                            }
                            //自己不能重复
                            var userCheck = Review.FirstOrDefault(e => e.ID != Review[i].ID && e.USER_ID == Review[i].USER_ID && !e.IS_DELETED);
                            if (userCheck != null)
                            {
                                var reUser = GetEntity<T_FM_USER>(Review[i].USER_ID);
                                throw new Exception("评审人员不能重复【" + reUser.NAME + "】！");
                            }
                            if (!Review[i].IS_DELETED && !listUserId.Contains(Review[i].USER_ID))
                            {
                                //listUserId.Add(Review[i].USER_ID);
                                T_SC_MT_MEETING_PALL model = new T_SC_MT_MEETING_PALL();
                                model.ID = Guid.NewGuid();
                                model.MEETING_ID = Review[i].MEETING_ID;
                                model.PERSONTYPE = SCMEETINGPERSONTYPE.REVIEW;
                                model.USER_ID = Review[i].USER_ID;
                                model.ORG_ID = Review[i].ORG_ID;
                                all.Add(model);
                            }
                        }
                    }

                    #region    添加主持人 和 记录人

                    T_SC_MT_MEETING_PALL modelHost = new T_SC_MT_MEETING_PALL();
                    modelHost.ID = Guid.NewGuid();
                    modelHost.MEETING_ID = entity.ID;
                    modelHost.PERSONTYPE = SCMEETINGPERSONTYPE.ALL;
                    modelHost.PERSONNATURE = PersonNature.HOST;
                    modelHost.USER_ID = entity.USER_ID_HOST.Value;
                    modelHost.ORG_ID = entity.ORG_ID;
                    all.Add(modelHost);


                    T_SC_MT_MEETING_PALL modelRecorder = new T_SC_MT_MEETING_PALL();
                    modelRecorder.ID = Guid.NewGuid();
                    modelRecorder.MEETING_ID = entity.ID;
                    modelRecorder.PERSONTYPE = SCMEETINGPERSONTYPE.ALL;
                    modelRecorder.PERSONNATURE = PersonNature.RECORDER;
                    modelRecorder.USER_ID = entity.USER_ID_RECORDER.Value;
                    modelRecorder.ORG_ID = entity.ORG_ID;
                    //modelRecorder.JOINRESULT = JoinTaskResult.Join;//记录人 默认 参加
                    all.Add(modelRecorder);

                    #endregion

                    //Task
                    //审批流
                    //entity.APPROVE_ID = Guid.NewGuid();
                    /*string serialCode = string.Empty;*/

                    #region     旧版带审批
                    ////公司级 3   部门级 0   车间级 1    班组级 2
                    ////只有明确是车间 走车间级 否则走部门级
                    //string param = entity.LEVELVALUE.Value.ToString();
                    //if (param == "0")
                    //{
                    //    //如果是安环部  找不到 部门负责人  param 改变为3
                    //    var dep = GetEntity<T_FM_DEPARTMENT>(entity.DEPARTMENT_ID);
                    //    if (dep.DEPARTMENT_STATUS == 2)//安全部门
                    //    {
                    //        param = "3";
                    //    }
                    //}
                    //MFlowPermitService.InsertApprove(serialCode, "SC028", param, entity.ID, "SC028_SHOWPRINT", entity.TaskID, true, () =>
                    //{
                    //    if (entity != null)
                    //        UpdateEntityNoCommit(entity);   //保存主表
                    //    if (listThemes != null && listThemes.Any())//安委会主题
                    //        BantchSaveEntityNoCommit(listThemes);
                    //    if (all != null && all.Any())//参会人员
                    //        BantchSaveEntityNoCommit(all);
                    //    if (PReView != null && PReView.Any())//审批人员
                    //        BantchSaveEntityNoCommit(PReView);
                    //    if (contentName != null && contentName.Any())//意见
                    //        BantchSaveEntityNoCommit(contentName);
                    //    if (filesOffice != null && filesOffice.Any())//会议通知加盖公章
                    //        BantchSaveEntityNoCommit(filesOffice);
                    //    if (files != null && files.Any())//附件
                    //        BantchSaveEntityNoCommit(files);
                    //}, entity.APPROVE_ID, null, null, null, null, null, null);
                    //// 审批完 回调方法  SC/SCMTMeeting/MeetingNoticeBack  
                    #endregion

                    T_FM_NOTIFICATION_TASK taskEnd = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        taskEnd = FMNotificActionTaskService.GetEntityTask(entity.TaskID, "SC028_SHOWPRINT");
                    }


                    #region     

                    //状态修改  给 所有参会人 发送（参加、请假）待办
                    //Guid MeetingId = new Guid(id);
                    //T_SC_MT_MEETING entity = GetEntity<T_SC_MT_MEETING>(MeetingId, new string[] { "Nav_ListPAll.Nav_User", "Nav_ListPReView.Nav_User", "Nav_UserRecorder", "Nav_UserHost" });// 参会人 评审人 记录人  主持人

                    //entity.STATUS = PFStandardStatus.Archived;//变成已归档
                    //                                          //如果是年度生产作业计划触发的，审批结束后发今日提醒给企管部负责人


                    T_FM_NOTIFICATION_TASK sendNotice = null;//会议类型对应的今日提醒
                    if (entity.CREACTTYPE == CREACTTYPEEnum.YearPlanAdd)
                    {
                        var userInfo = this.GetEntity<T_FM_PARAM_SET>(t => t.NAME == "企管部负责人", "Nav_User");
                        if (userInfo != null)
                        {
                            //sendNotice = FMNotificActionTaskService.InsertUserNoticeTaskModel("请上传下年度生产作业计划至文件库。", entity.ID, entity.ORG_ID, userInfo.USER_ID.Value, userInfo.Nav_User.NAME, DateTime.Now, DateTime.Now.AddDays(30), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                            sendNotice = FMNotificActionTaskService.InsertUserNoticeTaskModel("请上传下年度生产作业计划至文件库。", entity.ID, entity.ORG_ID, userInfo.USER_ID.Value, userInfo.Nav_User.NAME, DateTime.Now, (int)FMNoticeTypeEnum.今日提醒, "PF135", FMTASKTYPE.MT_MINUTES_Notice);
                        }
                    }

                    //  XXXX 会  参会通知  
                    string perNoticeTitle = entity.MEETINGTYPE.GetDescription() + "参会通知";
                    List<Guid> ListNoticeAll = new List<Guid>();
                    List<string> ListNoticeAllNAME = new List<string>();

                    var listUser = all.Where(e => !e.IS_DELETED).Select(e => e.USER_ID).ToList();

                    for (int i = 0; i < listUser.Count; i++)
                    {
                        if (ListNoticeAll.Contains(listUser[i]))
                        {
                            continue;
                        }
                        ListNoticeAll.Add(listUser[i]);
                        //ListNoticeAllNAME.Add(listUser[i].NAME);
                    }
                    //主持人
                    if (!ListNoticeAll.Contains(entity.USER_ID_HOST.Value))
                    {
                        ListNoticeAll.Add(entity.USER_ID_HOST.Value);
                        //ListNoticeAllNAME.Add(entity.Nav_UserHost.NAME);
                    }
                    //记录人
                    if (!ListNoticeAll.Contains(entity.USER_ID_RECORDER.Value))
                    {
                        ListNoticeAll.Add(entity.USER_ID_RECORDER.Value);
                        //ListNoticeAllNAME.Add(entity.Nav_UserRecorder.NAME);
                    }
                    //评审人
                    if (entity.Nav_ListPReView != null && entity.Nav_ListPReView.Any())
                    {
                        var ReView = entity.Nav_ListPReView.ToList();
                        for (int i = 0; i < ReView.Count; i++)
                        {
                            if (ListNoticeAll.Contains(ReView[i].USER_ID))
                            {
                                continue;
                            }
                            ListNoticeAll.Add(ReView[i].USER_ID);
                            //ListNoticeAllNAME.Add(ReView[i].Nav_User.NAME);
                        }
                    }

                    Dictionary<Guid, string> dicUserPhone = null;
                    if (entity.IS_SEND)
                    {
                        dicUserPhone = new Dictionary<Guid, string>();
                    }

                    if (ListNoticeAll != null && ListNoticeAll.Any())
                    {
                        var listUserTask = GetEntities<T_FM_USER>(e => ListNoticeAll.Contains(e.ID) && e.ENABLE_STATUS == 0, null, null);
                        T_FM_USER userTask = null;
                        for (int i = 0; i < ListNoticeAll.Count; i++)
                        {
                            userTask = listUserTask.FirstOrDefault(e => e.ID == ListNoticeAll[i]);
                            if (userTask == null)
                            {
                                ListNoticeAll.RemoveAt(i);
                                i--;
                            }
                            else
                            {
                                ListNoticeAllNAME.Add(userTask.NAME);
                                if (entity.IS_SEND && !dicUserPhone.ContainsKey(userTask.ID))
                                {
                                    dicUserPhone.Add(userTask.ID, userTask.PHONE);
                                }
                            }
                        }
                    }
                    //给责任人 发送通知
                    List<T_FM_NOTIFICATION_TASK> listNoticeDeals = FMNotificActionTaskService.InsertUserNoticeTaskModels(perNoticeTitle, entity.ID, entity.ORG_ID, ListNoticeAll, ListNoticeAllNAME, DateTime.Now, entity.BEGIN_TIME.Value, (int)FMNoticeTypeEnum.消息, "SC028_SHOWPRINT");

                    //不要做默认参加
                    //foreach (var item in listNoticeDeals)
                    //{
                    //    if (item.USER_ID == LoginID)
                    //    {
                    //        item.NOTICE_STATUS = 0;
                    //        item.TASK_DT = DateTime.Now;
                    //        break;
                    //    }
                    //}
                    //foreach (var item in all)
                    //{
                    //    if (item.USER_ID == LoginID)
                    //    {
                    //        item.JOINRESULT = JoinTaskResult.Join;
                    //        break;
                    //    }
                    //}
                    //如果会议已经开始了 待办变成已完成
                    if (entity.BEGIN_TIME.Value < DateTime.Now)
                    {
                        foreach (var item in listNoticeDeals)
                        {
                            item.NOTICE_STATUS = 1;
                        }
                    }

                    //发起人 和 记录人  默认 参加

                    var taskLogin = listNoticeDeals.FirstOrDefault(e => e.USER_ID == entity.USER_ID_ORIGINATOR);
                    if (taskLogin != null)
                    {
                        taskLogin.NOTICE_STATUS = 1;
                        taskLogin.TASK_DT = DateTime.Now;

                        //发起人 默认参加
                        T_SC_MT_MEETING_PALL modelORIGINATOR = all.FirstOrDefault(e => e.USER_ID == entity.USER_ID_ORIGINATOR);
                        if (modelORIGINATOR != null)
                        {
                            modelORIGINATOR.JOINRESULT = JoinTaskResult.Join;
                        }
                    }

                    ////var taskRECORDER = listNoticeDeals.FirstOrDefault(e => e.USER_ID == entity.USER_ID_RECORDER);
                    ////if (taskRECORDER != null)
                    ////{
                    ////    taskRECORDER.NOTICE_STATUS = 1;
                    ////    taskRECORDER.TASK_DT = DateTime.Now;
                    ////}

                    //this.UnifiedCommit(() =>
                    //{
                    //    if (entity != null)
                    //        UpdateEntityNoCommit(entity);
                    //    if (listNoticeDeals != null && listNoticeDeals.Any())//隐患上报明细表
                    //        BantchSaveEntity(listNoticeDeals);
                    //    if (sendNotice != null)
                    //        UpdateEntityNoCommit(sendNotice);
                    //});
                    //return true;

                    #endregion
                    if (listThemes != null && listThemes.Any())
                    {
                        foreach (var item in listThemes)
                        {
                            item.Nav_MeetingTheme = null;
                        }
                    }

                    if (entity.CREACTTYPE == null)
                        entity.CREACTTYPE = CREACTTYPEEnum.UserAdd;

                    if (string.IsNullOrEmpty(entity.CODE))
                        entity.CODE = "HY" + DateTime.Now.ToString("yyyyMMddHHmm");

                    #region    判断对接模块 修改 CREACTTYPE == CREACTTYPEEnum.

                    if ((entity.CREACTTYPE == CREACTTYPEEnum.System || entity.CREACTTYPE == CREACTTYPEEnum.UserAdd) && !string.IsNullOrEmpty(entity.CONTENT32))
                    {
                        //普通会议、文件审核会、文件评审会 会议内容是选择的 
                        //安委会、基层安全会  会议内容输入
                        CREACTTYPEEnum? CREACTTYPE = GetCREACTTYPE(entity.MEETINGTYPE, entity.CONTENT32);//根据会议内容 触发对应表单
                        if (CREACTTYPE != null)
                        {
                            entity.CREACTTYPE = CREACTTYPE;
                        }
                    }
                    #endregion

                    #region    短信发送
                    List<T_FM_NOTICE> listNotice = null;
                    if (entity.IS_SEND)
                    {
                        entity.IS_SENDED = true;
                        listNotice = new List<T_FM_NOTICE>();
                        Guid Key = Guid.NewGuid();
                        //所有的人 添加 参会通知
                        foreach (var item in listNoticeDeals)
                        {
                            if (item.USER_ID == LoginID)
                                continue;

                            listNotice.Add(new T_FM_NOTICE()
                            {
                                ID = Guid.NewGuid(),
                                KEY = Key,
                                ORG_ID = item.ORG_ID,
                                CREATE_TIME = DateTime.Now,
                                CREATER_ID = LoginID,
                                NOTICETYPE = NOTICETYPE.Meeting,
                                TEMPLATE_ID = NOTICETYPE.Meeting.GetDescription(),
                                TABLENAME = "T_SC_MT_MEETING",
                                DATA_ID = entity.ID,
                                USER_ID = item.USER_ID,
                                USERNAME = item.USER_NAME,
                                TEL = dicUserPhone.ContainsKey(item.USER_ID) ? dicUserPhone[item.USER_ID] : "",
                                NOTICE_STATUS = FMNoticeStatus.等待发送,
                                TRYCOUNT = 0,
                                TITLE = item.NOTICE_TITLE + "[" + entity.BEGIN_TIME.Value.ToString("yyyy-MM-dd HH:MM") + "]",
                                ENDDT = item.TASK_ENDDT
                            });
                        }
                    }

                    #endregion

                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表
                        if (listThemes != null && listThemes.Any())//安委会主题
                            BantchSaveEntityNoCommit(listThemes);
                        if (all != null && all.Any())//参会人员
                            BantchSaveEntityNoCommit(all);
                        if (PReView != null && PReView.Any())//审批人员
                            BantchSaveEntityNoCommit(PReView);
                        if (contentName != null && contentName.Any())//意见
                            BantchSaveEntityNoCommit(contentName);
                        if (filesOffice != null && filesOffice.Any())//会议通知加盖公章
                            BantchSaveEntityNoCommit(filesOffice);
                        if (files != null && files.Any())//附件
                            BantchSaveEntityNoCommit(files);
                        if (taskEnd != null)
                            UpdateEntityNoCommit(taskEnd);   //保存主表
                        if (listNoticeDeals != null && listNoticeDeals.Any())//参会通知
                            BantchSaveEntity(listNoticeDeals);
                        if (sendNotice != null)//会议类型对应的今日提醒
                            UpdateEntityNoCommit(sendNotice);
                        if (listNotice != null && listNotice.Any())//会议短信
                            BantchSaveEntityNoCommit(listNotice);
                    });

                    // 审批完 回调方法  SC/SCMTMeeting/MeetingNoticeBack 

                    if (entity.IS_SEND)
                    {
                        try
                        {
                            //短信发送
                            FMNoticeService.SendMsg(NOTICETYPE.Meeting, entity.ID);
                        }
                        catch { }
                    }
                }
                else
                {
                    throw new Exception("会议通知状态【" + entity.STATUS.GetDescription() + "】操作失败！");
                }

                return true;
            });
        }

        /// <summary>
        /// 根据检查内容 返回会议生成方式 
        /// </summary>
        /// <param name="MEETINGTYPE"></param>
        /// <param name="CONTENT"></param>
        /// <returns></returns>
        private CREACTTYPEEnum? GetCREACTTYPE(SCMEETINGTYPE MEETINGTYPE, string CONTENT)
        {
            if (string.IsNullOrEmpty(CONTENT))
                return null;
            switch (MEETINGTYPE)
            {
                case SCMEETINGTYPE.Ordinary:
                    if (CONTENT.Contains(ConnToOther.ToOG034EditName.GetDescription()))
                        return CREACTTYPEEnum.ToOG034Edit;
                    if (CONTENT.Contains(ConnToOther.安全生产方针讨论.GetDescription()))
                        return CREACTTYPEEnum.ToPT014;
                    if (CONTENT.Contains(ConnToOther.认可与奖励评价.GetDescription()))
                        return CREACTTYPEEnum.ToOG028;
                    if (CONTENT.Contains(ConnToOther.风险评价小组成立.GetDescription()))
                        return CREACTTYPEEnum.ToHM134;
                    if (CONTENT.Contains(ConnToOther.设备设施维修计划讨论.GetDescription()))
                        return null;
                    if (CONTENT.Contains(ConnToOther.设备设施维修工作方案讨论.GetDescription()))
                        return null;
                    if (CONTENT.Contains(ConnToOther.安全投入论证.GetDescription()))
                        return null;
                    if (CONTENT.Contains(ConnToOther.应急机构成立及人员任命.GetDescription()))
                        return CREACTTYPEEnum.ToOG010;
                    if (CONTENT.Contains(ConnToOther.成立矿山救护队.GetDescription()))
                        return null;
                    if (CONTENT.Contains(ConnToOther.潜在紧急事件讨论.GetDescription()))
                        return CREACTTYPEEnum.ToCM018;
                    if (CONTENT.Contains(ConnToOther.应急能力评估.GetDescription()))
                        return CREACTTYPEEnum.ToCM026;
                    if (CONTENT.Contains(ConnToOther.应急演练计划讨论.GetDescription()))
                        return CREACTTYPEEnum.ToCM002;
                    if (CONTENT.Contains(ConnToOther.应急演练方案讨论.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;


                    //if (CONTENT.Contains(ConnToOther.事故调查小组成立.GetDescription()))
                    //    return CREACTTYPEEnum.ToAE006;
                    //if (CONTENT.Contains(ConnToOther.事故调查讨论.GetDescription()))
                    //    return CREACTTYPEEnum.ToAE008;
                    //if (CONTENT.Contains(ConnToOther.调查报告讨论.GetDescription()))
                    //    return CREACTTYPEEnum.ToAE018;

                    //事故事件与会议关联总体流程
                    //事故事件上报[AE006] => 审批 => 触发【事故调查小组成立】会议 => 【事故调查小组成员AE008】表单=> 触发【事故调查讨论】会议 => 【勘察记录表 AE018】表单  => 触发【调查报告讨论】会议 => 【事故事件调查结果填报表AE010】
                    if (CONTENT.Contains(ConnToOther.事故调查小组成立.GetDescription()))
                        return CREACTTYPEEnum.ToAE008;
                    if (CONTENT.Contains(ConnToOther.事故调查讨论.GetDescription()))
                        return CREACTTYPEEnum.ToAE018;
                    if (CONTENT.Contains(ConnToOther.调查报告讨论.GetDescription()))
                        return CREACTTYPEEnum.ToAE010;


                    if (CONTENT.Contains(ConnToOther.事故事件统计分析.GetDescription()))
                        return null;
                    if (CONTENT.Contains(ConnToOther.事故事件回顾.GetDescription()))
                        return null;
                    if (CONTENT.Contains(ConnToOther.安全检查表的回顾与更新.GetDescription()))
                        return CREACTTYPEEnum.ToBS032;
                    if (CONTENT.Contains(ConnToOther.危险源辨识与风险评价回顾.GetDescription()))
                        return CREACTTYPEEnum.ToHM062_HM102;
                    if (CONTENT.Contains(ConnToOther.年度生产作业计划讨论会.GetDescription()))
                        return CREACTTYPEEnum.ToNotice;
                    if (CONTENT.Contains(ConnToOther.变化管理讨论.GetDescription()))
                        return CREACTTYPEEnum.ToPR023;

                    break;
                case SCMEETINGTYPE.FileAudit:

                    if (CONTENT.Contains(ConnToOther.法律法规更新评审会.GetDescription()))
                        return CREACTTYPEEnum.ToLR010;
                    if (CONTENT.Contains(ConnToOther.合理化建议评审会.GetDescription()))
                        return CREACTTYPEEnum.ToOG060;
                    if (CONTENT.Contains(ConnToOther.安全标准化评审会.GetDescription()))
                        return CREACTTYPEEnum.ToPE027;
                    if (CONTENT.Contains(ConnToOther.尾矿勘察文件评审.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.尾矿安全评价文件评审.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.回采勘察文件评审.GetDescription()))
                        return CREACTTYPEEnum.ToTL014;
                    if (CONTENT.Contains(ConnToOther.尾矿回采安全预评价文件评审.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.尾矿闭库安全现状评价文件评审.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.许可作业范围评审会.GetDescription()))
                        return CREACTTYPEEnum.ToHM104;
                    if (CONTENT.Contains(ConnToOther.安全生产责任制评审会.GetDescription()))
                        return CREACTTYPEEnum.ToOG002;
                    if (CONTENT.Contains(ConnToOther.尾矿防震技术论证报告评审会.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    break;

                case SCMEETINGTYPE.FileReView:
                    if (CONTENT.Contains(ConnToOther.安全评价文件审核.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.设计文件审核_露天矿山选厂.GetDescription()))
                        return CREACTTYPEEnum.ToPR002;
                    if (CONTENT.Contains(ConnToOther.应急预案审核.GetDescription()))
                        return CREACTTYPEEnum.ToSC067;
                    if (CONTENT.Contains(ConnToOther.勘察文件审核_尾矿.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.勘察文件审核_露天矿山.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.设计文件审核_尾矿.GetDescription()))
                        return CREACTTYPEEnum.ToPR002_2;
                    if (CONTENT.Contains(ConnToOther.回采勘察文件审核_尾矿.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.回采安全预评价文件审核_尾矿.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.回采设计文件审核_尾矿.GetDescription()))
                        return CREACTTYPEEnum.ToPR002_3;
                    if (CONTENT.Contains(ConnToOther.闭库安全现状评价文件审核_尾矿.GetDescription()))
                        return CREACTTYPEEnum.ToWJSH;
                    if (CONTENT.Contains(ConnToOther.闭库设计文件审核_尾矿.GetDescription()))
                        return CREACTTYPEEnum.ToPR002_4;
                    if (CONTENT.Contains(ConnToOther.所有的制度文件审核会.GetDescription()))
                        return null;
                    break;

                case SCMEETINGTYPE.SafetyBoard:
                    break;
                case SCMEETINGTYPE.BasicSecurity:
                    break;
                default:
                    break;
            }

            return null;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SendMsg")]
        public JsonActionResult<bool> SendMsg([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var mtConfig = GetEntity<T_SC_MT_CONFIG>(e => e.IS_SENDMSG);
                if (mtConfig == null)
                {
                    throw new Exception("暂未查询到短信开通信息！");
                }
                if (string.IsNullOrEmpty(filter.Keyword))
                {
                    throw new Exception("获取参数失败！");
                }

                Guid MeetingID = Guid.Empty;
                try
                {
                    MeetingID = Guid.Parse(filter.Keyword);
                }
                catch { MeetingID = Guid.Empty; }
                if (MeetingID == Guid.Empty)
                {
                    throw new Exception("获取参数失败！");
                }
                Guid? LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                //会议发起人或超管才有权限发送
                var meeting = GetEntity<T_SC_MT_MEETING>(MeetingID);
                if (meeting.USER_ID_ORIGINATOR != LoginID && !APT.Infrastructure.Api.AppContext.CurrentSession.UserName.ToLower().Contains("admin"))
                {
                    throw new Exception("只有发起人才有发送短信的权限！");
                }

                //添加信息 T_FM_NOTICE
                var listUserID = GetEntities<T_SC_MT_MEETING_PALL>(e => e.MEETING_ID == MeetingID, null, null).Select(e => e.USER_ID).Distinct();
                var listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
                Guid Key = Guid.NewGuid();

                DateTime? dtEndTime = null;
                var task = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID.Value == MeetingID && e.SOURCE_FORMCODE == "SC028_SHOWPRINT" && e.NOTICE_TITLE.EndsWith("通知"));
                if (task == null)
                {
                    dtEndTime = meeting.BEGIN_TIME;
                }
                else
                {
                    dtEndTime = task.TASK_ENDDT;
                }
                List<T_FM_NOTICE> listNoticeSend = new List<T_FM_NOTICE>();

                foreach (var item in listUser)
                {
                    listNoticeSend.Add(new T_FM_NOTICE()
                    {
                        ID = Guid.NewGuid(),
                        KEY = Key,
                        ORG_ID = item.ORG_ID,
                        CREATE_TIME = DateTime.Now,
                        CREATER_ID = LoginID,
                        NOTICETYPE = NOTICETYPE.Meeting,
                        TEMPLATE_ID = NOTICETYPE.Meeting.GetDescription(),
                        TABLENAME = "T_SC_MT_MEETING",
                        DATA_ID = meeting.ID,
                        USER_ID = item.ID,
                        USERNAME = item.NAME,
                        TEL = item.PHONE,
                        NOTICE_STATUS = FMNoticeStatus.等待发送,
                        TRYCOUNT = 0,
                        TITLE = meeting.MEETINGTYPE.GetDescription() + "参会通知[" + meeting.BEGIN_TIME.Value.ToString("yyyy-MM-dd HH:MM") + "]",
                        ENDDT = dtEndTime
                    });
                }

                if (listNoticeSend != null && listNoticeSend.Count > 0)
                {
                    meeting.IS_SENDED = true;
                    this.UnifiedCommit(() =>
                    {
                        UpdateEntityNoCommit(meeting);
                        BantchSaveEntityNoCommit(listNoticeSend);
                    });
                    FMNoticeService.SendMsg(NOTICETYPE.Meeting, null, Key);
                }

                return true;
            });
        }



        /// <summary>
        /// 会议通知发布审批回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("MeetingNoticeBack")]
        public JsonActionResult<bool> MeetingNoticeBack(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("SC/SCMTMeeting/MeetingNoticeBack", id);
            });
        }


        /// <summary>
        /// 参会人员 参会/请假 
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("PAllCheck")]
        public JsonActionResult<bool> PAllCheck([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(filter.Parameter1))
                {
                    throw new Exception("获取参数【待办ID】失败，请刷新首页后再操作！");
                }
                else if (filter.Parameter2 == "20" && string.IsNullOrEmpty(filter.Parameter3))
                {
                    throw new Exception("请填写请假备注！");
                }
                else
                {
                    var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    var meetingID = new Guid(filter.Keyword);
                    var taskID = new Guid(filter.Parameter1);
                    var JOINRESULT = int.Parse(filter.Parameter2);

                    //获取待办信息
                    var task = FMNotificActionTaskService.GetEntityTask(taskID);

                    var meeting = GetEntity<T_SC_MT_MEETING>(meetingID, new string[] { "Nav_UserHost", "Nav_UserRecorder", "Nav_ListPAll.Nav_User", "Nav_ListPReView.Nav_User" });
                    //T_SC_MT_MEETING_PALL modelAllLogin = null;
                    //T_SC_MT_MEETING_PREVIEW modelPVLogin = null;
                    List<T_SC_MT_MEETING_PALL> listModelAllLogin = null;
                    List<T_SC_MT_MEETING_PREVIEW> listModelPVLogin = null;
                    if ((meeting.BEGIN_TIME.HasValue && meeting.BEGIN_TIME.Value < DateTime.Now) || meeting.ISBEGIN)
                    {
                        throw new Exception("该会议已经开始，操作失败！");
                    }
                    if (filter.Parameter2 == "20")
                    {
                        if (meeting.USER_ID_HOST == loginID)
                        {
                            throw new Exception("主持人不能请假！");
                        }
                        else if (meeting.USER_ID_RECORDER == loginID)
                        {
                            throw new Exception("记录人不能请假！");
                        }
                        else if (meeting.Nav_ListPReView != null && meeting.Nav_ListPReView.Any())
                        {
                            listModelPVLogin = meeting.Nav_ListPReView.Where(e => e.USER_ID == loginID).ToList();
                            if (listModelPVLogin != null && listModelPVLogin.Count > 0)
                            {
                                throw new Exception("评审人员不能请假！");
                            }

                            //modelPVLogin = meeting.Nav_ListPReView.FirstOrDefault(e => e.USER_ID == loginID);
                            //if (modelPVLogin != null)
                            //{
                            //    throw new Exception("评审人员不能请假！");
                            //}
                        }
                    }

                    //modelAllLogin = meeting.Nav_ListPAll.FirstOrDefault(e => e.USER_ID == loginID);
                    //meeting.Nav_ListPAll
                    listModelAllLogin = meeting.Nav_ListPAll.Where(e => e.USER_ID == loginID).ToList();


                    if (listModelAllLogin != null && listModelAllLogin.Count > 0)// modelAllLogin != null
                    {
                        //modelAllLogin.JOINRESULT = (JoinTaskResult)JOINRESULT;
                        //modelAllLogin.NOTJOINREASON = filter.Parameter3;

                        listModelAllLogin.ForEach(e =>
                        {
                            e.JOINRESULT = (JoinTaskResult)JOINRESULT;
                            e.NOTJOINREASON = filter.Parameter3;
                        });

                        //if (modelAllLogin.PERSONTYPE == SCMEETINGPERSONTYPE.ALL )//所有人
                        //{
                        //    if (filter.Parameter2 == "20")
                        //    {
                        //        modelAllLogin.PERSONTYPE = SCMEETINGPERSONTYPE.ASKFORLEAVE;//请假
                        //    }
                        //    else
                        //    {
                        //        modelAllLogin.PERSONTYPE = SCMEETINGPERSONTYPE.JOIN;//参加
                        //    }
                        //}

                        listModelPVLogin = meeting.Nav_ListPReView.Where(e => e.USER_ID == loginID).ToList();
                        if (listModelPVLogin != null && listModelPVLogin.Count > 0)
                        {
                            listModelPVLogin.ForEach(e =>
                            {
                                e.JOINRESULT = (JoinTaskResult)JOINRESULT;
                                e.NOTJOINREASON = filter.Parameter3;
                            });

                        }

                        //if (modelAllLogin.PERSONTYPE == SCMEETINGPERSONTYPE.REVIEW)//评审人
                        //{
                        //    modelPVLogin = meeting.Nav_ListPReView.FirstOrDefault(e => e.USER_ID == loginID);
                        //    if (modelPVLogin != null)
                        //    {
                        //        modelPVLogin.JOINRESULT = (JoinTaskResult)JOINRESULT;
                        //        modelPVLogin.NOTJOINREASON = filter.Parameter3;
                        //    }
                        //}
                    }
                    else if (loginID != meeting.USER_ID_HOST && loginID != meeting.USER_ID_RECORDER)
                    {
                        throw new Exception("您不在参加会议名单，操作失败！");
                    }

                    this.UnifiedCommit(() =>
                    {
                        if (task != null)
                            UpdateEntityNoCommit(task);   //保存主表 NoCommit
                        if (listModelPVLogin != null && listModelPVLogin.Count > 0)
                            BantchUpdateEntityNoCommit(listModelPVLogin);
                        if (listModelAllLogin != null && listModelAllLogin.Count > 0)
                            BantchUpdateEntityNoCommit(listModelAllLogin);

                        //if (modelAllLogin != null) //保存信息
                        //    UpdateEntityNoCommit(modelAllLogin);
                        //if (modelPVLogin != null)//审批人
                        //    UpdateEntityNoCommit(modelPVLogin);
                    });
                }
                return true;
            });
        }

        /// <summary>
        /// 根据会议ID获取参会人员信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetMeetingPAll")]
        public JsonActionResult<List<T_FM_USER>> GetMeetingPAll([FromBody] KeywordFilter filter)
        {
            return SafeExecute<List<T_FM_USER>>(() =>
            {
                //var list = GetEntities<T_SC_MT_MEETING_PALL>(e => !e.IS_DELETED && e.PERSONTYPE == SCMEETINGPERSONTYPE.ALL, filter, new string[] { "Nav_User" }).ToList();

                Guid MEETING_ID = Guid.Empty;

                List<UserJoinParm> listAreaSearch = null;
                if (filter.FilterGroup.Groups.Count > 0)
                {
                    foreach (var item in filter.FilterGroup.Groups)
                    {
                        if (item.Rules.Count > 0)
                        {
                            foreach (var itemR in item.Rules)
                            {
                                switch (itemR.Field)
                                {
                                    case "Nav_ListPJoin":
                                        listAreaSearch = JsonHelper.FromJson<List<UserJoinParm>>(itemR.Value.ToString());
                                        break;
                                    case "MEETING_ID":
                                        MEETING_ID = new Guid(itemR.Value.ToString());
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }
                }
                else if (filter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in filter.FilterGroup.Rules)
                    {
                        switch (item.Field)
                        {
                            case "Nav_ListPJoin":
                                listAreaSearch = JsonHelper.FromJson<List<UserJoinParm>>(item.Value.ToString());
                                break;
                            case "MEETING_ID":
                                MEETING_ID = new Guid(item.Value.ToString());
                                break;
                            default:
                                break;
                        }
                    }
                }

                Expression<Func<T_SC_MT_MEETING_PALL, bool>> expression = e => !e.IS_DELETED && e.PERSONTYPE == SCMEETINGPERSONTYPE.ALL;
                if (MEETING_ID != Guid.Empty)
                {
                    expression = expression.And(e => e.MEETING_ID == MEETING_ID);
                }
                if (listAreaSearch != null && listAreaSearch.Count > 0)
                {
                    var IUserID = listAreaSearch.Select(e => e.USER_ID).ToList();//.Where(e=>!e.IS_DELETED.HasValue||!e.IS_DELETED.Value)
                    expression = expression.And(e => e.PERSONNATURE == PersonNature.JOIN && IUserID.Contains(e.USER_ID));
                }
                List<T_FM_USER> listResult = GetEntities<T_SC_MT_MEETING_PALL>(expression, null, new string[] { "Nav_User" }).Select(e => e.Nav_User).ToList<T_FM_USER>();
                return listResult;
            });
        }


        /// <summary>
        /// 数据删除
        /// </summary>
        /// <param name="id">过滤实体</param>
        /// <returns></returns>
        [HttpGet, Route("FullDelete")]
        public JsonActionResult<bool> FullDelete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                //删除审批流
                //删除明细
                //删除主表

                Guid meetingId = new Guid(id);
                string[] path = { "Nav_ListMeetingContent", "Nav_ListPAll", "Nav_ListPReView", "Nav_Files", "Nav_FilesOfficialseal", "Nav_FilesRecord" };
                T_SC_MT_MEETING entity = GetEntity<T_SC_MT_MEETING>(meetingId, path);

                if (entity.ISBEGIN)
                {
                    throw new Exception("该会议已经开始了，删除失败！");
                }
                else if (entity.CREACTTYPE.HasValue && entity.CREACTTYPE == CREACTTYPEEnum.System)
                {
                    throw new Exception("系统设置要召开的会议不能删除！");
                }

                List<Guid> listMeetingContentID = new List<Guid>();
                List<Guid> listPAllID = new List<Guid>();
                List<Guid> listPReViewID = new List<Guid>();
                List<Guid> filesIds = new List<Guid>();
                List<Guid> listOfficialsealID = new List<Guid>();
                List<Guid> listFilesRecordID = new List<Guid>();
                List<Guid> listApproveDetailId = new List<Guid>();

                if (entity.Nav_ListMeetingContent != null && entity.Nav_ListMeetingContent.Count > 0)
                {
                    listMeetingContentID = entity.Nav_ListMeetingContent.Select(e => e.ID).ToList();
                }
                if (entity.Nav_ListPAll != null && entity.Nav_ListPAll.Count > 0)
                {
                    listPAllID = entity.Nav_ListPAll.Select(e => e.ID).ToList();
                }
                if (entity.Nav_ListPReView != null && entity.Nav_ListPReView.Count > 0)
                {
                    listPReViewID = entity.Nav_ListPReView.Select(e => e.ID).ToList();
                }
                if (entity.Nav_Files != null && entity.Nav_Files.Any())
                {
                    filesIds = entity.Nav_Files.Select(t => t.ID).ToList();
                }
                if (entity.Nav_FilesOfficialseal != null && entity.Nav_FilesOfficialseal.Count > 0)
                {
                    listOfficialsealID = entity.Nav_FilesOfficialseal.Select(e => e.ID).ToList();
                }
                if (entity.Nav_FilesRecord != null && entity.Nav_FilesRecord.Count > 0)
                {
                    listFilesRecordID = entity.Nav_FilesRecord.Select(e => e.ID).ToList();
                }

                var listApproveDetail = this.GetEntities<T_PF_APPROVE_DETAIL>(t => t.APPROVE_ID == entity.APPROVE_ID, null, null);
                if (listApproveDetail != null && listApproveDetail.Any())
                {
                    listApproveDetailId = listApproveDetail.Select(e => e.ID).ToList();
                }

                UnifiedCommit(() =>
                {
                    if (listApproveDetailId.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_PF_APPROVE_DETAIL>(listApproveDetailId);
                    if (entity.APPROVE_ID.HasValue)
                        DeleteEntityNoCommit<T_PF_APPROVE>(entity.APPROVE_ID.Value.ToString());
                    if (listFilesRecordID.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_SC_MT_MEETING_FILE_RECORD>(listFilesRecordID);
                    if (listOfficialsealID.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_SC_MT_MEETING_FILE_OFFICIALSEAL>(listOfficialsealID);
                    if (filesIds.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_SC_MT_MEETING_FILE>(filesIds);
                    if (listPReViewID.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_SC_MT_MEETING_PREVIEW>(listPReViewID);
                    if (listPAllID.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_SC_MT_MEETING_PALL>(listPAllID);
                    if (listMeetingContentID.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_SC_MT_MEETING_CONTENT>(listMeetingContentID);
                    if (entity != null)
                        this.DeleteEntityNoCommit(entity);
                });

                return true;
            });
        }


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_SC_MT_MEETING> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            PagedActionResult<T_SC_MT_MEETING> result = null;
            if (!string.IsNullOrEmpty(pageFilter.MenuParameter))
            {
                if (pageFilter.MenuParameter == "40")
                {
                    result = WitOrderPaged(e => e.MEETINGTYPE == SCMEETINGTYPE.SafetyBoard || e.MEETINGTYPE == SCMEETINGTYPE.BasicSecurity, pageFilter);
                }
                else
                {
                    result = WitOrderPaged(e => e.MEETINGTYPE == SCMEETINGTYPE.Ordinary || e.MEETINGTYPE == SCMEETINGTYPE.FileAudit || e.MEETINGTYPE == SCMEETINGTYPE.FileReView, pageFilter);
                }
            }
            else
            {
                result = WitOrderPaged(null, pageFilter);
            }
            if (result.Data != null && result.Data.Any() && DataHelper.GetRequestType(Request.Headers) == 2)
            {
                foreach (var item in result.Data)
                {
                    item.STATUSSHOW = item.STATUS.GetDescription();
                }
            }
            return result;
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetSuit")]
        public JsonActionResult<T_SC_MT_MEETING> GetSuit([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_SC_MT_MEETING>(() =>
            {
                var model = GetEntity<T_SC_MT_MEETING>(null, filter);
                if (model.MEETINGTYPE == SCMEETINGTYPE.FileReView && model.Nav_ListPAll != null && model.Nav_ListPAll.Any())
                {
                    model.Nav_ListPAll = model.Nav_ListPAll.OrderBy(e => e.PERSONTYPE).ToList();
                }
                return model;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetSuitDevlop")]
        public JsonActionResult<T_SC_MT_MEETING> GetSuitDevlop([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_SC_MT_MEETING>(() =>
            {
                List<string> listIncludAll = filter.Include.ToList();
                List<string> listIncludSearch = new List<string>();
                List<string> listIncludPAll = new List<string>();

                foreach (var item in listIncludAll)
                {
                    if (item.Contains("Nav_ListPAll"))
                    {
                        if (item == "Nav_ListPAll")
                            continue;
                        else
                            listIncludPAll.Add(item.Replace("Nav_ListPAll.", ""));
                    }
                    else
                    {
                        listIncludSearch.Add(item);
                    }
                }
                filter.Include = listIncludSearch;
                var model = GetEntity<T_SC_MT_MEETING>(null, filter);

                var listAll = GetEntities<T_SC_MT_MEETING_PALL>(e => e.MEETING_ID == model.ID, null, listIncludPAll.ToArray());
                if (listAll != null && listAll.Any())
                {
                    model.Nav_ListPAll = listAll.ToList();
                }

                if (model.MEETINGTYPE == SCMEETINGTYPE.FileReView && model.Nav_ListPAll != null && model.Nav_ListPAll.Any())
                {
                    model.Nav_ListPAll = model.Nav_ListPAll.OrderBy(e => e.PERSONTYPE).ToList();
                }
                return model;
            });
        }



        /// <summary>
        /// 会议取消
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost, Route("Cancel")]
        public JsonActionResult<bool> Cancel([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(filter.Keyword))
                {
                    throw new Exception("请勾选会议通知后再取消！");
                }
                if (filter.Keyword.Contains(","))
                {
                    throw new Exception("每次只能取消一条会议通知！");
                }
                Guid guid = new Guid(filter.Keyword);
                var meeting = GetEntity<T_SC_MT_MEETING>(guid);
                if (meeting.ISBEGIN)
                {
                    throw new Exception("该会议已开始，取消失败！");
                }

                if (meeting.BEGIN_TIME.HasValue && meeting.BEGIN_TIME.Value < DateTime.Now)
                {
                    //开会时间过了 但是还没审批 可以取消

                    if (meeting.STATUS != PFStandardStatus.Approving)
                    {
                        throw new Exception("该会议已开始，取消失败！");
                    }
                }
                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                if (meeting.USER_ID_ORIGINATOR != LoginID)
                {
                    throw new Exception("只有发起人才能取消自己发起的会议！");
                }

                //会议取消
                meeting.ISCANCEL = true;
                meeting.MODIFY_TIME = DateTime.Now;

                //可能是 通知 或者 审批流
                IEnumerable<T_FM_NOTIFICATION_TASK> listNotice = null;
                T_PF_APPROVE modelAppro = null;
                IEnumerable<T_PF_APPROVE_DETAIL> IlistApproveDetal = null;
                switch (meeting.STATUS)
                {
                    case PFStandardStatus.Draft:
                        listNotice = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID.Value == meeting.ID && (e.SOURCE_FORMCODE == "SC028" || e.SOURCE_FORMCODE == "SC032"), null);
                        break;
                    case PFStandardStatus.Sign:
                    case PFStandardStatus.Approving:
                    case PFStandardStatus.Archived:
                        //会议通知审批 已经删除
                        ////会议 保存并发送 就是 审批状态
                        //if (meeting.APPROVE_ID.HasValue)
                        //{
                        //    //待办
                        //    listNotice = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID.Value == meeting.APPROVE_ID.Value, null);
                        //    var approID = meeting.APPROVE_ID.Value;
                        //    //业务数据
                        //    modelAppro = GetEntity<T_PF_APPROVE>(e => e.ID == approID);
                        //    IlistApproveDetal = GetEntities<T_PF_APPROVE_DETAIL>(e => e.APPROVE_ID == approID, null);
                        //}
                        //    break;
                        //case PFStandardStatus.Archived://审批 
                        //只是发送待办(参会通知) 没业务数据需要处理
                        listNotice = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID.Value == meeting.ID && e.SOURCE_FORMCODE == "SC028_SHOWPRINT", null);

                        break;
                    case PFStandardStatus.Rejected:
                        break;
                    default:
                        break;
                }

                //已经阅读 审批  除了操作者  告知 会议 已经取消


                IEnumerable<T_FM_NOTIFICATION_TASK> listNoticeCancel = null;
                List<Guid> listUserID = new List<Guid>();
                List<string> listUserName = new List<string>();


                #region    修改为已删除

                if (listNotice != null)
                {
                    foreach (var item in listNotice)
                    {
                        if (item.NOTICE_STATUS == 0)
                        {
                            item.NOTICE_STATUS = 1;//取消了 默认 正常已办
                            item.TASK_DT = DateTime.Now;
                        }
                        item.ISCANCEL = true;
                        item.MODIFY_TIME = meeting.MODIFY_TIME;

                        if (meeting.STATUS != PFStandardStatus.Draft)
                        {
                            //取消 今日提醒人员
                            listUserID.Add(item.USER_ID);
                            listUserName.Add(item.USER_NAME);
                        }
                    }
                }
                if (modelAppro != null)
                {
                    modelAppro.ISCANCEL = true;
                    modelAppro.MODIFY_TIME = meeting.MODIFY_TIME;
                    if (IlistApproveDetal != null && IlistApproveDetal.Any())
                    {
                        foreach (var item in IlistApproveDetal)
                        {
                            item.ISCANCEL = true;
                            item.MODIFY_TIME = meeting.MODIFY_TIME;
                        }
                    }
                }
                if (meeting.Nav_Approve != null)
                {
                    var t = meeting.Nav_Approve;
                    meeting.Nav_Approve = null;
                }
                #endregion

                #region 今日提醒

                if (listUserID.Count > 0)
                {
                    //给所有需要参会的人员触发一条今日提醒【原计划于“会议开始时间”召开的“会议名称”已取消】。

                    string Title = "原计划于" + meeting.BEGIN_TIME.Value.ToString("yyyy-MM-dd HH:mm") + "召开的【" + meeting.MEETINGTYPE.GetDescription() + "】已取消";

                    listNoticeCancel = FMNotificActionTaskService.InsertUserNoticeTaskModels(Title, guid, filter.OrgId, listUserID, listUserName, DateTime.Now, DateTime.Now.Date.AddDays(1).AddSeconds(-1), 2, "SC028_SHOWPRINT");

                }

                #endregion

                this.UnifiedCommit(() =>
                {
                    if (meeting != null)
                        UpdateEntityNoCommit(meeting);
                    if (listNotice != null && listNotice.Any())
                        BantchUpdateEntityNoCommit(listNotice);
                    if (modelAppro != null)//审批表单
                        UpdateEntityNoCommit(modelAppro);
                    if (IlistApproveDetal != null && IlistApproveDetal.Any())//审批流明细
                        BantchUpdateEntityNoCommit(IlistApproveDetal);
                    if (listNoticeCancel != null && listNoticeCancel.Any())//会议取消 给参会人 发送取消通知
                        BantchSaveEntityNoCommit(listNoticeCancel);
                });

                return true;
            });
        }



        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetAPP")]
        public JsonActionResult<T_SC_MT_MEETING> GetAPP([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var mt = GetEntity<T_SC_MT_MEETING>(null, filter, null);
                mt.MEETINGTYPESHOW = mt.MEETINGTYPE.GetDescription();
                if (mt.CREACTTYPE.HasValue && (int)mt.CREACTTYPE.Value == 10 && mt.STATUS == 0 && (mt.Nav_ListPAll == null || !mt.Nav_ListPAll.Any()))
                {
                    // setFieldEditable('MEETINGTYPE', false)

                    //加载参会人员信息
                    // this.getPAll(stateData.MEETINGTYPE, stateData.ORG_ID, stateData.ID, setFieldVisible, setFieldValue, dispatch, setFieldValueByBatch)
                    // export function getPAll(meetingType, orgId, meetingId, setFieldVisible, setFieldValue, dispatch, setFieldValueByBatch) {
                    if (mt.MEETINGTYPE == SCMEETINGTYPE.SafetyBoard || mt.MEETINGTYPE == SCMEETINGTYPE.BasicSecurity)
                    {
                        List<T_SC_MT_MEETING_PALL> listResult = new List<T_SC_MT_MEETING_PALL>();
                        List<T_FM_USER> listUsers = new List<T_FM_USER>();
                        //基层安全会按部门 / 车间 / 班组点选或模糊查询，默认部门所有人员向下包含

                        var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        BaseFilter fiterMT = new BaseFilter(filter.OrgId);
                        fiterMT.Order = DbOrder.DESC;
                        fiterMT.Orders.Add(new DataOrder() { Field = "CREATE_TIME", Order = DbOrder.DESC });
                        //SCMEETINGTYPE MEETINGTYPE = (SCMEETINGTYPE)int.Parse(filter.Parameter1);

                        //如果有 上次这种类型的会议 有人参加
                        var meetLast = GetEntity<T_SC_MT_MEETING>(e => e.USER_ID_ORIGINATOR == LoginID && e.MEETINGTYPE == mt.MEETINGTYPE && e.PLANSET_ID.HasValue && !e.IS_DELETED && e.Nav_ListPAll != null && e.Nav_ListPAll.Any(), fiterMT, "Nav_ListPAll");
                        if (meetLast != null && meetLast.Nav_ListPAll != null && meetLast.Nav_ListPAll.Any())
                        {
                            var listUserId = meetLast.Nav_ListPAll.Where(e => e.PERSONNATURE == PersonNature.JOIN).Select(e => e.USER_ID).Distinct();
                            listUsers = GetEntities<T_FM_USER>(e => listUserId.Contains(e.ID) && !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.DEPARTMENT_ID.HasValue, null, null).OrderBy(e => e.DEPARTMENT_ID).ToList();//"Nav_Department", "Nav_Person.Nav_Post"
                        }

                        if (listUsers == null || !listUsers.Any())
                        {
                            if (mt.MEETINGTYPE == SCMEETINGTYPE.BasicSecurity)
                            {
                                var loginInfo = GetEntity<T_FM_USER>(LoginID.Value, new string[] { "Nav_Department" });// "Nav_Person.Nav_Post"
                                ////基层安全会按部门/车间/班组点选或模糊查询，默认部门所有人员向下包含 
                                ////获取 层级 及以下 所有人
                                //listUsers = FMUserService.GetDownUser(loginInfo.DEPARTMENT_ID.Value, new string[] { "Nav_Department", "Nav_Person.Nav_Post" });

                                //部门负责人发起，参会人员为：部门内所属人员 + 车间安全员及负责人
                                //车间负责人发起，参会人员为：车间内所属人员 + 班组长
                                //班组负责人发起，参会人员为：班组内成员

                                //FMDepartmentType 部门 = 0, 车间 = 1, 班组 = 2, 公司 = 3
                                switch (loginInfo.Nav_Department.DEPARTMENT_TYPE)
                                {
                                    case 0:
                                    case 1:
                                        listUsers = FMUserService.GetUserContentNextHead(loginInfo.DEPARTMENT_ID.Value);
                                        break;
                                    case 2:
                                    case 3:
                                        //班组 = 2, 公司 = 3
                                        listUsers = FMUserService.GetDownUser(loginInfo.DEPARTMENT_ID.Value);//, new string[] { "Nav_Department" }, "Nav_Person.Nav_Post" 
                                        break;
                                    default:
                                        break;
                                }
                            }
                            else if (mt.MEETINGTYPE == SCMEETINGTYPE.SafetyBoard)
                            {
                                //部门级负责人 安全员
                                //FMDepartmentType.部门 =0
                                var listDep0 = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.DEPARTMENT_TYPE == 0, null, null);
                                var listApprovreRole = GetEntities<T_PF_APPROVAL_ROLE>(e => !e.IS_DELETED && (e.NAME == "部门负责人" || e.NAME == "部门安全员" || e.NAME == "安环部负责人" || e.NAME == "安环部安全员"), null, null);

                                if (listDep0 != null && listDep0.Any() && listApprovreRole != null && listApprovreRole.Any())
                                {
                                    List<Guid> ids = listDep0.Select(e => e.ID).ToList();
                                    List<Guid> idsApprove = listApprovreRole.Select(e => e.ID).ToList();
                                    var users = GetEntities<T_FM_USER>(e => !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.DEPARTMENT_ID.HasValue && ids.Contains(e.DEPARTMENT_ID.Value) && e.APPROVE_ROLE_ID.HasValue && idsApprove.Contains(e.APPROVE_ROLE_ID.Value), null, null);// new string[] { "Nav_Department" }, "Nav_Person.Nav_Post"

                                    if (users != null && users.Any())
                                    {
                                        listUsers = users.OrderBy(e => e.DEPARTMENT_ID).ThenByDescending(e => e.APPROVE_ROLE_ID).ToList();
                                    }
                                }
                            }
                        }
                        for (int i = 0; i < listUsers.Count; i++)
                        {
                            T_SC_MT_MEETING_PALL temp = new T_SC_MT_MEETING_PALL();
                            temp.ID = Guid.NewGuid();
                            temp.MEETING_ID = mt.ID;
                            temp.USER_ID = listUsers[i].ID;
                            temp.Nav_User = listUsers[i];
                            temp.ORG_ID = mt.ORG_ID;
                            temp.PERSONTYPE = SCMEETINGPERSONTYPE.ALL;
                            listResult.Add(temp);
                        }
                        //return listResult;
                        mt.Nav_ListPAll = listResult;
                    }
                }
                return mt;
            });
        }
    }

    /// <summary>
    /// 人会人员 选请假人、缺席人
    /// </summary>
    class UserJoinParm
    {
        public Guid USER_ID { get; set; }
        public Guid ID { get; set; }
        public Guid ORG_ID { get; set; }
        public Guid MEETING_MINUTES_ID { get; set; }
        public bool? IS_DELETED { get; set; }

    }
}