using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.ApiModel;
using System.Data;
using System.IO;
using APT.BaseData.Domain.Entities.FM;
using Castle.Core.Internal;
using static APT.SC.WebApi.Controllers.Api.BI.BIController;
using Microsoft.AspNetCore.DataProtection;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices.OP;
using APT.Migrations;
using System.Linq.Expressions;

namespace APT.SE.WebApi.Controllers.Api
{
    [Route("api/SE/SETest")]
    public partial class SETestController : AuthorizeApiController<T_SE_TEST>
    {
        IOPTenantDBConnService OPTenantDBConnService { get; set; }
        public SETestController(IOPTenantDBConnService opTenantDBConnService)
        {
            OPTenantDBConnService = opTenantDBConnService;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_SE_TEST> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            string TRAINNAME = null;//培训名称
            string NAME = null;//题目
            SETestTypeEnum? TYPE = null;//题型
            string PointNAME = null;//知识点
            Guid? POINT_ID = null;//知识点
            string POST_NAME = null;

            List<int> listUsAge = null;

            if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Count() > 0)
            {
                foreach (var item in pageFilter.FilterGroup.Rules)
                {
                    switch (item.Field)
                    {
                        case "TRAINNAME":
                            TRAINNAME = item.Value.ToString();
                            break;
                        case "USAGE"://1,2,4
                            if (item.Value.ToString() == "1")
                            {
                                listUsAge = new List<int>() { 1, 3, 5, 7 };
                            }
                            else if (item.Value.ToString() == "2")
                            {
                                listUsAge = new List<int>() { 2, 3, 6, 7 };
                            }
                            else if (item.Value.ToString() == "4")
                            {
                                listUsAge = new List<int>() { 4, 5, 6, 7 };
                            }
                            break;
                        case "NAME":
                            NAME = item.Value.ToString();
                            break;
                        case "TYPE":
                            TYPE = (SETestTypeEnum)int.Parse(item.Value.ToString());
                            break;
                        case "Nav_Points.Nav_Point.NAME":
                            PointNAME = item.Value.ToString();
                            break;
                        case "Nav_Posts.Nav_Post.NAME":
                            POST_NAME = item.Value.ToString();
                            break;
                        default:
                            break;
                    }
                }
                //if (POINT_ID != null)
                //{
                //    pageFilter.FilterGroup.Groups = new List<FilterGroup>();
                //}
                //pageFilter.FilterGroup.Rules = new List<FilterRule>();
            }
            if (pageFilter.FilterGroup.Groups != null && pageFilter.FilterGroup.Groups.Any())
            {
                foreach (var item in pageFilter.FilterGroup.Groups)
                {
                    if (item.Rules.Any())
                    {
                        foreach (var itemG in item.Rules)
                        {
                            if (itemG.Field == "Nav_Points.POINT_ID")
                            {
                                POINT_ID = new Guid(itemG.Value.ToString());
                                break;
                            }
                        }
                    }
                }
            }
            pageFilter.FilterGroup = new FilterGroup();

            //string POST_NAME = "";
            //string POINT_NAME = "";
            //if (pageFilter.Parameter1 != null)
            //{
            //    POST_NAME = (string)pageFilter.Parameter1;
            //}
            //if (pageFilter.Parameter2 != null)
            //{
            //    POINT_NAME = (string)pageFilter.Parameter2;
            //}
            PagedActionResult<T_SE_TEST> ret = WitOrderPaged(t => (POST_NAME == null ||
            (t.Nav_Posts.Any(it => it.Nav_Post.NAME.Contains(POST_NAME)))) &&
            (PointNAME == null ||
            (t.Nav_Points.Any(it => it.Nav_Point.NAME.Contains(PointNAME)))) &&
            (POINT_ID == null ||
            (t.Nav_Points.Any(it => it.POINT_ID.HasValue && it.POINT_ID.Value == POINT_ID))) && (
            TRAINNAME == null || t.TRAINNAME.Contains(TRAINNAME)) && (NAME == null || t.NAME.Contains(NAME)) && (TYPE == null || t.TYPE == TYPE) && (listUsAge == null || listUsAge.Contains(t.USAGE))
            , pageFilter);
            if (ret == null || ret.Data == null || ret.Data.Count() < 1)
            {
                ret.Data = new List<T_SE_TEST>();
                return ret;
            }
            var ids = ret.Data.Select(t => t.ID);
            BaseFilter filter = new BaseFilter(pageFilter.GetOrgId());
            filter.Include = new string[] { "Nav_Point" };
            var points = GetEntities<T_SE_TEST_LIST_POINT>(t => ids.Contains(t.TEST_ID), filter);
            foreach (var item in ret.Data)
            {
                var point = points.Where(t => t.TEST_ID == item.ID).Select(t => t.Nav_Point.NAME);
                var pointName = string.Join("，", point);
                item.OPTION_A = pointName;
            }
            return ret;
        }
        public class notifyName
        {

            public string NAME { get; set; }
        }
        /// <summary>
        /// 查询培训名称
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("getNotifyNames")]
        public JsonActionResult<List<notifyName>> getNotifyNames([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeExecute<List<notifyName>>(() =>
            {
                BaseFilter filter = new BaseFilter(pageFilter.GetOrgId());
                filter.SelectField = new string[] { "NAME" };
                DataOrder order1 = new DataOrder();
                order1.Field = "NAME";
                order1.Order = DbOrder.ASC;
                filter.Orders.Add(order1);
                var notifys = GetEntities<T_SE_TRAIN_NOTIFY>(t => t.IS_DELETED == false, filter).DistinctBy(t => t.NAME);
                List<notifyName> ret = new List<notifyName>();
                foreach (var notify in notifys)
                {
                    notifyName notifyName = new notifyName();
                    notifyName.NAME = notify.NAME;
                    ret.Add(notifyName);
                }
                ret = ret.OrderBy(t => t.NAME).ToList();
                return ret;
            });
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_TEST entity)
        {
            return SafeExecute(() =>
            {
                if (entity.ID == null || entity.ID == Guid.Empty)
                {
                    entity.ID = Guid.NewGuid();
                }
                if (string.IsNullOrEmpty(entity.NAME))
                {
                    throw new Exception("题目不可为空");
                }
                if (entity.TYPE is SETestTypeEnum.单选题 or SETestTypeEnum.多选题)
                {
                    if ((entity.ANSWER) == 0)
                    {
                        throw new Exception("答案不可为空");
                    }
                    if (string.IsNullOrEmpty(entity.OPTION_A) ||
                        string.IsNullOrEmpty(entity.OPTION_B) ||
                        string.IsNullOrEmpty(entity.OPTION_C) ||
                        string.IsNullOrEmpty(entity.OPTION_D)
                        )
                    {
                        throw new Exception("选择题选项不可为空");
                    }
                    if (entity.TYPE == SETestTypeEnum.单选题 &&
                        entity.ANSWER != 1 && entity.ANSWER != 2 && entity.ANSWER != 4 && entity.ANSWER != 8 && entity.ANSWER != 16)
                    {
                        throw new Exception("单选题只能有一个正确选项");
                    }
                    if (entity.TYPE == SETestTypeEnum.多选题 && (entity.ANSWER < 3 || entity.ANSWER == 4 || entity.ANSWER == 8 || entity.ANSWER == 16))
                    {
                        throw new Exception("多选题至少有两个正确选项");
                    }
                }
                if (entity.TYPE == SETestTypeEnum.是非题)
                {
                    if (entity.ANSWER != 1 && entity.ANSWER != 2)
                    {
                        throw new Exception("是非题答案只能为是或否");
                    }
                }
                var points = entity.Nav_Points;
                entity.Nav_Points = null;
                if (points == null || points.Count == 0)
                {
                    throw new Exception("知识点不可为空");
                }
                points.ForEach(t =>
                {
                    t.ORG_ID = entity.ORG_ID;
                    t.TEST_ID = entity.ID;
                });

                var posts = entity.Nav_Posts;
                entity.Nav_Posts = null;
                if (posts != null)
                {
                    posts.ForEach(t =>
                    {
                        t.TEST_ID = entity.ID;
                        t.ORG_ID = entity.ORG_ID;
                    });
                }
                this.UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (posts != null)
                        BantchSaveEntityNoCommit(posts);
                    if (points != null)
                        BantchSaveEntityNoCommit(points);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                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, 1);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;

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

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

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

                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 = 1)
        {
            //适用岗位去除 列：9 
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            List<int> listNotEmpty = new List<int>() { 0, 1, 7, 8, 9 };// 10 =>9
            Dictionary<int, List<int>> dicIndexEmpty = new Dictionary<int, List<int>>();
            int rowAll = dtSource.Rows.Count;
            int colAll = dtSource.Columns.Count;
            List<T_SE_TEST> mainTables = new List<T_SE_TEST>();
            List<T_SE_TEST_LIST_POST> sub1s = new List<T_SE_TEST_LIST_POST>();
            List<T_SE_TEST_LIST_POINT> sub2s = new List<T_SE_TEST_LIST_POINT>();

            var posts = GetEntities<T_FM_USER_POST>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            var points = GetEntities<T_SE_TEST_ENUM_POINT>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            T_FM_USER_POST modelPost = null;
            List<string> listPostNameEmpty = new List<string>();

            List<string> listAnswerNullIndex = new List<string>();//未获取到答案

            List<string> listAnswerErrorIndex = new List<string>();
            List<string> listAnswerError = new List<string>();
            string strANSWER = string.Empty;
            T_SE_TEST_ENUM_POINT modelPoint = null;
            List<string> listPointNameEmpty = new List<string>();
            DateTime dtNow = DateTime.Now;

            //数据库现有题目 去重判断
            List<T_SE_TEST> listDataAllCheck = GetEntities<T_SE_TEST>(e => !e.IS_DELETED, null, null).ToList();
            T_SE_TEST check = null;
            List<string> listRepeatDataIndex = new List<string>();
            List<string> listNameTypeError = new List<string>();
            List<string> listRepeatExcelIndex = new List<string>();
            List<string> listNameTypeEError = new List<string>();

            for (int i = 0; i < rowAll; i++)
            {
                #region    不能为空

                List<int> listi = null;
                for (int j = 0; j < colAll; 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);
                    }
                }
                if (listi != null)
                    dicIndexEmpty.Add(i + rowIndex, listi);//有空的 直接添加

                #endregion
                if (dicIndexEmpty.Count < 1)
                {
                    T_SE_TEST mainTable = new T_SE_TEST();
                    mainTable.ID = Guid.NewGuid();
                    mainTable.ORG_ID = orgId;
                    var testName = dtSource.Rows[i][0].ToString().Trim();
                    if (!string.IsNullOrEmpty(testName))
                    {
                        mainTable.NAME = testName;
                    }
                    else
                    {
                        continue;
                    }
                    var testType = dtSource.Rows[i][1].ToString().Trim();
                    if (!string.IsNullOrEmpty(testType))
                    {
                        if (testType == "是非题")
                        {
                            mainTable.TYPE = SETestTypeEnum.是非题;
                        }
                        else if (testType == "单选题")
                        {
                            mainTable.TYPE = SETestTypeEnum.单选题;
                        }
                        else if (testType == "多选题")
                        {
                            mainTable.TYPE = SETestTypeEnum.多选题;
                        }
                        else
                        {
                            throw new Exception("没有《" + testType + "》类型");
                        }
                    }
                    else
                    {
                        throw new Exception("题型不能为空!");
                    }


                    check = listDataAllCheck.FirstOrDefault(e => e.NAME == mainTable.NAME && e.TYPE == mainTable.TYPE);
                    if (check != null)
                    {
                        listRepeatDataIndex.Add((i + 1 + rowIndex).ToString());
                        listNameTypeError.Add(mainTable.NAME + "" + testType);
                    }
                    check = mainTables.FirstOrDefault(e => e.NAME == mainTable.NAME && e.TYPE == mainTable.TYPE);
                    if (check != null)
                    {
                        listRepeatExcelIndex.Add((i + 1 + rowIndex).ToString());
                        listNameTypeEError.Add(mainTable.NAME + "" + testType);
                    }

                    if (!string.IsNullOrEmpty(dtSource.Rows[i][2].ToString().Trim()))
                    {
                        mainTable.OPTION_A = (dtSource.Rows[i][2].ToString().Trim());
                    }
                    if (!string.IsNullOrEmpty(dtSource.Rows[i][3].ToString().Trim()))
                    {
                        mainTable.OPTION_B = (dtSource.Rows[i][3].ToString().Trim());
                    }
                    if (!string.IsNullOrEmpty(dtSource.Rows[i][4].ToString().Trim()))
                    {
                        mainTable.OPTION_C = (dtSource.Rows[i][4].ToString().Trim());
                    }
                    if (!string.IsNullOrEmpty(dtSource.Rows[i][5].ToString().Trim()))
                    {
                        mainTable.OPTION_D = (dtSource.Rows[i][5].ToString().Trim());
                    }
                    if (!string.IsNullOrEmpty(dtSource.Rows[i][6].ToString().Trim()))
                    {
                        mainTable.OPTION_E = (dtSource.Rows[i][6].ToString().Trim());
                    }
                    strANSWER = dtSource.Rows[i][7].ToString().Trim();
                    if (!string.IsNullOrEmpty(strANSWER))
                    {
                        if (mainTable.TYPE == SETestTypeEnum.是非题)
                        {
                            if (strANSWER == "A" || strANSWER == "是" || strANSWER == "a")
                            {
                                mainTable.ANSWER = 1;
                            }
                            else if (strANSWER == "B" || strANSWER == "否" || strANSWER == "b")
                            {
                                mainTable.ANSWER = 2;
                            }
                            else
                            {
                                if (!listAnswerError.Contains(strANSWER))
                                {
                                    listAnswerError.Add(strANSWER);
                                }
                                listAnswerErrorIndex.Add((i + rowIndex).ToString());
                            }
                        }
                        else if (mainTable.TYPE == SETestTypeEnum.单选题)
                        {
                            if (strANSWER == "A")
                            {
                                mainTable.ANSWER = 1;
                            }
                            else if (strANSWER == "B")
                            {
                                mainTable.ANSWER = 2;
                            }
                            else if (strANSWER == "C")
                            {
                                mainTable.ANSWER = 4;
                            }
                            else if (strANSWER == "D")
                            {
                                mainTable.ANSWER = 8;
                            }
                            else
                            {
                                if (listAnswerError.Contains(strANSWER))
                                {
                                    listAnswerError.Add(strANSWER);
                                }
                                listAnswerErrorIndex.Add((i + rowIndex).ToString());
                            }
                        }
                        else if (mainTable.TYPE == SETestTypeEnum.多选题)
                        {
                            int answer = 0;
                            if (strANSWER.Contains("A"))
                            {
                                answer = answer + 1;
                            }
                            if (strANSWER.Contains("B"))
                            {
                                answer = answer + 2;
                            }
                            if (strANSWER.Contains("C"))
                            {
                                answer = answer + 4;
                            }
                            if (strANSWER.Contains("D"))
                            {
                                answer = answer + 8;
                            }
                            if (strANSWER.Contains("E"))
                            {
                                answer = answer + 16;
                            }
                            mainTable.ANSWER = answer;
                        }
                    }
                    else
                    {
                        if (listAnswerError.Contains(strANSWER))
                        {
                            listAnswerError.Add(strANSWER);
                        }
                        listAnswerErrorIndex.Add((i + rowIndex).ToString());
                    }

                    if (mainTable.ANSWER == 0)
                    {
                        listAnswerNullIndex.Add((i + rowIndex).ToString());
                    }
                    if (!string.IsNullOrEmpty(dtSource.Rows[i][8].ToString().Trim()))
                    {
                        int k = 0;
                        if (dtSource.Rows[i][8].ToString().Contains("安全意识调查"))
                        {
                            k = k + 1;
                        }
                        if (dtSource.Rows[i][8].ToString().Contains("培训"))
                        {
                            k = k + 2;
                        }
                        if (dtSource.Rows[i][8].ToString().Contains("事故事件"))
                        {
                            k = k + 4;
                        }
                        mainTable.USAGE = k;
                    }
                    //if (!string.IsNullOrEmpty(dtSource.Rows[i][9].ToString().Trim()))
                    //{
                    //    var testPosts = dtSource.Rows[i][9].ToString().Trim().Split(';');
                    //    foreach (var postName in testPosts)
                    //    {
                    //        if (!string.IsNullOrEmpty(postName))
                    //        {
                    //            modelPost = posts.FirstOrDefault(t => t.NAME == postName);
                    //            if (modelPost == null)
                    //            {
                    //                if (!listPostNameEmpty.Contains(postName))
                    //                    listPostNameEmpty.Add(postName);
                    //            }
                    //            else
                    //            {
                    //                T_SE_TEST_LIST_POST sub1 = new T_SE_TEST_LIST_POST
                    //                {
                    //                    ID = Guid.NewGuid(),
                    //                    ORG_ID = orgId,
                    //                    TEST_ID = mainTable.ID,
                    //                    POST_ID = posts.FirstOrDefault(t => t.NAME == postName).ID
                    //                };
                    //                sub1s.Add(sub1);
                    //            }
                    //        }
                    //    }
                    //}
                    if (!string.IsNullOrEmpty(dtSource.Rows[i][9].ToString().Trim()))
                    {
                        var testPoints = dtSource.Rows[i][9].ToString().Trim().Split(';');
                        foreach (var pointName in testPoints)
                        {
                            if (!string.IsNullOrEmpty(pointName))
                            {
                                modelPoint = points.FirstOrDefault(t => t.NAME == pointName);
                                if (modelPoint != null)
                                {
                                    T_SE_TEST_LIST_POINT sub2 = new T_SE_TEST_LIST_POINT
                                    {
                                        ID = Guid.NewGuid(),
                                        ORG_ID = orgId,
                                        TEST_ID = mainTable.ID,
                                        POINT_ID = modelPoint.ID,
                                    };
                                    sub2s.Add(sub2);
                                }
                                else
                                {
                                    if (!listPointNameEmpty.Contains(pointName))
                                        listPointNameEmpty.Add(pointName);
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(dtSource.Rows[i][10].ToString().Trim()))
                    {
                        mainTable.TRAINNAME = dtSource.Rows[i][10].ToString().Trim();
                    }
                    mainTables.Add(mainTable);
                }
            }

            #region   提示

            string strEmptyError = string.Empty;
            if (listPostNameEmpty.Count > 0 || dicIndexEmpty.Count > 0 || listPointNameEmpty.Count > 0 || listRepeatDataIndex.Count > 0 || listRepeatExcelIndex.Count > 0 || listAnswerErrorIndex.Count > 0 || listAnswerNullIndex.Count > 0)
            {
                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) + "不能为空！";
                }

                if (listPostNameEmpty.Count > 0)
                {
                    throw new Exception("岗位未找到：" + string.Join(",", listPostNameEmpty));
                }
                if (listPointNameEmpty.Count > 0)
                {
                    throw new Exception("知识点未找到：" + string.Join(",", listPointNameEmpty));
                }
                if (listAnswerErrorIndex.Count > 0)
                {
                    throw new Exception("答案有误，行：【" + string.Join(",", listAnswerErrorIndex) + "】值：" + string.Join(",", listAnswerError));
                }
                if (listAnswerNullIndex.Count > 0)
                {
                    throw new Exception("获取答案有误，行：【" + string.Join(",", listAnswerNullIndex) + "】");
                }
                if (listRepeatDataIndex.Count > 0)
                {
                    throw new Exception("与现有题库重复，行：【" + string.Join(",", listRepeatDataIndex) + "】值：" + string.Join(",", listNameTypeError));
                }
                if (listRepeatExcelIndex.Count > 0)
                {
                    throw new Exception("Excel中题目重复，行：【" + string.Join(",", listRepeatExcelIndex) + "】值：" + string.Join(",", listNameTypeEError));
                }
            }
            if (strEmptyError != string.Empty)
                throw new Exception(strEmptyError);

            #endregion

            UnifiedCommit(() =>
            {
                if (mainTables != null && mainTables.Any())
                    BantchAddEntityNoCommit(mainTables);
                if (sub1s != null && sub1s.Any())
                    BantchAddEntityNoCommit(sub1s);
                if (sub2s != null && sub2s.Any())
                    BantchAddEntityNoCommit(sub2s);
            });
            Msg = "导入成功！";
            return true;
        }


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedHead")]
        public PagedActionResult<T_SE_TEST> OrderPagedHead([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_SE_TEST> result)
            {
                string strConn = OPTenantDBConnService.GetConnByORGID(new Guid(FilePathHead.JY.GetDescription()));
                using (var context = new MigrationContext(strConn))
                {
                    Expression<Func<T_SE_TEST, bool>> expression = e => !e.IS_DELETED;
                    if (pageFilter.FilterGroup != null && pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Count() > 0)
                    {
                        foreach (var item in pageFilter.FilterGroup.Rules)
                        {
                            if (item.Field == "NAME")
                            {
                                expression = expression.And(e => e.NAME.Contains(item.Value.ToString()));
                            }
                            else if (item.Field == "TYPE" && item.Value != null)
                            {
                                try
                                {
                                    SETestTypeEnum TYPE = (SETestTypeEnum)Convert.ToInt32(item.Value.ToString());
                                    expression = expression.And(e => e.TYPE == TYPE);
                                }
                                catch { }
                            }
                        }
                    }
                    Dictionary<string, DbOrder> orders = new Dictionary<string, DbOrder>();
                    orders.Add("CREATE_TIME", DbOrder.DESC);
                    PagedResultDto<T_SE_TEST> data = context.GetOrderPageEntities(expression, orders, null, pageFilter.Limit, pageFilter.Start, "Nav_Points.Nav_Point");
                    result.TotalCount = data.TotalCount;
                    result.Data = data.Items;
                    foreach (var item in result.Data)
                    {
                        if (item.TYPE == SETestTypeEnum.是非题)
                        {
                            item.OPTION_A = "正确";
                            item.OPTION_B = "错误";
                        }
                        item.ANSWERSHOW = GetAnswerShow(item.ANSWER);
                        if (item.Nav_Points != null && item.Nav_Points.Count() > 0)
                        {
                            item.STRPOINT = string.Join(',', item.Nav_Points.Select(e => e.Nav_Point.NAME));
                        }
                        else
                        {
                            item.STRPOINT = "";
                        }
                    }
                }
            });
        }


        /// <summary>
        /// 位掩码 根据答案获取显示
        /// </summary>
        /// <param name="ANSWER"></param>
        /// <param name="maxOption"></param>
        /// <returns></returns>
        private string GetAnswerShow(int ANSWER, int maxOption = 32)
        {
            List<int> select = new List<int>();
            int value = 1;
            while (value <= ANSWER && value <= maxOption)
            {
                if ((ANSWER & value) != 0)
                {
                    select.Add(value);
                }
                value *= 2;
            }
            string answer = string.Join(",", select);
            return answer.Replace("1", "A").Replace("2", "B").Replace("4", "C").Replace("8", "D");
        }
        /// <summary>
        /// 集团法律法规同步到本地
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost, Route("SyncToLocal")]
        public JsonActionResult<bool> SyncToLocal([FromBody] SyscList list)
        {
            return SafeExecute<bool>(() =>
            {
                var listText = list.ListModel;
                if (listText == null || listText.Count < 1)
                {
                    throw new Exception("请选择题目后再提交！");
                }

                Guid? LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                Guid? OrgID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                DateTime dtNow = DateTime.Now.Date;

                List<T_SE_TEST_LIST_POINT> listPoint = new List<T_SE_TEST_LIST_POINT>();
                List<T_SE_TEST_ENUM_POINT> listPointEnum = new List<T_SE_TEST_ENUM_POINT>();

                IEnumerable<T_SE_TEST> listTestData = null;
                List<T_SE_TEST_LIST_POINT> listPointData = new List<T_SE_TEST_LIST_POINT>();
                List<T_SE_TEST_ENUM_POINT> listPointEnumData = new List<T_SE_TEST_ENUM_POINT>();

                List<T_SE_TEST> listTestSync = new List<T_SE_TEST>();
                List<T_SE_TEST_LIST_POINT> listPointSync = new List<T_SE_TEST_LIST_POINT>();
                List<T_SE_TEST_ENUM_POINT> listPointEnumSync = new List<T_SE_TEST_ENUM_POINT>();

                T_SE_TEST modelTestSync = null;
                T_SE_TEST_LIST_POINT modelPointSync = null;
                T_SE_TEST_ENUM_POINT modelPointEnumSync = null;

                #region     获取入参数据 和 获取 入参对应数据库数据

                foreach (var item in list.ListModel)
                    if (item.Nav_Points != null && item.Nav_Points.Count() > 0)
                        listPoint.AddRange(item.Nav_Points);

                if (listPoint != null && listPoint.Count > 0)
                {
                    foreach (var item in listPoint)
                    {
                        if (!item.POINT_ID.HasValue)
                            continue;
                        modelPointEnumSync = listPointEnum.FirstOrDefault(e => e.ID == item.POINT_ID.Value);
                        if (modelPointEnumSync == null)
                            listPointEnum.Add(item.Nav_Point);
                    }
                }

                var listTestID = listText.Select(e => e.ID);
                listTestData = GetEntities<T_SE_TEST>(e => listTestID.Contains(e.ID), null, "Nav_Points.Nav_Point");
                foreach (var item in listTestData)
                {
                    if (item.Nav_Points != null && item.Nav_Points.Count > 0)
                        listPointData.AddRange(item.Nav_Points);
                }
                if (listPointData != null && listPointData.Count > 0)
                    foreach (var item in listPointData)
                        listPointEnumData.Add(item.Nav_Point);

                #endregion


                #region    数据判断处理  

                foreach (var item in listText)
                {
                    modelTestSync = listTestData.FirstOrDefault(e => e.ID == item.ID);
                    if (modelTestSync == null)
                    {
                        item.CREATER_ID = LoginID;
                        item.CREATE_TIME = dtNow;
                    }
                    else
                    {
                        item.NAME = modelTestSync.NAME;
                        item.TYPE = modelTestSync.TYPE;
                        item.OPTION_A = modelTestSync.OPTION_A;
                        item.OPTION_B = modelTestSync.OPTION_B;
                        item.OPTION_C = modelTestSync.OPTION_C;
                        item.OPTION_D = modelTestSync.OPTION_D;
                        item.OPTION_E = modelTestSync.OPTION_E;
                        item.ANSWER = modelTestSync.ANSWER;
                        item.USAGE = modelTestSync.USAGE;
                        item.TRAINNAME = modelTestSync.TRAINNAME;
                        item.MineType = modelTestSync.MineType;
                    }
                    listTestSync.Add(item);
                }

                foreach (var item in listPoint)
                {
                    if (listPointData != null && listPointData.Count() > 0)
                    {
                        modelPointSync = listPointData.FirstOrDefault(e => e.ID == item.ID);
                    }
                    else
                    {
                        modelPointSync = null;
                    }
                    if (modelPointSync == null)
                    {
                        item.CREATER_ID = LoginID;
                        item.CREATE_TIME = dtNow;
                    }
                    else
                    {
                        item.TEST_ID = modelPointSync.TEST_ID;
                        item.POINT_ID = modelPointSync.POINT_ID;
                    }
                    listPointSync.Add(item);
                }

                foreach (var item in listPointEnum)
                {
                    if (listPointEnumData != null && listPointEnumData.Count() > 0)
                    {
                        modelPointEnumSync = listPointEnumData.FirstOrDefault(e => e.ID == item.ID);
                    }
                    else
                    {
                        modelPointEnumSync = null;
                    }
                    if (modelPointEnumSync == null)
                    {
                        item.CREATER_ID = LoginID;
                        item.CREATE_TIME = dtNow;
                    }
                    else
                    {
                        item.NAME = modelPointEnumSync.NAME;
                        item.CODE = modelPointEnumSync.CODE;
                        item.TYPE = modelPointEnumSync.TYPE;
                    }
                    listPointEnumSync.Add(item);
                }

                #endregion

                #region   数据统一处理   CREATE_TIME    MODIFY_TIME    MODIFIER_ID

                if (listTestSync != null && listTestSync.Count() > 0)
                {
                    foreach (var item in listTestSync)
                    {
                        item.Nav_Points = null;
                        item.ORG_ID = OrgID;
                        if (item.CREATER_ID == LoginID)
                        {
                            item.CREATE_TIME = dtNow;
                        }
                        item.MODIFY_TIME = dtNow;
                        item.MODIFIER_ID = LoginID;
                    }
                }

                if (listPointSync != null && listPointSync.Count() > 0)
                {
                    foreach (var item in listPointSync)
                    {
                        item.Nav_Point = null;
                        item.ORG_ID = OrgID;
                        if (item.CREATER_ID == LoginID)
                        {
                            item.CREATE_TIME = dtNow;
                        }
                        item.MODIFY_TIME = dtNow;
                        item.MODIFIER_ID = LoginID;
                    }
                }

                if (listPointEnumSync != null && listPointEnumSync.Count() > 0)
                {
                    foreach (var item in listPointEnumSync)
                    {
                        item.ORG_ID = OrgID;
                        if (item.CREATER_ID == LoginID)
                        {
                            item.CREATE_TIME = dtNow;
                        }
                        item.MODIFY_TIME = dtNow;
                        item.MODIFIER_ID = LoginID;
                    }
                }

                #endregion

                #region    数据处理

                UnifiedCommit(() =>
                {
                    if (listTestSync != null && listTestSync.Any())
                        BantchSaveEntityNoCommit(listTestSync);
                    if (listPointSync != null && listPointSync.Any())
                        BantchSaveEntityNoCommit(listPointSync);
                    if (listPointEnumSync != null && listPointEnumSync.Any())
                        BantchSaveEntityNoCommit(listPointEnumSync);
                });

                #endregion

                return true;
            });
        }

        /// <summary>
        /// 数据同步传参 
        /// </summary>
        public class SyscList
        {
            public List<T_SE_TEST> ListModel { get; set; }//ICollection
        }
    }
}
