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;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SEConfig")]
    public partial class SEConfigController : AuthorizeApiController<T_SE_SECONFIG>
    {
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_SECONFIG entity)
        {
            return SafeExecute(() =>
            {
                var total = entity.S_TEST_COUNT * entity.S_TEST_SCORE+ entity.M_TEST_COUNT *entity.M_TEST_SCORE+entity.C_TEST_COUNT*entity.C_TEST_SCORE;
                entity.DEP_TRAIN_PLAN_END_TIME= DateTime.Parse(entity.DEP_TRAIN_PLAN_END_TIME.Value.ToShortDateString()+" 23:59:59");
                if (total != 100)
                {
                    throw new Exception("请注意试题总分是否为100分!");
                }
                this.UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                });
                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)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            Dictionary<int, List<int>> dicIndexEmpty = new Dictionary<int, List<int>>();
            //第一行是标题 跳过
            int rowAll = dtSource.Rows.Count;
            for (int i = 0; i < rowAll; i++)
            {
                for (int j = 0; j < 8; 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);//有空的 直接添加
                }
            }

            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            List<T_SE_RENEWAL_TRAIN> laws = new List<T_SE_RENEWAL_TRAIN>();
            var typess = GetEntities<T_SE_CERTIFICATE_TYPE>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            var users = GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0, new BaseFilter(orgId));
            DateTime dtNow = DateTime.Now;
            for (int i = 0; i < rowAll; i++)
            {
                T_SE_RENEWAL_TRAIN law = new T_SE_RENEWAL_TRAIN();
                law.ID = Guid.NewGuid();
                law.USER_ID = (Guid)userId;
                if (users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][0].ToString().Trim()) != null)
                {
                    law.USER_ID = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][0].ToString().Trim()).ID;
                }
                else
                {
                    throw new Exception("人员:" + dtSource.Rows[i][0].ToString().Trim() + "未找到");
                }
                if (typess.FirstOrDefault(t => t.NAME == dtSource.Rows[i][1].ToString().Trim()) != null)
                {
                    law.CERTIFICATE_TYPE_ID = typess.FirstOrDefault(t => t.NAME == dtSource.Rows[i][1].ToString().Trim()).ID;
                }
                else
                {
                    throw new Exception("证书类别:" + dtSource.Rows[i][1].ToString().Trim() + "未找到");
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][2].ToString().Trim()))
                {
                    law.CERTIFICATE_NAME = dtSource.Rows[i][2].ToString().Trim();
                }
                else
                {
                    throw new Exception("名称不能为空!");
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][3].ToString().Trim()))
                {
                    law.CERTIFICATE_CODE = dtSource.Rows[i][3].ToString().Trim();
                }
                else
                {
                    throw new Exception("证书编号不能为空!");
                }

                if (!string.IsNullOrEmpty(dtSource.Rows[i][4].ToString().Trim()))
                {
                    law.CERTIFICATE_AUTHORITY = dtSource.Rows[i][4].ToString().Trim();
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][5].ToString().Trim()))
                {
                    law.ISSUE_DATE = DateTime.Parse(dtSource.Rows[i][5].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][6].ToString().Trim()))
                {
                    law.EXPIRY_DATE = DateTime.Parse(dtSource.Rows[i][6].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][7].ToString().Trim()))
                {
                    law.REVIEW_DATE = DateTime.Parse(dtSource.Rows[i][7].ToString().Trim());
                }
                law.ORG_ID = orgId;
                laws.Add(law);
            }
            UnifiedCommit(() =>
            {
                if (laws != null && laws.Any())
                    BantchAddEntityNoCommit(laws);
            });
            Msg = "导入成功！";
            return true;
        }
    }
}
