using FluentScheduler;
using Microsoft.AspNetCore.Http;
using NPOI.SS.Formula.Functions;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using Siger.Middlelayer.AccRepository;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Dapper.FlowMetek;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Share.Constant;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Siger.ApiFlowMetek.Tasks
{
    /// <summary>
    /// Execl附件形式同步到Trace
    /// </summary>
    public class MetekExeclJob : IJob
    {
        private ErpRepository _erpRepository;
        private ApiAccDbContext _context;
        private ApiConfigDbContext _cfgContext;
        public MetekExeclJob()
        {
            _erpRepository = new ErpRepository();
            _context = new ApiAccDbContext();
            _cfgContext = new ApiConfigDbContext();
        }
        public void Execute()
        {
            try
            {
                Logger.WriteLineInfo("metekExcelJob start...");
                var path = _erpRepository.ExcelPath();
                var pid = _erpRepository.GetConfigPid();
                if (string.IsNullOrEmpty(path))
                {
                    Logger.WriteLineInfo("excel path is null");
                    return;
                }
                if (!Directory.Exists(path))
                {
                    Logger.WriteLineInfo($"{path} not found");
                    return;
                }
                if (pid == 0)
                {
                    Logger.WriteLineInfo("projectId not config");
                    return;
                }
                var dic = _context.siger_tr_dict.FirstOrDefault(f => f.projectId == pid && f.cat == AccDictCost.FlowMetek && f.dkey == DictKeyValConst.CheckExcelStation && f.status==(int)RowState.Valid);
                if (dic == null)
                {
                    Logger.WriteLineInfo("excel station id not config");
                    return;
                }
                var cfg = _cfgContext.siger_project_sync_config.FirstOrDefault(f => f.projectId == pid && f.module == (int)Module.Acc && f.table == MeteERPTable.CheckExcel);

                int.TryParse(dic.dval, out int station);
                var dateStr = DateTime.Now.ToString("yyyyMMdd");
                var virtualPath = Path.Combine(CommonConst.MetekAttachmentFilePath, dateStr);
                var physicaPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, virtualPath);
                if (!Directory.Exists(physicaPath))
                {
                    Directory.CreateDirectory(physicaPath);
                }
                DirectoryInfo dir = new DirectoryInfo(path);

                var folders = dir.GetDirectories();
                foreach (var folder in folders)
                {
                    //检查日期文件夹
                    var folderDate = folder.CreationTime;
                    if (cfg != null)
                    {
                        if (DateTime.TryParse(cfg.modifyDate, out DateTime folerCompatime))
                        {
                            if (folderDate.Date < folerCompatime.Date)
                                continue;
                        }
                    }

                    //检查文件
                    var files = folder.GetFiles();
                    if (files.Count() > 0)
                    {
                       
                        var lastupdate = DateTime.MinValue;
                        foreach (var file in files)
                        {
                            var ctime = file.CreationTime;
                            if (cfg != null)
                            {
                                if (DateTime.TryParse(cfg.createDate, out DateTime compatime))
                                {
                                    var total = ctime.Subtract(compatime).TotalSeconds;
                                    if (ctime < compatime || total<1)
                                        continue;
                                }
                            }
                            if (lastupdate < ctime)
                            {
                                lastupdate = ctime;
                            }
                            var sourcFile = file.FullName;
                            var direFile = Path.Combine(physicaPath, file.Name);
                            File.Copy(sourcFile, direFile, true);

                            var filename = file.Name.Remove(file.Name.LastIndexOf("."));
                            if (filename.Length < 8)
                            {
                                Logger.WriteLineInfo($"{filename} length less 8");
                                continue;
                            }
                            var snStr = filename.Substring(filename.Length - 8, 8);
                            SaveData(snStr, virtualPath, pid, station);


                            if (cfg == null)
                            {
                                _cfgContext.siger_project_sync_config.Add(new Middlelayer.Repository.Entities.siger_project_sync_config
                                {
                                    projectId = pid,
                                    createDate = lastupdate.ToString(),
                                    modifyDate = folderDate.Date.ToString(),
                                    module = (int)Module.Acc,
                                    table = MeteERPTable.CheckExcel,
                                    status = 1,
                                    lastupdate = DateTime.Now
                                });
                            }
                            else
                            {
                                cfg.createDate = lastupdate.ToString();
                                cfg.modifyDate = folderDate.Date.ToString();
                            }
                            _cfgContext.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.ToString());
            }
        }

        void SaveData(string sn ,string path,int projectId, int station)
        {
            var snObj = _context.siger_tr_sn_list.FirstOrDefault(f => f.projectId == projectId && f.SN == sn);
            if (snObj == null)
            {

                return;
            }
            var traceObj = _context.siger_tr_sn_trace.FirstOrDefault(f => f.projectId == projectId && f.SN == sn);
            if (traceObj != null)
            {
                return;
            }
            var seqID = Guid.NewGuid().ToString();
            var datetime = DateTime.Now;
            _context.siger_tr_sn_trace.Add(new Middlelayer.AccRepository.Entities.SigerTrSnTrace
            {
                SeqID = seqID,
                Station = station,
                TransDateTime = datetime,
                LastUpdateTime = datetime,
                status = 1,
                projectId = projectId,
                SN = sn,
                Result = "OK",
                type = 0,
                ProductID = snObj.ProductId.ToString()


            }); ;
            _context.siger_tr_sn_trace_detail.Add(new Middlelayer.AccRepository.Entities.SigerTrSNTraceDetail
            {
                SeqID = seqID,
                SN = sn,
                projectId = projectId,
                Result = "OK",
                Item = "附件",
                Value = path,
                LastUpdateTime = datetime,
                TransDateTime = datetime,
                status = 1,
                Remarks = "attachment url"

            });
            _context.SaveChanges();
        }
    }
}
