using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using APT.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;

namespace APT.BS.WebApi.Controllers.Api
{
    [Route("api/BS/BSCheckMain")]
    public partial class BSCheckMainController : AuthorizeApiController<T_BS_CHECK_MAIN>
    {
        [HttpPost, Route("Get")]
        public JsonActionResult<T_BS_CHECK_MAIN> Get([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_CHECK_MAIN>(() =>
            {
                filter.IgnoreDataRule = true;
                var result = this.ActionOrderEntities<T_BS_CHECK_MAIN>(null, null, filter).FirstOrDefault();
                //result.Nav_CheckTypeLevel.CheckLevelDescription = ((HMLevleEnum)(result.Nav_CheckTypeLevel.CheckLevel)).GetDescription();
                result.CHECKOBJECT_DESCRIPTION = ((BSMineTypeEnum)(result.CHECKOBJECT)).GetDescription();
                result.QUESTION_LEVE_DESCRIPTION = ((BSQuestionLevelEnum)(result.QUESTION_LEVEL)).GetDescription();//问题等级
                result.SERIOUS_RISK_DESCRIPTION = ((BSSeriousRiskEnum)(result.SERIOUS_RISK)).GetDescription();//是否重大隐患
                return result;
            });
        }



        /// <summary>
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                Guid? orgId = null;
                if (!string.IsNullOrEmpty(orgIdStr))
                    orgId = new Guid(orgIdStr);
                else
                    return null;
                ImportDataModel result = new ImportDataModel();
                var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                if (!Directory.Exists(dic))
                    Directory.CreateDirectory(dic);
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    string filePath = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
                    Byte[] fileData = new Byte[postedFile.Length];
                    Stream sr = postedFile.OpenReadStream();//创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    //获取数据
                    Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
                    startRowIndexs.Add(0, 3);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;

                    bool isOK = InsertModel(dataTables.Tables[0], orgId.Value, ref Msg);

                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }

                    result.Data = Msg;
                    result.MessageList = new List<string> { Msg };
                }

                return result;
            });
        }

        /// <summary>
        /// 获取责任对象
        /// </summary>
        /// <param name="isClass"></param>
        /// <param name="strObj"></param>
        /// <returns></returns>
        public BSPLANCHECKOBJECTEnum GetBSPLANCHECKOBJECTEnum(string strObj, bool? isClass)
        {
            BSPLANCHECKOBJECTEnum result = BSPLANCHECKOBJECTEnum.Head;
            if (string.IsNullOrEmpty(strObj))
            {
                if (isClass.HasValue && isClass.Value)
                {
                    result = BSPLANCHECKOBJECTEnum.ClassMonitor;
                }
            }
            else
            {
                var enumsObjV = Enum.GetValues<BSPLANCHECKOBJECTEnum>();
                foreach (var item in enumsObjV)
                {
                    if (item.GetDescription() == strObj)
                    {
                        result = item;
                    }
                }
            }
            return result;
        }


        /// <summary>
        /// 数据插入
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="OrgID"></param>
        /// <param name="Msg"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool InsertModel(DataTable dtSource, Guid OrgID, ref string Msg, int rowIndex = 4)
        {
            //SMS 检查范围 默认露天矿
            //删除 检查范围、检查周期、检查依据、重大隐患类别 
            //检查区域 0   检查类型1    检查项目分类2  检查层级3    责任单位4  检查项目5    检查内容6   检查问题描述7   检查问题等级8  整改建议与措施9

            //检查对象0 检查区域1	检查类型2	检查项目分类3	检查层级4	责任单位5	检查周期6	检查项目7	检查内容8	检查依据9	检查问题描述10	检查问题等级11	重大隐患类别12	整改建议与措施13    责任人14 

            if (dtSource == null || dtSource.Rows.Count < 0)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            List<int> listNotEmpty = new List<int>() { 0, 1, 3, 4, 5, 7, 8, 9 };//2,
            //BSMineTypeEnum


            #region     定义变量

            Dictionary<int, List<int>> dicIndexEmpty = new Dictionary<int, List<int>>();

            ////检查对象0
            //int ICheckObject = 0;
            //string strCheckObject = string.Empty;


            //检查区域 1
            //List<int> listArea = new List<int>();
            var listModelArea = GetEntities<T_HM_RISK_AREA>(e => !e.IS_DELETED, null, null).ToList();
            string strArea = string.Empty;
            T_HM_RISK_AREA modelArea = new T_HM_RISK_AREA();

            //检查类型 2
            List<int> listType = new List<int>();
            List<string> listStrType = new List<string>();
            var listModelType = GetEntities<T_BS_CHECK_TYPE>(e => !e.IS_DELETED, null, null).ToList();
            string strType = string.Empty;
            T_BS_CHECK_TYPE modelType = new T_BS_CHECK_TYPE();



            ////检查项目分类 3
            //List<int> listProjCate = new List<int>();
            //List<string> listStrProjCate = new List<string>();
            //var listModelProjCate = GetEntities<T_BS_CHECK_PROJECT_CATEGORY>(e => !e.IS_DELETED, null, null);
            //string strProjCate = string.Empty;
            //T_BS_CHECK_PROJECT_CATEGORY modelProjCate = new T_BS_CHECK_PROJECT_CATEGORY();

            //检查层级 4
            List<int> listTypeLevel = new List<int>();
            List<string> listStrTypeLevel = new List<string>();
            var listModelTypeLevel = GetEntities<T_BS_CHECK_TYPE_LEVEL>(e => !e.IS_DELETED, null, new string[] { "Nav_Enums", "Nav_CheckType" }).ToList();
            List<T_FM_ENUMS> listCheckTypeLevelEnums = null;
            T_FM_ENUMS TypeLevelEnumsTemp = null;
            string strTypeLevel = string.Empty;
            T_BS_CHECK_TYPE_LEVEL modelTypeLevel = new T_BS_CHECK_TYPE_LEVEL();

            //责任单位5
            List<T_FM_DEPARTMENT> ListModelDepartment = null;
            List<string> listStrDepartmentName = new List<string>();
            char[] charSplit = new char[] { '、', '；' };
            string strDepName = string.Empty;
            List<string> listDepName = new List<string>();
            List<int> listDepartment = new List<int>();


            //检查项目 7
            //List<int> listProject = new List<int>();
            var listModelProject = GetEntities<T_BS_CHECK_PROJECT>(e => !e.IS_DELETED, null, null).ToList();
            string strProject = string.Empty;
            T_BS_CHECK_PROJECT modelProject = new T_BS_CHECK_PROJECT();


            //检查内容 8
            var listModelContents = GetEntities<T_BS_CHECK_CONTENTS>(e => !e.IS_DELETED, null, null).ToList();
            string strContents = string.Empty;
            T_BS_CHECK_CONTENTS modelContents = new T_BS_CHECK_CONTENTS();
            List<T_BS_CHECK_CONTENTS> listModelContentsAdd = new List<T_BS_CHECK_CONTENTS>();


            //检查问题描述10	 整改建议与措施13    一个问题描述 有且仅有一个整改建议与措施  和问题等级
            List<T_BS_CHECK_QUESTION> listCheckQuestion = GetEntities<T_BS_CHECK_QUESTION>(e => !e.IS_DELETED, null, null).ToList();
            string strDescreption = string.Empty;//检查问题描述10
            string strDemand = string.Empty;//整改建议与措施13
            T_BS_CHECK_QUESTION modelQuestion = new T_BS_CHECK_QUESTION();



            //检查问题等级11
            //List<string> listStrQuestionLevel = new List<string>() { "重大", "A", "B", "C", "D", };
            string strQuestionLevel = string.Empty;
            List<int> listQuestionLevel = new List<int>();
            int iQuestionLevel = 0;

            //责任人14 
            //BSPLANCHECKOBJECTEnum? RESPONOBJECT = null;
            //string strResponObject = string.Empty;


            #endregion

            //安全检查库
            List<T_BS_CHECK_MAIN> listMain = new List<T_BS_CHECK_MAIN>();
            List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT> listMainDep = new List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT>();
            List<T_BS_CHECK_PROJECT> listProjectAdd = new List<T_BS_CHECK_PROJECT>();
            List<T_BS_CHECK_QUESTION> listCheckQuestionAdd = new List<T_BS_CHECK_QUESTION>();
            List<T_HM_RISK_AREA> listAreaAdd = new List<T_HM_RISK_AREA>();

            List<T_BS_CHECK_TYPE> listCheckType = new List<T_BS_CHECK_TYPE>();
            List<T_BS_CHECK_TYPE_LEVEL> listCheckTypeLevel = new List<T_BS_CHECK_TYPE_LEVEL>();

            DateTime dtNow = new DateTime();

            List<T_FM_DEPARTMENT> listDep = GetEntities<T_FM_DEPARTMENT>(null, null).ToList();

            #region     数据判断

            //第一行是标题 跳过
            int rowAll = dtSource.Rows.Count;
            //List<EnumsResult> list = DataHelper.GetEnum("BSMineTypeEnum");
            //EnumsResult? enumCheck = null;
            List<EnumsResult> listLevel = DataHelper.GetEnum("BSQuestionLevelEnum");
            EnumsResult? enumCheck = null;
            for (int i = 0; i < rowAll; i++)
            {
                #region    不能为空

                List<int> listi = null;
                for (int j = 0; j < 10; j++)
                {
                    if (!listNotEmpty.Contains(j))
                        continue;

                    if (string.IsNullOrEmpty(dtSource.Rows[i][j].ToString().Trim()))
                    {
                        if (listi == null)
                        {
                            listi = new List<int>();
                        }
                        listi.Add(j + 1);
                    }
                }
                if (listi != null)
                {
                    dicIndexEmpty.Add(i + rowIndex, listi);//有空的 直接添加
                    continue;
                }
                #endregion

                #region 检查区域  0

                strArea = dtSource.Rows[i][0].ToString().Trim();
                modelArea = listModelArea.FirstOrDefault(e => e.NAME == strArea);
                if (modelArea == null && dicIndexEmpty.Count < 1 && listType.Count < 1 && listTypeLevel.Count < 1 && listQuestionLevel.Count < 1)//&& listProjCate.Count < 1
                {
                    //检查区域
                    modelArea = new T_HM_RISK_AREA();
                    modelArea.ID = Guid.NewGuid();
                    modelArea.CODE = "CheckAdd";
                    modelArea.NAME = strArea;
                    modelArea.IS_DELETED = false;
                    modelArea.ORG_ID = OrgID;
                    //modelArea.ENTITY_ORG_TPYE   =;
                    //modelArea.FORM_ID           =;
                    //modelArea.FLOW_STATUS       =;
                    //modelArea.FLOW_SEND_STATUS  =;
                    //modelArea.FLOW_ID           =;
                    modelArea.CREATE_TIME = dtNow;
                    modelArea.MODIFY_TIME = dtNow;
                    //modelArea.CREATER_ID =;
                    //modelArea.MODIFIER_ID =;
                    modelArea.STATUS = STATUSEnum.启用;
                    //modelArea.DEPARTMENT_ID =;
                    modelArea.LEVEL = BaseData.Domain.Enums.FMDepartmentType.公司;
                    modelArea.LEVEL = BaseData.Domain.Enums.FMDepartmentType.公司;

                    listModelArea.Add(modelArea);
                    listAreaAdd.Add(modelArea);

                }
                #endregion

                #region 检查类型  1

                strType = dtSource.Rows[i][1].ToString().Trim();
                modelType = listModelType.FirstOrDefault(e => e.NAME == strType);
                if (modelType == null)
                {
                    ////检查类型
                    //listType.Add(i);
                    //if (!listStrType.Contains(strType))
                    //    listStrType.Add(strType);
                    modelType = new T_BS_CHECK_TYPE()
                    {
                        ID = Guid.NewGuid(),
                        CODE = strType,
                        NAME = strType,
                        ENABLE_STATUS = 0,
                        NUM = listModelType.Count() + 1,
                        REMARK = "导入添加",
                        IS_DELETED = false,
                        ORG_ID = OrgID,
                        //ENTITY_ORG_TPYE
                        //FORM_ID
                        //FLOW_STATUS
                        //FLOW_SEND_STATUS
                        //FLOW_ID
                        //CREATE_TIME
                        //MODIFY_TIME
                        //CREATER_ID
                        //MODIFIER_ID
                        PARENT_ID = null,
                        //TEXT=
                        IS_LEAF = false,
                    };
                    listCheckType.Add(modelType);
                    listModelType.Add(modelType);
                }

                #endregion

                #region //项目分类  2

                //strProjCate = dtSource.Rows[i][2].ToString().Trim();
                //modelProjCate = listModelProjCate.FirstOrDefault(e => e.NAME == strProjCate);
                //if (modelProjCate == null)
                //{
                //    //检查项目分类
                //    listProjCate.Add(i + rowIndex);
                //    if (!listStrProjCate.Contains(strProjCate))
                //        listStrProjCate.Add(strProjCate);
                //    continue;
                //}

                #endregion

                #region 检查层级  3

                strTypeLevel = dtSource.Rows[i][3].ToString().Trim();
                modelTypeLevel = listModelTypeLevel.FirstOrDefault(e => e.Nav_Enums.NAME == strTypeLevel && e.Nav_CheckType.NAME == strType);
                if (modelTypeLevel == null)
                {
                    //检查层级
                    //listTypeLevel.Add(i);
                    //if (!listStrTypeLevel.Contains(strType + "-" + strTypeLevel))
                    //    listStrTypeLevel.Add(strType + "-" + strTypeLevel);
                    if (listCheckTypeLevelEnums == null)
                        listCheckTypeLevelEnums = GetEntities<T_FM_ENUMS>(null, null).ToList();
                    TypeLevelEnumsTemp = listCheckTypeLevelEnums.FirstOrDefault(e => e.NAME == strTypeLevel);
                    if (TypeLevelEnumsTemp == null)
                    {
                        listTypeLevel.Add(i + rowIndex);
                        if (!listStrTypeLevel.Contains(strType + "-" + strTypeLevel))
                            listStrTypeLevel.Add(strType + "-" + strTypeLevel);
                        continue;
                    }
                    else
                    {
                        modelTypeLevel = new T_BS_CHECK_TYPE_LEVEL()
                        {
                            ID = Guid.NewGuid(),
                            CHECK_TYPE_ID = modelType.ID,
                            IS_DELETED = false,
                            ORG_ID = OrgID,
                            //ENTITY_ORG_TPYE
                            //FORM_ID
                            //FLOW_STATUS
                            //FLOW_SEND_STATUS
                            //FLOW_ID
                            //CREATE_TIME
                            //MODIFY_TIME
                            //CREATER_ID
                            //MODIFIER_ID
                            CheckLevel_ENUMS_ID = TypeLevelEnumsTemp.ID,
                            CODE = strTypeLevel
                        };
                        listCheckTypeLevel.Add(modelTypeLevel);
                        //modelTypeLevel.Nav_Enums = TypeLevelEnumsTemp;
                        //modelTypeLevel.Nav_CheckType = modelType;
                        listModelTypeLevel.Add(
                            new T_BS_CHECK_TYPE_LEVEL()
                            {
                                ID = modelTypeLevel.ID,
                                CHECK_TYPE_ID = modelType.ID,
                                IS_DELETED = false,
                                ORG_ID = OrgID,
                                //ENTITY_ORG_TPYE
                                //FORM_ID
                                //FLOW_STATUS
                                //FLOW_SEND_STATUS
                                //FLOW_ID
                                //CREATE_TIME
                                //MODIFY_TIME
                                //CREATER_ID
                                //MODIFIER_ID
                                CheckLevel_ENUMS_ID = TypeLevelEnumsTemp.ID,
                                CODE = strTypeLevel,
                                Nav_Enums = TypeLevelEnumsTemp,
                                Nav_CheckType = modelType,
                            });
                    }
                }

                #endregion

                #region     责任单位 4

                strDepName = dtSource.Rows[i][4].ToString().Trim();
                listDepName = strDepName.Split(charSplit, StringSplitOptions.RemoveEmptyEntries).ToList();

                ListModelDepartment = listDep.FindAll(e => listDepName.Contains(e.NAME));
                if (ListModelDepartment == null || ListModelDepartment.Count == 0)
                {
                    listDepartment.Add(i + rowIndex);
                    if (!listStrDepartmentName.Contains(strDepName))
                    {
                        listStrDepartmentName.Add(strDepName);
                    }
                    continue;
                }
                else if (ListModelDepartment.Count != listDepName.Count)
                {
                    listDepartment.Add(i + rowIndex);
                    if (!listStrDepartmentName.Contains(strDepName))
                    {
                        listStrDepartmentName.Add(strDepName);
                    }
                    continue;
                }
                #endregion

                #region  检查项目 5 

                strProject = dtSource.Rows[i][5].ToString().Trim();
                modelProject = listModelProject.FirstOrDefault(e => e.NAME == strProject);
                if (modelProject == null && dicIndexEmpty.Count < 1 && listType.Count < 1 && listTypeLevel.Count < 1 && listQuestionLevel.Count < 1)//&& listProjCate.Count < 1
                {
                    //检查项目  listProject.Add(i);
                    modelProject = new T_BS_CHECK_PROJECT();
                    modelProject.ID = Guid.NewGuid();
                    modelProject.NAME = strProject;
                    modelProject.ENABLE_STATUS = 0;
                    modelProject.NUM = i;
                    //modelProject.REMARK              =;
                    modelProject.IS_DELETED = false;
                    modelProject.ORG_ID = OrgID;
                    //modelProject.ENTITY_ORG_TPYE     =;
                    //modelProject.FORM_ID             =;
                    //modelProject.FLOW_STATUS         =;
                    //modelProject.FLOW_SEND_STATUS    =;
                    //modelProject.FLOW_ID             =;
                    modelProject.CREATE_TIME = dtNow;
                    modelProject.MODIFY_TIME = dtNow;
                    //modelProject.CREATER_ID          =;
                    //modelProject.MODIFIER_ID         =;
                    listProjectAdd.Add(modelProject);
                    listModelProject.Add(modelProject);
                }

                #endregion

                #region   检查内容 6

                strContents = dtSource.Rows[i][6].ToString().Trim();
                modelContents = listModelContents.FirstOrDefault(e => e.CHECKCONTENT == strContents && BSMineTypeEnum.Mine == e.CHECKOBJECT);
                if (modelContents == null)
                {
                    modelContents = new T_BS_CHECK_CONTENTS();
                    modelContents.ID = Guid.NewGuid();
                    modelContents.CHECKCONTENT = strContents;
                    modelContents.IS_DELETED = false;
                    modelContents.ORG_ID = OrgID;
                    //modelContents.ENTITY_ORG_TPYE =;
                    //modelContents.FORM_ID =;
                    //modelContents.FLOW_STATUS =;
                    //modelContents.FLOW_SEND_STATUS =;
                    //modelContents.FLOW_ID =;
                    modelContents.CREATE_TIME = dtNow;
                    modelContents.MODIFY_TIME = dtNow;
                    //modelContents.CREATER_ID =;
                    //modelContents.MODIFIER_ID =;
                    modelContents.CHECKOBJECT = BSMineTypeEnum.Mine;// (BSMineTypeEnum)ICheckObject;

                    listModelContents.Add(modelContents);
                    listModelContentsAdd.Add(modelContents);
                }

                #endregion

                #region  检查问题等级   8

                strQuestionLevel = dtSource.Rows[i][8].ToString().Trim();
                enumCheck = listLevel.FirstOrDefault(e => e.NAME == strQuestionLevel);
                if (enumCheck != null)
                    iQuestionLevel = enumCheck.ID;
                else
                {
                    listQuestionLevel.Add(i + rowIndex); //检查问题等级
                    continue;
                }
                #endregion

                #region   检查问题 7  （添加数据库）

                strDescreption = dtSource.Rows[i][7].ToString().Trim();
                modelQuestion = listCheckQuestion.FirstOrDefault(e => !e.IS_DELETED && e.DESCREPTION == strDescreption);// && e.DEMAND == strDemand  不报错

                if (modelQuestion == null && dicIndexEmpty.Count < 1 && listType.Count < 1 && listTypeLevel.Count < 1 && listQuestionLevel.Count < 1)//&& listProjCate.Count < 1
                {
                    strDemand = dtSource.Rows[i][9].ToString().Trim();

                    modelQuestion = new T_BS_CHECK_QUESTION();
                    modelQuestion.ID = Guid.NewGuid();
                    modelQuestion.DESCREPTION = strDescreption;
                    modelQuestion.DEMAND = strDemand;
                    modelQuestion.NUM = i;
                    modelQuestion.ENABLE_STATUS = 0;
                    modelQuestion.IS_DELETED = false;
                    modelQuestion.ORG_ID = OrgID;

                    modelQuestion.QUESTION_LEVEL = (BSQuestionLevelEnum)iQuestionLevel;
                    modelQuestion.CHECK_CONTENTS_ID = modelContents.ID;

                    //modelQuestion.ENTITY_ORG_TPYE    =;
                    //modelQuestion.FORM_ID            =;
                    //modelQuestion.FLOW_STATUS        =;
                    //modelQuestion.FLOW_SEND_STATUS   =;
                    //modelQuestion.FLOW_ID            =;
                    modelQuestion.CREATE_TIME = dtNow;
                    modelQuestion.MODIFY_TIME = dtNow;
                    //modelQuestion.CREATER_ID         =;
                    //modelQuestion.MODIFIER_ID        =;
                    listCheckQuestion.Add(modelQuestion);//以便下次使用
                    listCheckQuestionAdd.Add(modelQuestion);//添加到数据库
                }

                #endregion

                #region      listMain

                if (dicIndexEmpty.Count < 1 && listType.Count < 1 && listTypeLevel.Count < 1 && listQuestionLevel.Count < 1 && listDepartment.Count < 1)// && listProjCate.Count < 1
                {
                    T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                    modelAdd.ID = Guid.NewGuid();
                    modelAdd.CHECKOBJECT = (int)BSMineTypeEnum.Mine;// ICheckObject;
                    modelAdd.CHECK_PROJECT_ID = modelProject.ID;
                    modelAdd.CHECK_QUESTION_ID = modelQuestion.ID;
                    modelAdd.CHECKCONTENT = dtSource.Rows[i][6].ToString().Trim();//dtSource.Rows[i][8]
                    //modelAdd.CHECKPROOF = dtSource.Rows[i][9].ToString().Trim();
                    modelAdd.QUESTION_LEVEL = iQuestionLevel;
                    modelAdd.SERIOUS_RISK = iQuestionLevel == 10 ? 1 : 0;
                    modelAdd.CHECK_TYPE_ID = modelType.ID;
                    modelAdd.CHECK_TYPE_LEVEL_ID = modelTypeLevel.ID;
                    modelAdd.RISK_AREA_ID = modelArea.ID;
                    modelAdd.ENABLE_STATUS = 0;
                    modelAdd.NUM = i;
                    modelAdd.IS_DELETED = false;
                    modelAdd.ORG_ID = OrgID;
                    //modelAdd.ENTITY_ORG_TPYE =    ;
                    //modelAdd.FORM_ID =    ;
                    //modelAdd.FLOW_STATUS =    ;
                    //modelAdd.FLOW_SEND_STATUS =    ;
                    //modelAdd.FLOW_ID =    ;
                    modelAdd.CREATE_TIME = dtNow;
                    modelAdd.MODIFY_TIME = dtNow;
                    //modelAdd.CREATER_ID =    ;
                    //modelAdd.MODIFIER_ID =    ;
                    modelAdd.ISRISK = false;
                    //modelAdd.CHECK_PROJECT_CATEGORY_ID = modelProjCate.ID;
                    //modelAdd.CHECK_PROJECT_PROJECT_CATEGORY_ID =    ;
                    //wyw1114-1
                    //modelAdd.RESPONOBJECT = RESPONOBJECT.Value;
                    //modelAdd.DEPARTMENT_ID = item.ID;
                    modelAdd.CHECK_CONTENTS_ID = modelContents.ID;

                    listMain.Add(modelAdd);
                    //责任部门 可能多个
                    foreach (var item in ListModelDepartment)
                    {
                        listMainDep.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                        {
                            ID = Guid.NewGuid(),
                            MAIN_ID = modelAdd.ID,
                            ORG_ID = modelAdd.ORG_ID,
                            DEPARTMENT_ID = item.ID,
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head,// RESPONOBJECT.Value
                        });
                    }
                }

                #endregion
            }

            #endregion

            #region     提示

            // 行：1，列：2、3、4；行：2，列：1 不能为空！
            string strEmptyError = string.Empty;
            if (dicIndexEmpty.Count > 0)
            {
                int colIndex = 0;
                foreach (var item in dicIndexEmpty)
                {
                    strEmptyError += "行：" + item.Key + "，列：";
                    colIndex = 0;
                    foreach (var itemVal in item.Value)
                    {
                        strEmptyError += (colIndex > 0 ? "、" : "") + itemVal;
                        colIndex++;
                    }
                    strEmptyError += "；";
                }
                strEmptyError = strEmptyError.Substring(0, strEmptyError.Length - 1) + "不能为空！";
            }

            //string strAreaError = string.Empty;
            //if (listArea != null && listArea.Count > 0)
            //{
            //    strAreaError = "未找到检查区域" + string.Join(',', listArea);
            //}

            string strTypeError = string.Empty;
            if (listType != null && listType.Count > 0)
            {
                strTypeError = "未找到检查类型:" + string.Join(",", listStrType) + "，行：" + string.Join(',', listType);
            }
            //string strProjCateError = string.Empty;
            //if (listProjCate != null && listProjCate.Count > 0)
            //{
            //    strProjCateError = "未找到检查项目分类:" + string.Join(",", listStrProjCate) + ",行：" + string.Join(',', listProjCate);
            //}
            //listStrProjCate listStrTypeLevel
            string strTypeLevelError = string.Empty;
            if (listTypeLevel != null && listTypeLevel.Count > 0)
            {
                strTypeLevelError = "未找到检查层级:" + string.Join(",", listStrTypeLevel) + "，行：" + string.Join(',', listTypeLevel);
            }

            //string strProjectError = string.Empty;
            //if (listProject != null && listProject.Count > 0)
            //{
            //    strProjectError = "未找到检查项目" + string.Join(',', listProject);
            //}

            string strQuestionLevelError = string.Empty;
            if (listQuestionLevel != null && listQuestionLevel.Count > 0)
            {
                strQuestionLevelError = "未找到问题等级，行：" + string.Join(',', listQuestionLevel);
            }


            string strDepartmentError = string.Empty;
            if (listDepartment != null && listDepartment.Count > 0)
            {
                strDepartmentError += "未找到责任单位" + string.Join(',', listStrDepartmentName) + "，行：" + string.Join(',', listDepartment);
            }

            if (!string.IsNullOrEmpty(strEmptyError))
            {
                Msg += strEmptyError;
            }
            //if (!string.IsNullOrEmpty(strAreaError))
            //{
            //    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strAreaError;
            //}
            if (!string.IsNullOrEmpty(strTypeError))
            {
                Msg += (Msg.Length > 0 ? "、\r\n" : "") + strTypeError;
            }
            //if (!string.IsNullOrEmpty(strProjCateError))
            //{
            //    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strProjCateError;
            //}
            if (!string.IsNullOrEmpty(strTypeLevelError))
            {
                Msg += (Msg.Length > 0 ? "、\r\n" : "") + strTypeLevelError;
            }
            //if (!string.IsNullOrEmpty(strProjectError))
            //{
            //    Msg += (Msg.Length > 0 ? "、\r\n" : "") + strProjectError;
            //}
            if (!string.IsNullOrEmpty(strQuestionLevelError))
            {
                Msg += (Msg.Length > 0 ? "、\r\n" : "") + strQuestionLevelError;
            }
            if (!string.IsNullOrEmpty(strDepartmentError))
            {
                Msg += (Msg.Length > 0 ? "、\r\n" : "") + strDepartmentError;
            }

            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }

            #endregion

            this.UnifiedCommit(() =>
            {
                if (listModelContentsAdd != null && listModelContentsAdd.Any())
                    BantchSaveEntityNoCommit(listModelContentsAdd);
                if (listMain != null && listMain.Any())
                    BantchSaveEntityNoCommit(listMain);
                if (listCheckQuestionAdd != null && listCheckQuestionAdd.Any())
                    BantchSaveEntityNoCommit(listCheckQuestionAdd);
                if (listAreaAdd != null && listAreaAdd.Any())
                    BantchSaveEntityNoCommit(listAreaAdd);
                if (listProjectAdd != null && listProjectAdd.Any())
                    BantchSaveEntityNoCommit(listProjectAdd);
                if (listCheckType != null && listCheckType.Any())
                    BantchSaveEntityNoCommit(listCheckType);
                if (listCheckTypeLevel != null && listCheckTypeLevel.Any())
                    BantchSaveEntityNoCommit(listCheckTypeLevel);
                if (listMainDep != null && listMainDep.Any())
                    BantchSaveEntityNoCommit(listMainDep);
            });

            Msg = "导入成功！\r\n检查库：" + listMain.Count + "条" + (listModelContentsAdd.Count > 0 ? ("、检查内容：" + listModelContentsAdd.Count + "条") : "") + (listCheckQuestionAdd.Count > 0 ? ("、检查问题：" + listCheckQuestionAdd.Count + "条") : "") + (listAreaAdd.Count > 0 ? ("、检查区域：" + listAreaAdd.Count + "条、") : "") + (listProjectAdd.Count > 0 ? ("检查项目：" + listProjectAdd.Count + "条") : "") + (listCheckType.Count > 0 ? ("检查类型：" + listCheckType.Count + "条") : "") + (listCheckTypeLevel.Count > 0 ? ("检查类型等级：" + listCheckTypeLevel.Count + "条") : "") + "！";
            return true;
        }

        /// <summary>
        /// 更新或新增数据
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_BS_CHECK_MAIN entity)
        {
            return SafeExecute(() =>
            {
                var listMainDep = entity.Nav_ListMainDep;
                entity.Nav_ListMainDep = null;
                var listLaw = entity.Nav_ListLaw;
                entity.Nav_ListLaw = null;

                if (listMainDep != null && !listMainDep.Any())
                {
                    foreach (var item in listMainDep)
                    {
                        item.Nav_Department = null;
                    }
                }
                entity.CHECKPROOF = "";
                if (listLaw != null && listLaw.Any())
                {
                    foreach (var item in listLaw)
                    {
                        //entity.CHECKPROOF += (string.IsNullOrEmpty(entity.CHECKPROOF) ? "" : "，") + item.Nav_Law.NAME;
                        //item.Nav_Law = null;
                        entity.CHECKPROOF += (string.IsNullOrEmpty(entity.CHECKPROOF) ? "" : "，") + item.Nav_Standard.NAME;
                        item.Nav_Standard = null;
                    }
                }
                if (entity.CHECKPROOF != null && entity.CHECKPROOF.Length > 500)
                {
                    entity.CHECKPROOF = entity.CHECKPROOF.Substring(0, 490);
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntity(entity);
                    if (listMainDep != null && listMainDep.Any())
                        BantchSaveEntityNoCommit(listMainDep);
                    if (listLaw != null && listLaw.Any())
                        BantchSaveEntityNoCommit(listLaw);
                });
                return true;
            });
        }

        /// <summary>
        /// 获取导出数据  
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetOutPutData")]
        public PagedActionResult<OutPutInfo> GetOutPutData([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<OutPutInfo> result)
            {
                pageFilter.SelectField = null;
                pageFilter.Include = null;
                #region    获取搜索信息
                List<string> listPath = new List<string>();
                //Groups => Rules
                Guid? CHECK_TYPE_ID = null;//CHECK_TYPE_ID
                Guid? RISK_AREA_ID = null;//RISK_AREA_ID

                ////Rules
                //BSMineTypeEnum? CHECKOBJECT = null;//CHECKOBJECT
                BSQuestionLevelEnum? QUESTION_LEVEL = null; //QUESTION_LEVEL
                BSSeriousRiskEnum? SERIOUS_RISK = null; //SERIOUS_RISK
                string CHECKCONTENT = string.Empty;
                //string CHECKPROOF = string.Empty;
                string CheckTypeLevelName = string.Empty; //Nav_CheckTypeLevel.Nav_Enums.NAME
                string CheckProjectNAME = string.Empty; //Nav_CheckProject.NAME
                string CheckProjectCategoryNAME = string.Empty;//Nav_CheckProjectCategory.NAME

                if (pageFilter.FilterGroup.Groups != null && pageFilter.FilterGroup.Groups.Any())
                {
                    foreach (var item in pageFilter.FilterGroup.Groups)
                    {
                        if (item.Rules != null && item.Rules.Any())
                        {
                            foreach (var itemRule in item.Rules)
                            {
                                if (itemRule.Field == "CHECK_TYPE_ID" && itemRule.Value != null)
                                {
                                    CHECK_TYPE_ID = new Guid(itemRule.Value.ToString());
                                    listPath.Add("Nav_CheckType");
                                }
                                else if (itemRule.Field == "RISK_AREA_ID" && itemRule.Value != null)
                                {
                                    RISK_AREA_ID = new Guid(itemRule.Value.ToString());
                                    listPath.Add("Nav_RiskArea");
                                }
                            }
                        }
                    }
                }

                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Any())
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        switch (item.Field)
                        {
                            case "Nav_CheckProjectCategory.NAME":
                                CheckProjectCategoryNAME = item.Value.ToString();
                                listPath.Add("Nav_CheckProjectCategory");
                                break;
                            case "Nav_CheckProject.NAME":
                                CheckProjectNAME = item.Value.ToString();
                                listPath.Add("Nav_CheckProject");
                                break;
                            case "Nav_CheckTypeLevel.Nav_Enums.NAME":
                                CheckTypeLevelName = item.Value.ToString();
                                listPath.Add("Nav_CheckTypeLevel.Nav_Enums");
                                break;
                            case "CHECKCONTENT":
                                CHECKCONTENT = item.Value.ToString();
                                break;
                            case "QUESTION_LEVEL":
                                QUESTION_LEVEL = (BSQuestionLevelEnum)int.Parse(item.Value.ToString());
                                break;
                            case "SERIOUS_RISK":
                                SERIOUS_RISK = (BSSeriousRiskEnum)int.Parse(item.Value.ToString());
                                break;
                            default:
                                break;
                        }
                    }
                }

                //检查范围    "检查区域（辨识区域）"	检查类型	检查项目分类	检查层级	责任单位	检查周期	"检查项目（辨识对象）"	"检查内容（风险对象 + 是否 + 管控措施）"	检查依据	"检查问题描述（失效后的所有现象，逐条填写）"	检查问题等级	重大隐患类别	整改建议与措施	责任人

                #endregion

                //检查库
                var IListCheckMain = GetEntities<T_BS_CHECK_MAIN>(e => !e.IS_DELETED && e.RISK_AREA_ID.HasValue && e.CHECK_QUESTION_ID.HasValue && e.CHECK_TYPE_ID.HasValue && e.CHECK_PROJECT_ID.HasValue && e.CHECK_TYPE_LEVEL_ID.HasValue, pageFilter, null).OrderByDescending(e => e.CREATE_TIME);//&& e.Nav_ListMainDep.Any()&& e.CHECK_CONTENTS_ID.HasValue
                if (IListCheckMain == null || !IListCheckMain.Any())
                    return;

                //检查类型
                Expression<Func<T_BS_CHECK_TYPE, bool>> expressionCheckType = e => !e.IS_DELETED;
                if (CHECK_TYPE_ID.HasValue)
                    expressionCheckType = expressionCheckType.And(e => e.ID == CHECK_TYPE_ID.Value);
                if (!string.IsNullOrEmpty(CheckTypeLevelName))
                    expressionCheckType = expressionCheckType.And(e => e.Nav_ListCheckTypeLevel.Where(ee => ee.Nav_Enums.NAME.Contains(CheckTypeLevelName)).Any());
                var IListCheckType = GetEntities<T_BS_CHECK_TYPE>(expressionCheckType, null, "Nav_ListCheckTypeLevel.Nav_Enums");
                if (IListCheckType == null || !IListCheckType.Any())
                    return;

                //检查区域
                Expression<Func<T_HM_RISK_AREA, bool>> expressionArea = e => !e.IS_DELETED;
                if (RISK_AREA_ID.HasValue)
                    expressionArea = expressionArea.And(e => e.ID == RISK_AREA_ID.Value);
                var IListArea = GetEntities<T_HM_RISK_AREA>(expressionArea, null, null);
                if (IListArea == null || !IListArea.Any())
                    return;


                //检查项目
                Expression<Func<T_BS_CHECK_PROJECT, bool>> expressionProject = e => !e.IS_DELETED;
                if (!string.IsNullOrEmpty(CheckProjectNAME))
                    expressionProject = expressionProject.And(e => e.NAME.Contains(CheckProjectNAME));
                var IListProject = GetEntities<T_BS_CHECK_PROJECT>(expressionProject, null, null);
                if (IListProject == null || !IListProject.Any())
                    return;

                //检查项目分类
                Expression<Func<T_BS_CHECK_PROJECT_CATEGORY, bool>> expressionProjectCategory = e => !e.IS_DELETED;
                if (!string.IsNullOrEmpty(CheckProjectCategoryNAME))
                    expressionProjectCategory = expressionProjectCategory.And(e => e.NAME.Contains(CheckProjectCategoryNAME));
                var IiListProjectCategory = GetEntities<T_BS_CHECK_PROJECT_CATEGORY>(expressionProjectCategory, null, null);
                if (IiListProjectCategory == null || !IiListProjectCategory.Any())
                    return;

                //检查内容
                Expression<Func<T_BS_CHECK_CONTENTS, bool>> expressionContents = e => !e.IS_DELETED;
                if (!string.IsNullOrEmpty(CHECKCONTENT))
                    expressionContents = expressionContents.And(e => e.CHECKCONTENT.Contains(CHECKCONTENT));
                if (QUESTION_LEVEL.HasValue)
                    expressionContents = expressionContents.And(e => e.Nav_ListCheckQuestion.Where(ee => ee.QUESTION_LEVEL == QUESTION_LEVEL.Value).Any());
                var IListContents = GetEntities<T_BS_CHECK_CONTENTS>(expressionContents, null, null);
                if (IListContents == null || !IListContents.Any())
                    return;

                //检查问题
                Expression<Func<T_BS_CHECK_QUESTION, bool>> expressionQuestopn = e => !e.IS_DELETED;
                if (QUESTION_LEVEL.HasValue)
                    expressionQuestopn = expressionQuestopn.And(e => e.QUESTION_LEVEL == QUESTION_LEVEL.Value);
                if (SERIOUS_RISK.HasValue)
                    expressionQuestopn = expressionQuestopn.And(e => e.SERIOUS_RISK == (int)SERIOUS_RISK.Value);
                var IListQuestion = GetEntities<T_BS_CHECK_QUESTION>(e => !e.IS_DELETED, null, null);
                if (IListQuestion == null || !IListQuestion.Any())
                    return;

                var listMainDep = GetEntities<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT>(e => !e.IS_DELETED && e.MAIN_ID.HasValue, null, null);

                //责任部门  Main  Nav_ListMainDep
                var IListDep = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED, null, null);



                string split = "、";//char[] charSplit = new char[] { '、', '；' };

                List<OutPutData> listDataResult = new List<OutPutData>();
                OutPutData model = null;
                List<string> listDep = null;
                T_BS_CHECK_QUESTION mainQuestion = null;
                BSPLANCHECKOBJECTEnum? RESPONOBJECT = null;
                T_BS_CHECK_TYPE modelCheckType = null;

                foreach (var item in IListCheckMain)
                {
                    listDep = new List<string>();
                    RESPONOBJECT = null;
                    item.Nav_ListMainDep = listMainDep.Where(e => e.MAIN_ID.Value == item.ID).ToList();
                    if (item.Nav_ListMainDep != null && item.Nav_ListMainDep.Any())
                    {
                        foreach (var itemDep in item.Nav_ListMainDep)
                        {
                            if (!itemDep.IS_DELETED && itemDep.DEPARTMENT_ID.HasValue)
                            {
                                listDep.Add(IListDep.FirstOrDefault(e => e.ID == itemDep.DEPARTMENT_ID.Value)?.NAME);
                                RESPONOBJECT = itemDep.RESPONOBJECT;
                            }
                        }
                    }
                    else
                    {
                        RESPONOBJECT = null;
                    }
                    if (!listDep.Any())
                        continue;
                    mainQuestion = IListQuestion.FirstOrDefault(e => e.ID == item.CHECK_QUESTION_ID.Value);
                    if (mainQuestion == null)
                        continue;
                    modelCheckType = IListCheckType.FirstOrDefault(e => e.ID == item.CHECK_TYPE_ID.Value);
                    if (mainQuestion == null)
                        continue;

                    //责任单位 合并为一个单元
                    model = new OutPutData();
                    model.CHECKOBJECT = ((BSMineTypeEnum)item.CHECKOBJECT).GetDescription();
                    model.AREA_NAME = (IListArea.FirstOrDefault(e => e.ID == item.RISK_AREA_ID.Value))?.NAME;
                    model.CHECK_TYPE_NAME = modelCheckType.NAME;
                    model.CHECK_PROJECT_CATEGORY_NAME = (IiListProjectCategory.FirstOrDefault(e => e.ID == item.CHECK_PROJECT_CATEGORY_ID.Value))?.NAME;
                    model.CHECK_TYPE_LEVEL_NAME = modelCheckType.Nav_ListCheckTypeLevel.FirstOrDefault(e => e.ID == item.CHECK_TYPE_LEVEL_ID)?.Nav_Enums?.NAME;
                    model.List_DEPARTMENT_NAME = string.Join(split, listDep);
                    model.JCZQ = "";
                    model.CHECK_PROJECT_NAME = (IListProject.FirstOrDefault(e => e.ID == item.CHECK_PROJECT_ID.Value))?.NAME;
                    model.CHECKCONTENT = item.CHECKCONTENT;
                    model.CHECKPROOF = item.CHECKPROOF;
                    model.DESCREPTION = mainQuestion.DESCREPTION;
                    model.QUESTION_LEVEL = ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription();
                    if (item.SERIOUS_RISK == (int)BSSeriousRiskEnum.是)
                        model.SERIOUS_RISK = "是";

                    model.DEMAND = mainQuestion.DEMAND;
                    model.RESPONOBJECT = RESPONOBJECT.HasValue ? RESPONOBJECT.GetDescription() : "";

                    listDataResult.Add(model);
                }

                OutPutInfo outPutInfo = new OutPutInfo();
                outPutInfo.listData = listDataResult;
                outPutInfo.listColDataTitle = new List<string>() { "检查范围", "检查区域", "检查类型", "检查项目分类", "检查层级", "责任单位", "检查周期", "检查项目", "检查内容", "检查依据", "检查问题描述", "检查问题等级", "重大隐患类别", "整改建议与措施", "责任人" };
                outPutInfo.listColDataIndex = new List<string>() { "CHECKOBJECT", "AREA_NAME", "CHECK_TYPE_NAME", "CHECK_PROJECT_CATEGORY_NAME", "CHECK_TYPE_LEVEL_NAME", "List_DEPARTMENT_NAME", "JCZQ", "CHECK_PROJECT_NAME", "CHECKCONTENT", "CHECKPROOF", "DESCREPTION", "QUESTION_LEVEL", "SERIOUS_RISK", "DEMAND", "RESPONOBJECT" };

                result.Data = new List<OutPutInfo>() { outPutInfo };
                result.TotalCount = listDataResult.Count;
            });
        }
    }

    public class OutPutData
    {
        /// <summary>
        /// 检查范围
        /// </summary>
        public string CHECKOBJECT { get; set; }

        /// <summary>
        /// 检查区域
        /// </summary>
        public string AREA_NAME { get; set; }

        /// <summary>
        /// 检查类型
        /// </summary>
        public string CHECK_TYPE_NAME { get; set; }

        /// <summary>
        /// 检查项目分类
        /// </summary>
        public string CHECK_PROJECT_CATEGORY_NAME { get; set; }

        /// <summary>
        /// 检查层级
        /// </summary>
        public string CHECK_TYPE_LEVEL_NAME { get; set; }

        /// <summary>
        /// 责任单位
        /// </summary>
        public string List_DEPARTMENT_NAME { get; set; }

        /// <summary>
        /// 检查周期--空 
        /// </summary>
        public string JCZQ { get; set; }

        /// <summary>
        /// 检查项目 
        /// </summary>
        public string CHECK_PROJECT_NAME { get; set; }

        /// <summary>
        /// 检查内容 
        /// </summary>
        public string CHECKCONTENT { get; set; }

        /// <summary>
        /// 检查依据 
        /// </summary>
        public string CHECKPROOF { get; set; }

        /// <summary>
        /// 检查问题描述
        /// </summary>
        public string DESCREPTION { get; set; }

        /// <summary>
        /// 问题等级  BSQuestionLevelEnum   检查问题等级
        /// </summary>
        public string QUESTION_LEVEL { get; set; }

        /// <summary>
        /// 是否重大隐患  重大隐患类别 
        /// </summary>
        public string SERIOUS_RISK { get; set; } = BSSeriousRiskEnum.否.GetDescription();

        /// <summary>
        /// 整改建议与措施
        /// </summary>
        public string DEMAND { get; set; }

        /// <summary>
        /// 责任对象 string  责任人
        /// </summary>
        public string RESPONOBJECT { get; set; } = BSPLANCHECKOBJECTEnum.Head.GetDescription();

    }

    /// <summary>
    /// 自定义导出数据结构
    /// </summary>
    public class OutPutInfo
    {
        public List<OutPutData> listData { get; set; }
        public List<string> listColDataIndex { get; set; }
        public List<string> listColDataTitle { get; set; }
    }
}