using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.SC
{
    [Route("api/SC/SCMTContent")]
    public class SCMTContentController : AuthorizeApiController<T_SC_MT_CONTENT>
    {
        public SCMTContentController()
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SC_MT_CONTENT entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.MEETINGTYPE == 0)
                {
                    throw new Exception("请选择会议类型！");
                }
                if (!entity.CONTENTNAME_ID.HasValue)
                {
                    throw new Exception("请选择会议内容！");
                }
                if (entity.CHECKTYPE == 0)
                {
                    throw new Exception("请选择题型！");
                }
                if (string.IsNullOrEmpty(entity.TITLE))
                {
                    throw new Exception("请填写题目！");
                }

                var check = GetEntity<T_SC_MT_CONTENT>(e => e.ID != entity.ID && e.MEETINGTYPE == entity.MEETINGTYPE && e.CONTENTNAME_ID == entity.CONTENTNAME_ID && e.CHECKTYPE == entity.CHECKTYPE && e.TITLE == entity.TITLE && !e.IS_DELETED);
                if (check != null)
                {
                    throw new Exception("会议意见基础库不能重复！");
                }

                var contentDetail = entity.Nav_ListContentDeal;
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                                                        //保存新的
                    if (contentDetail != null && contentDetail.Any())
                        this.BantchSaveEntityNoCommit(contentDetail);
                });
                return true;
            });
        }



        #region     自定义数据导入


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

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

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

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

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

                return result;
            });
        }

        /// <summary>
        /// 数据插入
        /// </summary>
        /// <param name="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)
        {
            //会议内容 会议类型    题型 题目  选项 (开发资料 可以直接导入)

            if (dtSource == null || dtSource.Rows.Count < rowIndex + 1)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }

            //5列数据 
            //1、会议内容  2、会议类型  3、题型  4、题目 5、选项

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

            List<string> listMeetTingType = new List<string>() { "普通会议", "文件审核会", "文件评审会", "安委会", "基层安全会" };
            List<string> listCheckType = new List<string>() { "单选", "复选" };//题型

            Dictionary<string, SCMEETINGTYPE> dicContentName = new Dictionary<string, SCMEETINGTYPE>();
            List<string> listContentName = new List<string>();
            #region     数据判断

            //第一行是标题 跳过
            int rowAll = dtSource.Rows.Count;
            for (int i = rowIndex; i < rowAll; i++)
            {
                #region    不能为空

                for (int j = 0; j < 5; j++)
                {
                    List<int> listi = null;
                    if (string.IsNullOrEmpty(dtSource.Rows[i][j].ToString().Trim()))
                    {
                        if (j == 0 && i != rowIndex)
                        {
                            //会议内容 合并 可以为空 
                            continue;
                        }
                        if (listi == null)
                        {
                            listi = new List<int>();
                        }
                        listi.Add(j);
                    }
                    if (listi == null)
                        continue;
                    dicIndexEmpty.Add(i, listi);//有空的 直接添加
                }

                #endregion

                #region    会议类型错误

                if (!listMeetTingType.Contains(dtSource.Rows[i][1]) && !string.IsNullOrEmpty(dtSource.Rows[i][1].ToString().Trim()))
                {
                    listTypeError.Add(i);
                }
                else
                {
                    if (dicIndexEmpty.Count < 1 && listTypeError.Count < 1 && listCheckTypeError.Count < 1)
                    {
                        //有错 就不添加了
                        if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()) && !dicContentName.ContainsKey(dtSource.Rows[i][0].ToString().Trim()))
                        {
                            dicContentName.Add(dtSource.Rows[i][0].ToString().Trim(), GetMeetingType(dtSource.Rows[i][1].ToString().Trim()).Value);
                            listContentName.Add(dtSource.Rows[i][0].ToString().Trim());
                        }
                    }
                }

                #endregion

                #region    题型错误

                if (!listCheckType.Contains(dtSource.Rows[i][2]) && !string.IsNullOrEmpty(dtSource.Rows[i][2].ToString()))
                {
                    listCheckTypeError.Add(i);
                }

                #endregion

            }

            #endregion

            #region     提示

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

            //行 会议类型错误
            string strTypeError = "";
            if (listTypeError.Count > 0)
            {
                strTypeError = "行：";
                for (int i = 0; i < listTypeError.Count; i++)
                {
                    strTypeError += (i > 0 ? "、" : "") + listTypeError[i];
                }
                strTypeError += "会议类型有误！";
            }

            //行 会议类型错误
            string strCheckTypeError = "";
            if (listCheckTypeError.Count > 0)
            {
                strCheckTypeError = "行：";
                for (int i = 0; i < listCheckTypeError.Count; i++)
                {
                    strCheckTypeError += (i > 0 ? "、" : "") + listCheckTypeError[i];
                }
                strCheckTypeError += "题型有误！";
            }

            if (!string.IsNullOrEmpty(strTypeError) || !string.IsNullOrEmpty(strCheckTypeError))
            {
                Msg = Msg + strTypeError + strCheckTypeError;
            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }

            #endregion

            #region     数据插入

            List<T_SC_MT_CONTENT_NAME> listContentNameAdd = new List<T_SC_MT_CONTENT_NAME>();
            List<T_SC_MT_CONTENT> listContentAdd = new List<T_SC_MT_CONTENT>();
            List<T_SC_MT_CONTENT_DEAL> listContentDealAdd = new List<T_SC_MT_CONTENT_DEAL>();

            var listModelContentName = GetEntities<T_SC_MT_CONTENT_NAME>(e => listContentName.Contains(e.NAME), null, null);
            List<T_SC_MT_CONTENT_NAME> listModelContentNames = new List<T_SC_MT_CONTENT_NAME>();
            if (listModelContentName != null && listModelContentName.Any())
            {
                listModelContentNames = listModelContentName.ToList();
            }
            DateTime dtNow = DateTime.Now;
            string strDtNow = dtNow.ToString("yyyyMMddHHmmss");
            int CONTENT_NO = 1;
            T_SC_MT_CONTENT_NAME modelName = null;
            for (int i = rowIndex; i < rowAll; i++)
            {
                if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))
                {
                    modelName = listModelContentNames.FirstOrDefault(e => e.NAME == dtSource.Rows[i][0].ToString().Trim() && e.MEETINGTYPE == GetMeetingType(dtSource.Rows[i][1].ToString().Trim()));
                    
                }
                //空的话 保持和上一个一致

                #region    会议内容名称

                if (modelName == null)
                {
                    modelName = new T_SC_MT_CONTENT_NAME();
                    modelName.ID = Guid.NewGuid();
                    modelName.CODE = strDtNow + i;
                    modelName.NAME = dtSource.Rows[i][0].ToString().Trim();
                    modelName.ENABLE_STATUS = FMEnableStatusEnum.启用;
                    modelName.IS_DELETED = false;
                    modelName.ORG_ID = OrgID;
                    modelName.CREATE_TIME = dtNow;
                    modelName.MEETINGTYPE = GetMeetingType(dtSource.Rows[i][1].ToString().Trim()).Value;
                    //model.ENTITY_ORG_TPYE
                    //model.FORM_ID
                    //model.FLOW_STATUS
                    //model.FLOW_SEND_STATUS
                    //model.FLOW_ID
                    //model.MODIFY_TIME
                    //model.CREATER_ID
                    //model.MODIFIER_ID
                    listContentNameAdd.Add(modelName);
                    listModelContentNames.Add(modelName);
                    CONTENT_NO = 1;
                }

                #endregion

                #region    会议内容题型 题目

                //会议  题目等 不考虑与数据库重复 直接插入

                T_SC_MT_CONTENT modelContent = new T_SC_MT_CONTENT();
                modelContent.ID = Guid.NewGuid();
                modelContent.CODE = strDtNow + i;
                modelContent.CHECKTYPE = dtSource.Rows[i][2].ToString().Trim() == "复选" ? CHECKTYPE.Check : CHECKTYPE.TheRadio;
                modelContent.TITLE = dtSource.Rows[i][3].ToString().Trim();
                modelContent.IS_DELETED = false;
                modelContent.ORG_ID = OrgID;
                modelContent.CREATE_TIME = dtNow;
                modelContent.MEETINGTYPE = modelName.MEETINGTYPE;
                modelContent.CONTENTNAME_ID = modelName.ID;

                modelContent.CONTENT_NO = CONTENT_NO;
                CONTENT_NO++;

                //modelContent.ENTITY_ORG_TPYE
                //modelContent.FORM_ID
                //modelContent.FLOW_STATUS
                //modelContent.FLOW_SEND_STATUS
                //modelContent.FLOW_ID
                //modelContent.MODIFY_TIME
                //modelContent.CREATER_ID
                //modelContent.MODIFIER_ID

                listContentAdd.Add(modelContent);//会议意见

                #endregion

                #region     会议选项

                //"□安全生产法律法规与其他要求的相关规定  
                //□风险控制要求
                //□事故应对措施
                //□员工的合理化建议
                //□工艺、设备安全技术改造"
                //是 / 部分 / 否
                //是 / 部分 / 否
                //是 / 部分 / 否
                //是 / 部分 / 否
                //点选，是 / 否
                //点选，是 / 否

                string strDetails = dtSource.Rows[i][4].ToString().Trim();
                string[] details = strDetails.Split(new char[] { ' ', '/', ',', '，', '□', '点', '选', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                if (details == null)
                {
                    continue;
                }
                else
                {
                    for (int j = 0; j < details.Length; j++)
                    {
                        T_SC_MT_CONTENT_DEAL modelDetails = new T_SC_MT_CONTENT_DEAL();
                        modelDetails.ID = Guid.NewGuid();
                        modelDetails.CONTENT_ID = modelContent.ID;
                        modelDetails.CONTENTDETAIL = details[j];
                        modelDetails.PERSCORE = 0;
                        modelDetails.IS_DELETED = false;
                        modelDetails.ORG_ID = OrgID;
                        modelDetails.CREATE_TIME = dtNow;
                        modelDetails.CONTENT_DEAL_NO = (j + 1);
                        //modelDetails.ENTITY_ORG_TPYE  = ;
                        //modelDetails.FORM_ID          = ;
                        //modelDetails.FLOW_STATUS      = ;
                        //modelDetails.FLOW_SEND_STATUS = ;
                        //modelDetails.FLOW_ID          = ;
                        //modelDetails.MODIFY_TIME
                        //modelDetails.CREATER_ID
                        //modelDetails.MODIFIER_ID
                        listContentDealAdd.Add(modelDetails);
                    }
                }
                #endregion
            }

            #endregion

            this.UnifiedCommit(() =>
            {
                if (listContentNameAdd != null && listContentNameAdd.Any())
                    this.BantchSaveEntityNoCommit(listContentNameAdd);
                if (listContentAdd != null && listContentAdd.Any())
                    this.BantchSaveEntityNoCommit(listContentAdd);
                if (listContentDealAdd != null && listContentDealAdd.Any())
                    this.BantchSaveEntityNoCommit(listContentDealAdd);
            });
            Msg = "导入成功！";
            return true;
        }


        private SCMEETINGTYPE? GetMeetingType(string MeetingType)
        {
            SCMEETINGTYPE? result = null;
            switch (MeetingType)
            {
                case "普通会议":
                    result = SCMEETINGTYPE.Ordinary;
                    break;
                case "文件审核会":
                    result = SCMEETINGTYPE.FileAudit;
                    break;
                case "文件评审会":
                    result = SCMEETINGTYPE.FileReView;
                    break;
                case "安委会":
                    result = SCMEETINGTYPE.SafetyBoard;
                    break;
                case "基层安全会":
                    result = SCMEETINGTYPE.BasicSecurity;
                    break;
                default:
                    break;
            }
            return result;
        }

        #endregion

    }
}