using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.SC.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.FO.WebApi.Controllers
{
    /// <summary>
    ///  工作票排班明细
    /// </summary>
    [Route("api/FO/FOScheduling")]
    public partial class SchedulingController : AuthorizeApiController<T_FO_SCHEDULING>
    {
        /// <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)
        {
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            var newFilter = new BaseFilter(orgId);
            newFilter.SelectField = new List<string> { "NAME" };
            var fmClass = this.GetEntities<T_FM_CLASS>(t => !t.IS_DELETED, newFilter, "Nav_ClassDetail");
            var users = GetEntities<T_FM_USER>(t => t.IS_DELETED == false && t.ENABLE_STATUS == 0, new BaseFilter(orgId));
            if (dtSource.Rows.Count == 1)
            {
                throw new Exception("导入必须两条以上，一条请直接新增");
            }
            for (int i = 0; i < rowAll; i++)
            {
                if (string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第"+(i+1)+"行第1列:日期不能为空";
                    else
                        Msg = Msg + "\n" + "第" + (i + 1) + "行第1列:日期不能为空";
                }
                if (string.IsNullOrEmpty(dtSource.Rows[i][1].ToString().Trim()))
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + (i + 1) + "行第2列:班次不能为空";
                    else
                        Msg = Msg + "\n" + "第" + (i + 1) + "行第2列:班次不能为空";
                }
                else 
                {
                    var firstClass = fmClass.FirstOrDefault(t => t.NAME == dtSource.Rows[i][1].ToString().Trim());
                    if (firstClass == null)
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + (i + 1) + "行第2列:班次未找到，请先到班次管理添加";
                        else
                            Msg = Msg + "\n" + "第" + (i + 1) + "行第2列:班次未找到，请先到班次管理添加";
                    }
                }
                if (string.IsNullOrEmpty(dtSource.Rows[i][2].ToString().Trim()))
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + (i + 1) + "行第3列:带班领导不能为空";
                    else
                        Msg = Msg + "\n" + "第" + (i + 1) + "行第3列:带班领导不能为空";
                }
                else
                {
                    var firstUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][2].ToString().Trim());
                    if (firstUser == null)
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + (i + 1) + "行第3列:带班领导未找到，请先到用户列表添加";
                        else
                            Msg = Msg + "\n" + "第" + (i + 1) + "行第3列:带班领导未找到，请先到用户列表添加";
                    }
                }
                if (string.IsNullOrEmpty(dtSource.Rows[i][5].ToString().Trim()))
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + (i + 1) + "行第6列:班次不能为空";
                    else
                        Msg = Msg + "\n" + "第" + (i + 1) + "行第6列:班次不能为空";
                }
                else
                {
                    var firstClass = fmClass.FirstOrDefault(t => t.NAME == dtSource.Rows[i][5].ToString().Trim());
                    if (firstClass == null)
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + (i + 1) + "行第6列:班次未找到，请先到班次管理添加";
                        else
                            Msg = Msg + "\n" + "第" + (i + 1) + "行第6列:班次未找到，请先到班次管理添加";
                    }
                }
                if (string.IsNullOrEmpty(dtSource.Rows[i][6].ToString().Trim()))
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + (i + 1) + "行第7列:带班领导不能为空";
                    else
                        Msg = Msg + "\n" + "第" + (i + 1) + "行第7列:带班领导不能为空";
                }
                else
                {
                    var firstUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][6].ToString().Trim());
                    if (firstUser == null)
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + (i + 1) + "行第7列:带班领导未找到，请先到用户列表添加";
                        else
                            Msg = Msg + "\n" + "第" + (i + 1) + "行第7列:带班领导未找到，请先到用户列表添加";
                    }
                }
                if (string.IsNullOrEmpty(dtSource.Rows[i][9].ToString().Trim()))
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + (i + 1) + "行第10列:班次不能为空";
                    else
                        Msg = Msg + "\n" + "第" + (i + 1) + "行第10列:班次不能为空";
                }
                else
                {
                    var firstClass = fmClass.FirstOrDefault(t => t.NAME == dtSource.Rows[i][9].ToString().Trim());
                    if (firstClass == null)
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + (i + 1) + "行第10列:班次未找到，请先到班次管理添加";
                        else
                            Msg = Msg + "\n" + "第" + (i + 1) + "行第10列:班次未找到，请先到班次管理添加";
                    }
                }
                if (string.IsNullOrEmpty(dtSource.Rows[i][10].ToString().Trim()))
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + (i + 1) + "行第11列:带班领导不能为空";
                    else
                        Msg = Msg + "\n" + "第" + (i + 1) + "行第11列:带班领导不能为空";
                }
                else
                {
                    var firstUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][10].ToString().Trim());
                    if (firstUser == null)
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + (i + 1) + "行第11列:带班领导未找到，请先到用户列表添加";
                        else
                            Msg = Msg + "\n" + "第" + (i + 1) + "行第11列:带班领导未找到，请先到用户列表添加";
                    }
                }
                i++;
            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            var classFirst = fmClass.FirstOrDefault(t => t.NAME == dtSource.Rows[0][1].ToString().Trim());
            var classScond = fmClass.FirstOrDefault(t => t.NAME == dtSource.Rows[0][5].ToString().Trim());
            var classThird = fmClass.FirstOrDefault(t => t.NAME == dtSource.Rows[0][9].ToString().Trim());
            List<T_FO_SCHEDULING> sches = new List<T_FO_SCHEDULING>();
            string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            for (int i = 0; i < rowAll; i++)
            {
                var firstUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][2].ToString().Trim());
                var techUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][3].ToString().Trim());
                var driverUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][4].ToString().Trim());
                var scondUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][6].ToString().Trim());
                var techScondUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][7].ToString().Trim());
                var driverScondUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][8].ToString().Trim());
                var thirdUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][10].ToString().Trim());
                var techThirdUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][11].ToString().Trim());
                var driverThirdUser = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][12].ToString().Trim());
                T_FO_SCHEDULING sche = new T_FO_SCHEDULING();
                sche.ID = Guid.NewGuid();
                sche.ORG_ID = orgId;
                sche.DATE = Convert.ToDateTime(dtSource.Rows[i][0].ToString().Trim());
                sche.USER_ID = firstUser.ID;
                sche.TECH_ID = techUser?.ID;
                sche.DRIVER_ID = driverUser?.ID;
                sche.CLASS_ID = classFirst.ID;
                sche.REMARK = dtSource.Rows[i][13].ToString().Trim();
                sche.WEEK = Day[Convert.ToInt32(sche.DATE.DayOfWeek.ToString("d"))].ToString().Trim();
                sches.Add(sche);
                T_FO_SCHEDULING sche2 = new T_FO_SCHEDULING();
                sche2.ID = Guid.NewGuid();
                sche2.ORG_ID = orgId;
                sche2.DATE = Convert.ToDateTime(dtSource.Rows[i][0].ToString().Trim());
                sche2.USER_ID = scondUser.ID;
                sche2.TECH_ID = techScondUser?.ID;
                sche2.DRIVER_ID = driverScondUser?.ID;
                sche2.CLASS_ID = classScond.ID;
                sche2.REMARK = dtSource.Rows[i][13].ToString().Trim();
                sche2.WEEK = Day[Convert.ToInt32(sche.DATE.DayOfWeek.ToString("d"))].ToString().Trim();
                sches.Add(sche2);
                T_FO_SCHEDULING sche3 = new T_FO_SCHEDULING();
                sche3.ID = Guid.NewGuid();
                sche3.ORG_ID = orgId;
                sche3.DATE = Convert.ToDateTime(dtSource.Rows[i][0].ToString().Trim());
                sche3.USER_ID = thirdUser.ID;
                sche3.TECH_ID = techThirdUser?.ID;
                sche3.DRIVER_ID = driverThirdUser?.ID;
                sche3.CLASS_ID = classThird.ID;
                sche3.REMARK = dtSource.Rows[i][13].ToString().Trim();
                sche3.WEEK = Day[Convert.ToInt32(sche.DATE.DayOfWeek.ToString("d"))].ToString().Trim();
                sches.Add(sche3);
            }
            UnifiedCommit(() =>
            {
                if (sches != null && sches.Any())
                    BantchAddEntityNoCommit(sches);
            });
            //Msg = "导入成功！";
            return true;
        }

    }
}
