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.SC.PT;
using APT.MS.Domain.Entities.SK;
using APT.MS.Domain.Enums.SK;
using APT.Utility;
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
{
    /// 
    ///  检查内容
    /// 
    [Route("api/SK/SKCheckContents")]
    public partial class CheckContentsController : AuthorizeApiController
    {
        /// 
        /// 排序分页查询数据
        /// 
        /// 分页过滤实体
        /// 
        [HttpPost, Route("SKOrderPaged")]
        public PagedActionResult SKOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            if (pageFilter.Sort == "NAME")
            {
                pageFilter.Sort = "";
            }
            pageFilter.Include.Add("Nav_ListCheckQuestion");
            return WitOrderPaged(null, pageFilter);
        }
        /// 
        /// 更新或新增数据
        /// 
        /// 对象实体
        /// 
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult FullUpdate([FromBody] T_SK_CHECK_CONTENTS entity)
        {
            return SafeExecute(() =>
            {
                var olds = this.GetEntity(t => !t.IS_DELETED && t.CHECKCONTENT == entity.CHECKCONTENT && t.ID != entity.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;
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        BantchSaveEntityNoCommit(details);
                    if (basics != null && basics.Any())
                        BantchSaveEntityNoCommit(basics);
                });
                return true;
            });
        }
        /// 
        /// 检查内容对应的隐患描述
        /// 
        /// 
        /// 
        [HttpPost, Route("GetHiddenScripList")]
        public PagedActionResult GetHiddenScripList([FromBody] KeywordPageFilter pageFilter)
        {
            if (pageFilter.Sort == "NAME")
            {
                pageFilter.Sort = "";
            }
            var result = new PagedActionResult();
            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 => t.CHECK_CONTENTS_ID == Guid.Parse(filter.Value.ToString()), pageFilter);
            }
            else
            {
                var resultTemp = this.GetEntities(t => t.IS_DELETED == false, new BaseFilter(pageFilter.OrgId));
                var questionIds = resultTemp.Distinct(t => t.DESCREPTION).Select(m => m.ID).ToList();
                result = this.GetOrderPageEntities(m => questionIds.Contains(m.ID), pageFilter);
            }
            return result;
        }
        /// 
        /// 导入
        /// 
        /// 
        /// 
        [HttpPost, Route("ImportUpdate")]
        public JsonActionResult ImportUpdate(IFormCollection files)
        {
            return SafeExecute(() =>
            {
                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 startRowIndexs = new Dictionary();
                    startRowIndexs.Add(0, 1);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;
                    isOK = InsertModel2(dataTables.Tables[0], orgId, ref Msg);
                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }
                }
                return isOK;
            });
        }
        /// 
        /// 导入
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        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 contents = new List();
            List qustions = new List();
            Guid? checkId = null;
            var baseFilter = new BaseFilter(orgId);
            var oldContents = this.GetEntities(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)//旧表已存在数据
                    {
                        checkId = first.ID;
                    }
                    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();
                    var scores = new List();
                    var methods = new List();
                    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)
                        throw new Exception("第" + (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
                                        throw new Exception("隐患对应序号的层级未填写");
                                }
                                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
                                        throw new Exception("隐患对应序号的层级未填写");
                                }
                                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
                                        throw new Exception("隐患对应序号的整改措施未填写");
                                }
                                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
                                        throw new Exception("隐患对应序号的整改措施未填写");
                                }
                                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;
        }
        /// 
        /// 导入
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        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 contents = new List();
            List qustions = new List();
            var baseFilter = new BaseFilter(orgId);
            var productionUnits = this.GetEntities(i => i.IS_DELETED == false, baseFilter);
            var oldContents = this.GetEntities(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 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)//旧表已存在数据
                        {
                            T_SK_CHECK_QUESTION content = new T_SK_CHECK_QUESTION();
                            content.ORG_ID = orgId;
                            content.CHECKCONTENT = dtSource.Rows[i][1].ToString().Trim();
                            content.DESCREPTION = dtSource.Rows[i][2].ToString().Trim();
                            content.QUESTION_LEVEL_SHOW = dtSource.Rows[i][3].ToString().Trim();
                            content.QUESTION_LEVEL = content.QUESTION_LEVEL_SHOW == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                            content.DEMAND = dtSource.Rows[i][4].ToString().Trim();
                            content.PRODUCTION_UNIT_ID = unit?.ID;
                            content.CHECK_CONTENTS_ID = first.ID;
                            qustions.Add(content);
                        }
                        else
                        {
                            T_SK_CHECK_QUESTION content = new T_SK_CHECK_QUESTION();
                            content.ORG_ID = orgId;
                            content.CHECKCONTENT = dtSource.Rows[i][1].ToString().Trim();
                            content.DESCREPTION = dtSource.Rows[i][2].ToString().Trim();
                            content.QUESTION_LEVEL_SHOW = dtSource.Rows[i][3].ToString().Trim();
                            content.QUESTION_LEVEL = content.QUESTION_LEVEL_SHOW == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                            content.DEMAND = dtSource.Rows[i][4].ToString().Trim();
                            content.PRODUCTION_UNIT_ID = unit?.ID;
                            qustions.Add(content);
                        }
                    
                    
                }
            }
            if (qustions != null && qustions.Any())
            {
                var contentList2 = qustions.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 = qustions.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 qu in qus)
                        {
                            qu.NUM = j;
                            j++;
                        }
                    }
                }
                var contentList = qustions.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;
                        contents.Add(content);
                        var qus = qustions.Where(t => t.PRODUCTION_UNIT_ID == item.Key.PRODUCTION_UNIT_ID && t.CHECKCONTENT == item.Key.CHECKCONTENT).ToList();
                        var j = 1;
                        foreach (var qu in qus)
                        {
                            qu.CHECK_CONTENTS_ID = content.ID;
                            qu.NUM = j;
                            j++;
                        }
                    }
                }
            }
            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;
        }
    }
}