using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.LR;
using APT.MS.Domain.Entities.SC.PT;
using APT.MS.Domain.Entities.SK;
using APT.MS.Domain.Enums.SK;
using APT.Utility;
using Castle.Core.Internal;
using Google.Protobuf.WellKnownTypes;
using ICSharpCode.SharpZipLib.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using Org.BouncyCastle.Asn1.Ess;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using Ubiety.Dns.Core;

namespace APT.SK.WebApi.Controllers.Api
{
    /// <summary>
    ///  检查内容
    /// </summary>
    [Route("api/SK/SKCheckContents")]
    public partial class CheckContentsController : AuthorizeApiController<T_SK_CHECK_CONTENTS>
    {
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("SKOrderPaged")]
        public PagedActionResult<T_SK_CHECK_CONTENTS> SKOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            if (pageFilter.Sort == "NAME")
            {
                pageFilter.Sort = "";
            }
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "reset");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
            {
                pageFilter.FilterGroup.Rules.Remove(filter);
            }
            pageFilter.Include.Add("Nav_ListCheckQuestion");
            pageFilter.Include.Add("Nav_ContentsBasics.Nav_Law");
            pageFilter.SelectField.Add("Nav_ProductionUnit.NAME");
            pageFilter.SelectField.Add("CHECKCONTENT");
            pageFilter.SelectField.Add("CHECK_STANDARD");
            pageFilter.SelectField.Add("JT_SYNC");
            pageFilter.SelectField.Add("Nav_ListCheckQuestion.NUM");
            pageFilter.SelectField.Add("Nav_ListCheckQuestion.DESCREPTION");
            pageFilter.SelectField.Add("Nav_ListCheckQuestion.QUESTION_LEVEL");
            pageFilter.SelectField.Add("Nav_ListCheckQuestion.DEMAND");
            pageFilter.SelectField.Add("Nav_ContentsBasics.Nav_Law.NAME");
            var result = GetOrderPageEntities<T_SK_CHECK_CONTENTS>(null, pageFilter);
            if (result != null && result.Data != null && result.Data.Any())
            {
                foreach (var item in result.Data)
                {
                    if (item.Nav_ListCheckQuestion != null && item.Nav_ListCheckQuestion.Any())
                    {
                        foreach (var item2 in item.Nav_ListCheckQuestion.OrderBy(t => t.NUM))
                        {
                            if (item2 != null && !string.IsNullOrEmpty(item2.DESCREPTION) && !string.IsNullOrEmpty(item2.DEMAND))
                            {
                                var tempD = item2.NUM + "*" + item2.DESCREPTION;
                                item.DESCREPTION = item.DESCREPTION + tempD;
                                var tempL = item2.NUM + "*" + item2.QUESTION_LEVEL.GetDescription() +"。";
                                item.QUESTION_LEVEL_SHOW = item.QUESTION_LEVEL_SHOW + tempL;
                                var tempM = item2.NUM + "*" + item2.DEMAND;
                                item.DEMAND = item.DEMAND + tempM;
                            }
                        }
                    }
                    if (item.Nav_ContentsBasics != null && item.Nav_ContentsBasics.Any())
                    {
                        item.CHECK_BASICS = string.Join("；", item.Nav_ContentsBasics.Select(t=>t.Nav_Law?.NAME));
                    }
                }
            }
            return result;
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("SkGet")]
        public JsonActionResult<T_SK_CHECK_CONTENTS> SkGet([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_SK_CHECK_CONTENTS>(() =>
            {
               if(filter.FilterGroup.Rules.Any(t=>t.Field=="ID"))
                {
                    var ids = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                    if(ids.Contains(","))
                    {
                        var idArr = ids.Split(",");
                        filter.FilterGroup.Rules.Remove(filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID"));
                        filter.FilterGroup.Rules.Add(new APT.Infrastructure.Core.FilterRule
                        {
                            Field = "ID",
                            Operate = FilterOperate.Equal,
                            Value = idArr.FirstOrDefault()
                        });
                    }
                }
                var entity = this.GetEntity<T_SK_CHECK_CONTENTS>(null,filter);
                entity.Nav_ListCheckQuestion = entity.Nav_ListCheckQuestion?.OrderBy(t => t.NUM).ToList();
                return entity;
            });
        
        }

        /// <summary>
        /// 更新或新增数据
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SK_CHECK_CONTENTS entity)
        {
            return SafeExecute<bool>(() =>
            {
                var olds = this.GetEntity<T_SK_CHECK_CONTENTS>(t => !t.IS_DELETED && t.CHECKCONTENT == entity.CHECKCONTENT && t.ID != entity.ID && t.PRODUCTION_UNIT_ID == entity.PRODUCTION_UNIT_ID);
                if (olds != null)
                {
                    throw new Exception("检查内容重复，请先修改");
                }
                var details = entity.Nav_ListCheckQuestion;
                entity.Nav_ListCheckQuestion = null;
                if (details != null && details.Any())
                {
                    foreach (var item in details)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.CHECK_CONTENTS_ID = entity.ID;
                    }
                }
                var basics = entity.Nav_ContentsBasics;
                entity.Nav_ContentsBasics = null;
                if (basics != null && basics.Any())
                {
                    foreach (var item in basics)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.CHECK_CONTENTS_ID = entity.ID;
                        item.Nav_Law = null;
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        BantchSaveEntityNoCommit(details);
                    if (basics != null && basics.Any())
                        BantchSaveEntityNoCommit(basics);
                });
                return true;
            });
        }
        /// <summary>
        /// 检查内容对应的隐患描述
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetHiddenScripList")]
        public PagedActionResult<T_SK_CHECK_QUESTION> GetHiddenScripList([FromBody] KeywordPageFilter pageFilter)
        {
            if (pageFilter.Sort == "NAME")
            {
                pageFilter.Sort = "";
            }
            var result = new PagedActionResult<T_SK_CHECK_QUESTION>();
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "CHECK_CONTENTS_ID");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
            {
                pageFilter.FilterGroup.Rules.Remove(filter);
                result = this.GetOrderPageEntities<T_SK_CHECK_QUESTION>(t => t.CHECK_CONTENTS_ID == Guid.Parse(filter.Value.ToString()), pageFilter);
            }
            else
            {
                var resultTemp = this.GetEntities<T_SK_CHECK_QUESTION>(t => t.IS_DELETED == false, new BaseFilter(pageFilter.OrgId));
                var questionIds = resultTemp.Distinct(t => t.DESCREPTION).Select(m => m.ID).ToList();
                result = this.GetOrderPageEntities<T_SK_CHECK_QUESTION>(m => questionIds.Contains(m.ID), pageFilter);
            }
            return result;
        }
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost, Route("ImportUpdate")]
        public JsonActionResult<bool> ImportUpdate(IFormCollection files)
        {
            return SafeExecute<bool>(() =>
            {
                bool isOK = true;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织        
                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, 2);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;
                    isOK = InsertModel3(dataTables.Tables[0], orgId, ref Msg);

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

                return isOK;
            });
        }
        /// <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 = 1)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (rowAll == 1)
            {
                throw new Exception("导入必须两条以上，一条请直接新增");
            }
            List<T_SK_CHECK_CONTENTS> contents = new List<T_SK_CHECK_CONTENTS>();
            List<T_SK_CHECK_QUESTION> qustions = new List<T_SK_CHECK_QUESTION>();
            Guid? checkId = null;
            var baseFilter = new BaseFilter(orgId);
            var oldContents = this.GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, baseFilter, "Nav_ListCheckQuestion");
            for (int i = 0; i < rowAll; i++)
            {
                if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))
                {
                    var first = oldContents.FirstOrDefault(x => x.CHECKCONTENT == dtSource.Rows[i][0].ToString().Trim());
                    if (first != null)//旧表已存在数据
                    {
                        Msg = Msg + ("第" + (i + 2) + "行，检查内容已存在，请勿重复导入");
                    }
                    else//不存在
                    {
                        T_SK_CHECK_CONTENTS content = new T_SK_CHECK_CONTENTS();
                        content.ORG_ID = orgId;
                        content.CHECKCONTENT = dtSource.Rows[i][0].ToString().Trim();
                        checkId = content.ID;
                        contents.Add(content);
                    }
                    var items = new List<string>();
                    var scores = new List<string>();
                    var methods = new List<string>();
                    var itemLists = dtSource.Rows[i][1].ToString().Trim().Split("。").ToList();
                    var scoreLists = dtSource.Rows[i][2].ToString().Trim().Split("。").ToList();
                    var methodLists = dtSource.Rows[i][3].ToString().Trim().Split("。").ToList();
                    foreach (var ite in itemLists)
                    {
                        if (!string.IsNullOrEmpty(ite))
                            items.Add(ite);
                    }
                    foreach (var ite in scoreLists)
                    {
                        if (!string.IsNullOrEmpty(ite))
                            scores.Add(ite);
                    }
                    foreach (var ite in methodLists)
                    {
                        if (!string.IsNullOrEmpty(ite))
                            methods.Add(ite);
                    }
                    if (items.Count != scores.Count || items.Count != methods.Count)
                        Msg= Msg+("第" + (i + 2) + "行，隐患描述与隐患等级与整改措施不匹配");
                    else
                    {
                        if (items != null && items.Any())
                        {
                            var NO = 1;
                            foreach (var item in items)
                            {
                                T_SK_CHECK_QUESTION question = new T_SK_CHECK_QUESTION();
                                question.CHECK_CONTENTS_ID = checkId;
                                question.ORG_ID = orgId;
                                var itemArr = item.Split("、");
                                if (itemArr.Length != 2)
                                {
                                    question.NUM = NO;
                                    question.DESCREPTION = item.ToString();
                                }
                                else
                                {
                                    question.NUM = int.Parse(itemArr[0]);
                                    question.DESCREPTION = itemArr[1].ToString();
                                }
                                qustions.Add(question);
                                NO++;
                            }
                        }
                        if (scores != null && scores.Any())
                        {
                            var NO = 1;
                            foreach (var item in scores)
                            {
                                var itemArr = item.Split("、");
                                if (itemArr.Length != 2)
                                {
                                    var question = qustions.FirstOrDefault(t => t.CHECK_CONTENTS_ID == checkId && t.NUM == NO);
                                    if (question != null)
                                    {
                                        question.QUESTION_LEVEL = item == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                                    }
                                    else
                                        Msg= Msg+("隐患对应序号的层级未填写");
                                }
                                else
                                {
                                    var question = qustions.FirstOrDefault(t => t.CHECK_CONTENTS_ID == checkId && t.NUM == int.Parse(itemArr[0]));
                                    if (question != null)
                                        question.QUESTION_LEVEL = itemArr[1] == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                                    else
                                        Msg= Msg+("隐患对应序号的层级未填写");
                                }
                                NO++;
                            }
                        }
                        if (methods != null && methods.Any())
                        {
                            var NO = 1;
                            foreach (var item in methods)
                            {
                                var itemArr = item.Split("、");
                                if (itemArr.Length != 2)
                                {
                                    var question = qustions.FirstOrDefault(t => t.CHECK_CONTENTS_ID == checkId && t.NUM == NO);
                                    if (question != null)
                                        question.DEMAND = item;
                                    else
                                        Msg= Msg+("隐患对应序号的整改措施未填写");
                                }
                                else
                                {
                                    var question = qustions.FirstOrDefault(t => t.CHECK_CONTENTS_ID == checkId && t.NUM == int.Parse(itemArr[0]));
                                    if (question != null)
                                        question.DEMAND = itemArr[1];
                                    else
                                        Msg= Msg+("隐患对应序号的整改措施未填写");
                                }
                                NO++;
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            else
            {
                UnifiedCommit(() =>
                {
                    if (contents != null && contents.Any())
                        BantchSaveEntityNoCommit(contents);
                    if (qustions != null && qustions.Any())
                        BantchSaveEntityNoCommit(qustions);
                });
                Msg = "导入成功！";
            }
            return true;
        }

        /// <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 InsertModel2(DataTable dtSource, Guid? orgId, ref string Msg, int rowIndex = 1)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (rowAll == 1)
            {
                throw new Exception("导入必须两条以上，一条请直接新增");
            }
            List<T_SK_CHECK_CONTENTS> contents = new List<T_SK_CHECK_CONTENTS>();
            List<T_SK_CHECK_QUESTION> qustions = new List<T_SK_CHECK_QUESTION>();
            List<T_SK_CHECK_CONTENTS_BASIC> basics = new List<T_SK_CHECK_CONTENTS_BASIC>();
            List<T_SK_CHECK_QUESTION> qustionTemps = new List<T_SK_CHECK_QUESTION>();
            var baseFilter = new BaseFilter(orgId);
            var lawList = this.GetEntities<T_LR_LAW>(i => i.IS_DELETED == false, baseFilter);
            var productionUnits = this.GetEntities<T_FM_USER_PRODUCTION_UNIT_SET>(i => i.IS_DELETED == false, baseFilter);
            var oldContents = this.GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, baseFilter);
            var oldHiddens = this.GetEntities<T_SK_CHECK_QUESTION>(i => i.IS_DELETED == false, baseFilter);
            var oldbass = this.GetEntities<T_SK_CHECK_CONTENTS_BASIC>(i => i.IS_DELETED == false, baseFilter);
            for (int i = 0; i < rowAll; i++)
            {
                if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))
                {
                        var unit = productionUnits.FirstOrDefault(t => t.NAME == dtSource.Rows[i][0].ToString().Trim());
                        var first = oldContents.FirstOrDefault(x =>x.PRODUCTION_UNIT_ID == unit?.ID && x.CHECKCONTENT == dtSource.Rows[i][1].ToString().Trim());
                        if (first != null)//旧表已存在数据
                        {
                            Msg = Msg + "检查内容：" + dtSource.Rows[i][1].ToString().Trim() + "已存在,请直接到系统配置修改；";
                        //T_SK_CHECK_QUESTION content = new T_SK_CHECK_QUESTION();
                        //content.ORG_ID = orgId;
                        //content.CHECKCONTENT = dtSource.Rows[i][1].ToString().Trim();
                        //content.CHECK_BASICS = dtSource.Rows[i][2].ToString().Trim();
                        //content.CHECK_STANDARD = dtSource.Rows[i][3].ToString().Trim();
                        //content.DESCREPTION = dtSource.Rows[i][4].ToString().Trim();
                        //content.QUESTION_LEVEL_SHOW = dtSource.Rows[i][5].ToString().Trim();
                        //content.QUESTION_LEVEL = content.QUESTION_LEVEL_SHOW == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                        //content.DEMAND = dtSource.Rows[i][6].ToString().Trim();
                        //content.PRODUCTION_UNIT_ID = unit?.ID;
                        //content.CHECK_CONTENTS_ID = first.ID;
                        //qustionTemps.Add(content);
                        //first.CHECK_STANDARD = content.CHECK_STANDARD;
                        //contents.Add(first);
                    }
                        else
                        {
                            T_SK_CHECK_QUESTION content = new T_SK_CHECK_QUESTION();
                            content.ORG_ID = orgId;
                            content.CHECKCONTENT = dtSource.Rows[i][1].ToString().Trim();
                            content.CHECK_BASICS = dtSource.Rows[i][2].ToString().Trim();
                            content.CHECK_STANDARD = dtSource.Rows[i][3].ToString().Trim();
                            content.DESCREPTION = dtSource.Rows[i][4].ToString().Trim();
                            content.QUESTION_LEVEL_SHOW = dtSource.Rows[i][5].ToString().Trim();
                            content.QUESTION_LEVEL = content.QUESTION_LEVEL_SHOW == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                            content.DEMAND = dtSource.Rows[i][6].ToString().Trim();
                            content.PRODUCTION_UNIT_ID = unit?.ID;
                            qustionTemps.Add(content);
                        }
                }
            }
            if (qustionTemps != null && qustionTemps.Any())
            {
                //已有检查内容，隐患描述直接加
                //var contentList2 = qustionTemps.Where(m => m.CHECK_CONTENTS_ID != null).GroupBy(t => new { t.CHECK_CONTENTS_ID, t.PRODUCTION_UNIT_ID, t.CHECKCONTENT }).Distinct().ToList();
                //if (contentList2 != null && contentList2.Any())
                //{
                //    foreach (var item in contentList2)
                //    {
                //        var qus = qustionTemps.Where(t => t.CHECK_CONTENTS_ID == item.Key.CHECK_CONTENTS_ID && t.PRODUCTION_UNIT_ID == item.Key.PRODUCTION_UNIT_ID && t.CHECKCONTENT == item.Key.CHECKCONTENT).ToList();
                //        var j = 1;
                //        foreach (var que in qus)
                //        {
                //            var quFirst = oldHiddens.FirstOrDefault(t =>t.CHECK_CONTENTS_ID== item.Key.CHECK_CONTENTS_ID &&  t.DESCREPTION == que.DESCREPTION &&  t.DEMAND == que.DEMAND && t.QUESTION_LEVEL == que.QUESTION_LEVEL);
                //            if (quFirst == null)
                //            {
                //                T_SK_CHECK_QUESTION qu = new T_SK_CHECK_QUESTION();
                //                qu.CHECK_CONTENTS_ID = item.Key.CHECK_CONTENTS_ID;
                //                qu.ORG_ID = orgId;
                //                qu.DESCREPTION = que.DESCREPTION;
                //                qu.DEMAND = que.DEMAND;
                //                qu.QUESTION_LEVEL = que.QUESTION_LEVEL;
                //                qu.NUM = j;
                //                qustions.Add(qu);
                //                j++;
                //            }
                //            if (!string.IsNullOrEmpty(que.CHECK_BASICS))
                //            { 
                //                var laws=que.CHECK_BASICS.Split("；").ToList();
                //                foreach (var law in laws)
                //                {
                //                    var lawFirst = lawList.FirstOrDefault(t => t.NAME == law);
                //                    if (!string.IsNullOrEmpty(law))
                //                    {
                //                        if (lawFirst != null)
                //                        {
                //                            var laFirst = oldbass.FirstOrDefault(t => t.CHECK_CONTENTS_ID == item.Key.CHECK_CONTENTS_ID && t.LAW_ID == lawFirst.ID);
                //                            if (laFirst == null)
                //                            {
                //                                T_SK_CHECK_CONTENTS_BASIC bas = new T_SK_CHECK_CONTENTS_BASIC();
                //                                bas.ORG_ID = orgId;
                //                                bas.LAW_ID = lawFirst.ID;
                //                                basics.Add(bas);
                //                            }  
                //                        }
                //                        else
                //                        {
                //                            Msg = Msg + "找不到检查依据：" + law + ",请先到法律法规库添加";
                //                        }
                //                    }
                //                }
                //            }
                //        }
                //    }
                //}
                //新增的检查内容
                var contentList = qustionTemps.Where(m=>m.CHECK_CONTENTS_ID==null).GroupBy(t => new { t.PRODUCTION_UNIT_ID, t.CHECKCONTENT }).Distinct().ToList();
                if (contentList != null && contentList.Any())
                {
                    foreach (var item in contentList)
                    {
                        T_SK_CHECK_CONTENTS content = new T_SK_CHECK_CONTENTS();
                        content.ORG_ID = orgId;
                        content.PRODUCTION_UNIT_ID = item.Key.PRODUCTION_UNIT_ID;
                        content.CHECKCONTENT = item.Key.CHECKCONTENT;
                        content.CHECK_STANDARD = qustionTemps.FirstOrDefault(t => t.PRODUCTION_UNIT_ID == item.Key.PRODUCTION_UNIT_ID && t.CHECKCONTENT == item.Key.CHECKCONTENT)?.CHECK_STANDARD;
                        contents.Add(content);
                        var qus = qustionTemps.Where(t => t.PRODUCTION_UNIT_ID == item.Key.PRODUCTION_UNIT_ID && t.CHECKCONTENT == item.Key.CHECKCONTENT).ToList();
                        var j = 1;
                        foreach (var que in qus)
                        {
                            T_SK_CHECK_QUESTION qu = new T_SK_CHECK_QUESTION();
                            qu.CHECK_CONTENTS_ID = content.ID;
                            qu.ORG_ID = orgId;
                            qu.DESCREPTION = que.DESCREPTION;
                            qu.DEMAND = que.DEMAND;
                            qu.QUESTION_LEVEL = que.QUESTION_LEVEL;
                            qu.NUM = j;
                            qustions.Add(qu);
                            j++;
                            if (!string.IsNullOrEmpty(que.CHECK_BASICS))
                            {
                                var laws = que.CHECK_BASICS.Split("；").ToList();
                                foreach (var law in laws)
                                {
                                    var lawFirst = lawList.FirstOrDefault(t => t.NAME == law);
                                    if (!string.IsNullOrEmpty(law))
                                    {
                                        if (lawFirst != null)
                                        {
                                            T_SK_CHECK_CONTENTS_BASIC bas = new T_SK_CHECK_CONTENTS_BASIC();
                                            bas.ORG_ID = orgId;
                                            bas.LAW_ID = lawFirst.ID;
                                            basics.Add(bas);
                                        }
                                        else
                                        {
                                            Msg = Msg + "找不到检查依据：" + law + ",请先到法律法规库添加；";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            else
            {
                UnifiedCommit(() =>
                {
                    if (contents != null && contents.Any())
                        BantchSaveEntityNoCommit(contents);
                    if (qustions != null && qustions.Any())
                        BantchSaveEntityNoCommit(qustions);
                });
                Msg = "导入成功！";
            }
            return true;
        }
        /// <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 InsertModel3(DataTable dtSource, Guid? orgId, ref string Msg, int rowIndex = 1)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (rowAll == 1)
            {
                throw new Exception("导入必须两条以上，一条请直接新增");
            }
            List<T_SK_CHECK_CONTENTS> contents = new List<T_SK_CHECK_CONTENTS>();
            List<T_SK_CHECK_QUESTION> qustions = new List<T_SK_CHECK_QUESTION>();
            List<T_SK_CHECK_CONTENTS_BASIC> basics = new List<T_SK_CHECK_CONTENTS_BASIC>();
            List<T_SK_CHECK_QUESTION> qustionTemps = new List<T_SK_CHECK_QUESTION>();
            var baseFilter = new BaseFilter(orgId);
            var productionUnits = this.GetEntities<T_FM_USER_PRODUCTION_UNIT_SET>(i => i.IS_DELETED == false, baseFilter);
            var oldContents = this.GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, baseFilter);
            var oldLaws = this.GetEntities<T_LR_LAW>(i => i.IS_DELETED == false, baseFilter);
            
            for (int i = 0; i < rowAll; i++)
            {
                if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))
                {
                    var unit = productionUnits.FirstOrDefault(t => t.NAME == dtSource.Rows[i][0].ToString().Trim());
                    if (unit == null)//旧表已存在数据
                    {
                        Msg = Msg +"第" + (i + 3) + "行生产单元：" + dtSource.Rows[i][0].ToString().Trim() + "不存在,请先到系统管理添加；";

                    }
                }
                else
                {
                    Msg = Msg + "第" + (i + 3) + "行生产单元不能为空；";
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][1].ToString().Trim()))
                {
                    if (!dtSource.Rows[i][1].ToString().Trim().EndsWith("？"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行检查内容" + dtSource.Rows[i][1].ToString().Trim() + "格式不正确，必须以中文问号结尾 ；";
                    }
                    else
                    {
                        var conFirst = oldContents.FirstOrDefault(t => t.CHECKCONTENT == dtSource.Rows[i][1].ToString().Trim());
                        if (conFirst != null)
                        {
                            Msg = Msg + "第" + (i + 3) + "行检查内容" + dtSource.Rows[i][1].ToString().Trim() + "已存在，请勿重复导入；";
                        }
                    }
                    string content = dtSource.Rows[i][1].ToString().Trim()[0..^1];
                    if (content.Contains("？"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行检查内容" + dtSource.Rows[i][1].ToString().Trim() + "格式不正确，内容中间不能有问号 ；";
                    }
                }
                else
                {
                    Msg = Msg + "第" + (i + 3) + "行检查内容不能为空；";
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][2].ToString().Trim()))
                {
                    var lists = dtSource.Rows[i][2].ToString().Trim().Split("；").ToList();
                    if (lists != null && lists.Any())
                    {
                        foreach (var item in lists)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                var conFirst = oldLaws.FirstOrDefault(t => t.NAME == item);
                                if (conFirst == null)
                                {
                                    Msg = Msg + "第" + (i + 3) + "行检查依据" + item + "不存在，请先到知识库法律法规库维护；";
                                }
                            }
                        }
                    }
                }
                var hiddenDes = dtSource.Rows[i][4].ToString().Trim();
                if (!string.IsNullOrEmpty(hiddenDes))
                {
                    if (!hiddenDes.Contains("。"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行隐患描述格式不正确：1*内容。";
                    }
                    if (!hiddenDes.Contains("*"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行隐患描述格式不正确：1*内容。";
                    }
                    var lists = hiddenDes.Split("。").ToList();
                    if (lists != null && lists.Any())
                    {
                        foreach (var item in lists)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                if (!item.Contains("*"))
                                {
                                    Msg = Msg + "第" + (i + 3) + "行隐患描述格式不正确：1*内容。";
                                }
                            }
                        }
                    }
                }
                var hiddenLevel = dtSource.Rows[i][5].ToString().Trim();
                if (!string.IsNullOrEmpty(hiddenLevel))
                {
                    if (!hiddenLevel.Contains("。"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行隐患等级格式不正确：1*内容。";
                    }
                    if (!hiddenLevel.Contains("*"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行隐患等级格式不正确：1*内容。";
                    }
                    var lists = hiddenLevel.Split("。").ToList();
                    if (lists != null && lists.Any())
                    {
                        foreach (var item in lists)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                if (!item.Contains("*"))
                                {
                                    Msg = Msg + "第" + (i + 3) + "行隐患等级格式不正确：1*内容。";
                                }
                                else
                                {
                                    if (item.Split('*')[1].ToString() != "一般" && item.Split('*')[1].ToString() != "重大")
                                    {
                                        Msg = Msg + "第" + (i + 3) + "行隐患等级只能填写一般或重大";
                                    }
                                }
                            }
                        }
                    }
                }
                var hiddenMes = dtSource.Rows[i][6].ToString().Trim();
                if (!string.IsNullOrEmpty(hiddenMes))
                {
                    if (!hiddenMes.Contains("。"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行整改措施格式不正确：1*内容。";
                    }
                    if (!hiddenMes.Contains("*"))
                    {
                        Msg = Msg + "第" + (i + 3) + "行整改措施格式不正确：1*内容。";
                    }
                    var lists = hiddenMes.Split("。").ToList();
                    if (lists != null && lists.Any())
                    {
                        foreach (var item in lists)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                if (!item.Contains("*"))
                                {
                                    Msg = Msg + "第" + (i + 3) + "行整改措施格式不正确：1*内容。";
                                }
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            for (int i = 0; i < rowAll; i++)
            {
                var unit = productionUnits.FirstOrDefault(t => t.NAME == dtSource.Rows[i][0].ToString().Trim());
                T_SK_CHECK_QUESTION content = new T_SK_CHECK_QUESTION();
                content.ORG_ID = orgId;
                content.CHECKCONTENT = dtSource.Rows[i][1].ToString().Replace("\n", "").Trim();
                content.CHECK_BASICS = dtSource.Rows[i][2].ToString().Replace("\n", "").Trim();
                content.CHECK_STANDARD = dtSource.Rows[i][3].ToString().Replace("\n", "").Trim();
                content.DESCREPTION = dtSource.Rows[i][4].ToString().Replace("\n", "").Trim();
                content.QUESTION_LEVEL_SHOW = dtSource.Rows[i][5].ToString().Replace("\n", "").Trim();
                content.DEMAND = dtSource.Rows[i][6].ToString().Replace("\n", "").Trim();
                content.PRODUCTION_UNIT_ID = unit?.ID;
                qustionTemps.Add(content);
            }
            if (qustionTemps != null && qustionTemps.Any())
            {
                foreach (var item in qustionTemps)
                {
                    T_SK_CHECK_CONTENTS content = new T_SK_CHECK_CONTENTS();
                    content.ORG_ID = orgId;
                    content.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                    content.CHECKCONTENT = item.CHECKCONTENT;
                    content.CHECK_STANDARD = item.CHECK_STANDARD;
                    contents.Add(content);
                    if (!string.IsNullOrEmpty(item.DESCREPTION) && !string.IsNullOrEmpty(item.DEMAND))
                    {
                        var ques = item.DESCREPTION.Split("。").ToList();
                        var levels = item.QUESTION_LEVEL_SHOW.Split("。").ToList();
                        var mess = item.DEMAND.Split("。").ToList();
                        if (ques != null && ques.Any())
                        {
                            foreach (var que in ques)
                            {
                                if (!string.IsNullOrEmpty(que))
                                {
                                    var quNum = que.Split("*")[0];
                                    var mes = mess.FirstOrDefault(t => t.StartsWith(quNum));
                                    var level = levels.FirstOrDefault(t => t.StartsWith(quNum));
                                    T_SK_CHECK_QUESTION qu = new T_SK_CHECK_QUESTION();
                                    qu.CHECK_CONTENTS_ID = content.ID;
                                    qu.ORG_ID = orgId;
                                    qu.DESCREPTION = que.Split('*')[1].ToString()+"。";
                                    qu.DEMAND = mes.Split("*")[1].ToString() + "。";
                                    qu.QUESTION_LEVEL = level != null && level.Split("*")[1].ToString() == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                                    qu.NUM = int.Parse(que.Split('*')[0].ToString());
                                    qustions.Add(qu);
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(item.CHECK_BASICS))
                    {
                        var lists = item.CHECK_BASICS.Split("；").ToList();
                        if (lists != null && lists.Any())
                        {
                            foreach (var bas in lists)
                            {
                                if (!string.IsNullOrEmpty(bas))
                                {
                                    var basFirst = oldLaws.FirstOrDefault(t => t.NAME == bas);
                                    T_SK_CHECK_CONTENTS_BASIC post = new T_SK_CHECK_CONTENTS_BASIC();
                                    post.ORG_ID = orgId;
                                    post.CHECK_CONTENTS_ID = content.ID;
                                    post.LAW_ID = basFirst.ID;
                                    basics.Add(post);
                                }
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            else
            {
                UnifiedCommit(() =>
                {
                    if (contents != null && contents.Any())
                        BantchSaveEntityNoCommit(contents);
                    if (qustions != null && qustions.Any())
                        BantchSaveEntityNoCommit(qustions);
                    if (basics != null && basics.Any())
                        BantchSaveEntityNoCommit(basics);
                });
                Msg = "导入成功！";
            }
            return true;
        }
    }
}
