using System.Data;
using System.Transactions;
using ChinhDo.Transactions;
using Common;
using Commonlib;
using LiteDB;
using NLog;
using NPOI.POIFS.Crypt.Dsig;
using Quartz;

namespace BLW_Log.services
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class MyExcel : IJob
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        public static void ExcelDealWith()
        {
            NewMethod(true);
        }

        public static void NewMethod(bool Is_Auto = true)
        {
            string 现在时间_天 = DateTime.Now.ToString("yyyy/MM/dd");
            string 现在时间天 = DateTime.Now.ToString("yyyy-MM-dd");
            if (Is_Auto == false)
            {
                现在时间天 = DateTime.Now.ToString("yyyy-MM-dd#HH:mm:ss:fff");
            }
            try
            {

                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]单据编号(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]日期(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]购货单位(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头][自定义]项目名称：", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]币别(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]汇率(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]结算日期(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]销售方式", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]交货方式", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]发货地点", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]收货地址", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]结算方式", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]摘要", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]业务员", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头][自定义]技术员", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "物料代码(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "物料名称", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "规格型号", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "单位(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "数量(*)", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "税率(%)(*)", DataType = typeof(decimal) });
                dt.Columns.Add(new DataColumn() { ColumnName = "折扣率(%)(*)", DataType = typeof(decimal) });
                dt.Columns.Add(new DataColumn() { ColumnName = "交货日期(*)", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "辅助属性", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "备注", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "客户料号", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "客户商品名称", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "单价", DataType = typeof(string) });

                //获取需要处理的所有文件
                string[] dealwith_files = Directory.GetFiles(ExcelScan.DealWithDir);


                _logger.Info("开始读取 各个文件数据");
                List<DataTable> list_table = new List<DataTable>();
                foreach (var item in dealwith_files)
                {
                    string fileName = Path.GetFileName(item);
                    bool bbb = fileName.StartsWith(ExcelScan.上传成功);
                    bool ccc = fileName.StartsWith(ExcelScan.上传失败);
                    bool ddd = bbb && ccc;
                    if (ddd == false)
                    {
                        _logger.Info("读取文件" + fileName + "的数据");
                        var DT = ExcelHelper.ReadExcelToDataTable(ExcelScan.DealWithDir + "\\" + fileName);
                        DataTable NewDt = removeEmpty(DT);
                        list_table.Add(NewDt);
                    }
                }

                _logger.Info("合并各个文件数据");
                DataTable BigTable = MergeDataTables(list_table);


                _logger.Info("合并件数据完成");


                _logger.Info("生成 金蝶系统需要的数据 ");
                var QQ = BigTable.Rows.Cast<DataRow>();
                var QQ1 = QQ.GroupBy(A => A.Field<string>("项目名称"));
                IdWorker idworker = IdWorker.Singleton;
                using var db = new LiteDatabase(@"MyData.db");
                foreach (var item in QQ1)
                {
                    string? 项目名称 = item.Key;
                    //string currentdate = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    //S1123698807356395520
                    //S1123698807356395520
                    //S1123698807444475904

                    //string idaaaa = idworker.nextId().ToString();
                    //idaaaa = idaaaa.Substring(10, idaaaa.Length - 10);

                    // 获得 customer 集合
                    var col = db.GetCollection<Customer>("customers");
                    // 创建你的新 customer 实例
                    var customer = new Customer
                    {
                        Name = Guid.NewGuid().ToString(),
                    };

                    col.EnsureIndex(x => x.Name, true);
                    // 插入新的 customer 文档 (Id 是自增的)
                    col.Insert(customer);
                    //col.DeleteMany(A=>A.Id<=2000);

                    string idaaaa = customer.Id.ToString();

                    idaaaa = idaaaa.PadLeft(10, '0');
                    string 单据编号 = "S" + idaaaa;
                    Thread.Sleep(20);
                    string 现在时间 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    foreach (var item1 in item)
                    {
                        string? 产品料号 = item1["产品料号"]?.ToString();
                        string? 产品名称 = item1["产品名称"]?.ToString();
                        string? 发货数量 = item1["发货数量"]?.ToString();
                        string? 发货单价 = item1["单价"]?.ToString();
                        string? 销售 = item1["销售"]?.ToString();
                        string? 客户名称 = item1["客户名称"]?.ToString();
                        //string? 单位 = item1["单位"]?.ToString();

                        产品料号 = 产品料号?.Replace(" ", "");

                        DataRow dr = dt.NewRow();
                        dr["[表头]单据编号(*)"] = 单据编号;
                        dr["[表头]日期(*)"] = 现在时间;
                        /*dr["[表头]购货单位(*)"] = 项目名称;*/
                        dr["[表头]购货单位(*)"] = 项目名称;
                        dr["[表头][自定义]项目名称："] = 客户名称;
                        dr["[表头]币别(*)"] = "人民币";
                        dr["[表头]汇率(*)"] = "1";

                        dr["[表头]结算日期(*)"] = 现在时间_天;

                        dr["[表头]销售方式"] = "";
                        dr["[表头]交货方式"] = "";
                        dr["[表头]发货地点"] = "";
                        dr["[表头]收货地址"] = "";
                        dr["[表头]结算方式"] = "";
                        dr["[表头]摘要"] = "";
                        dr["[表头]业务员"] = 销售;
                        dr["[表头][自定义]技术员"] = "邹竟";
                        dr["物料代码(*)"] = 产品料号;
                        dr["物料名称"] = "";
                        dr["规格型号"] = "";
                        dr["单位(*)"] = "个";
                        dr["数量(*)"] = 发货数量;
                        dr["税率(%)(*)"] = "0";
                        dr["折扣率(%)(*)"] = "0";
                        dr["交货日期(*)"] = 现在时间_天;
                        dr["辅助属性"] = "";
                        dr["备注"] = "";


                        dr["客户料号"] = "";
                        dr["客户商品名称"] = "";
                        if (!string.IsNullOrWhiteSpace(发货单价))
                        {
                            dr["单价"] = 发货单价;
                        }
                        else
                        {
                            dr["单价"] = "0";
                        }
                        dt.Rows.Add(dr);
                    }
                }
                _logger.Info("生成 Excel 数据完成 ");

                string FinalFileResult = string.Format("{0}\\{1}.xlsx", ExcelScan.targetDir, 现在时间天);
                //创建新的Excel
                ExcelHelper.CreateNewExcel(FinalFileResult, dt);

                _logger.Info("生成 Excel 完成。Excel的名字为：" + FinalFileResult);

                string fileNameFFF = Path.GetFileName(FinalFileResult);
                string bakDirFFF = ExcelScan.JinDieBakDir + "\\" + 现在时间天;
                if (!Directory.Exists(bakDirFFF))
                {
                    Directory.CreateDirectory(bakDirFFF);
                }
                string bakname = bakDirFFF + "\\" + fileNameFFF;
                File.Copy(FinalFileResult, bakname, true);


                _logger.Info("生成 Excel 备份完成。Excel的名字为：" + FinalFileResult);
                foreach (var item in dealwith_files)
                {
                    File.Delete(item);
                }

                string[] source_files = Directory.GetFiles(ExcelScan.sourceDir);
                foreach (var item in source_files)
                {
                    File.Delete(item);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("生成财务需要的数据出错：" + ex.Message);
            }
        }
        public static void TempNewMethod(bool Is_Auto = true)
        {
            string 现在时间_天 = DateTime.Now.ToString("yyyy/MM/dd");
            string 现在时间天 = DateTime.Now.ToString("yyyy-MM-dd");
            if (Is_Auto == false)
            {
                现在时间天 = DateTime.Now.ToString("yyyy-MM-dd#HH:mm:ss:fff");
            }
            try
            {

                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]单据编号(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]日期(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]购货单位(*)", DataType = typeof(string), MaxLength = 225 }); 
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头][自定义]项目名称：", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]币别(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]汇率(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]结算日期(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]销售方式", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]交货方式", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]发货地点", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]收货地址", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]结算方式", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]摘要", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头]业务员", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "[表头][自定义]技术员", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "物料代码(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "物料名称", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "规格型号", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "单位(*)", DataType = typeof(string), MaxLength = 225 });
                dt.Columns.Add(new DataColumn() { ColumnName = "数量(*)", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "税率(%)(*)", DataType = typeof(decimal) });
                dt.Columns.Add(new DataColumn() { ColumnName = "折扣率(%)(*)", DataType = typeof(decimal) });
                dt.Columns.Add(new DataColumn() { ColumnName = "交货日期(*)", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "辅助属性", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "备注", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "客户料号", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "客户商品名称", DataType = typeof(string) });
                dt.Columns.Add(new DataColumn() { ColumnName = "单价", DataType = typeof(string) });

                //获取需要处理的所有文件
                string[] dealwith_files = Directory.GetFiles(ExcelScan.DealWithDir);


                _logger.Info("开始读取 各个文件数据");
                List<DataTable> list_table = new List<DataTable>();
                foreach (var item in dealwith_files)
                {
                    string fileName = Path.GetFileName(item);
                    bool bbb = fileName.StartsWith(ExcelScan.上传成功);
                    bool ccc = fileName.StartsWith(ExcelScan.上传失败);
                    bool ddd = bbb && ccc;
                    if (ddd == false)
                    {
                        _logger.Info("读取文件" + fileName + "的数据");
                        var DT = ExcelHelper.ReadExcelToDataTable(ExcelScan.DealWithDir + "\\" + fileName);
                        DataTable NewDt = removeEmpty(DT);
                        list_table.Add(NewDt);
                    }
                }

                _logger.Info("合并各个文件数据");
                DataTable BigTable = MergeDataTables(list_table);


                _logger.Info("合并件数据完成");


                _logger.Info("生成 金蝶系统需要的数据 ");
                var QQ = BigTable.Rows.Cast<DataRow>();
                var QQ1 = QQ.GroupBy(A => A.Field<string>("项目名称"));
                IdWorker idworker = IdWorker.Singleton;
                using var db = new LiteDatabase(@"MyData.db");
                foreach (var item in QQ1)
                {
                    string? 项目名称 = item.Key;
                    //string currentdate = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    //S1123698807356395520
                    //S1123698807356395520
                    //S1123698807444475904

                    //string idaaaa = idworker.nextId().ToString();
                    //idaaaa = idaaaa.Substring(10, idaaaa.Length - 10);

                    // 获得 customer 集合
                    var col = db.GetCollection<Customer>("customers");
                    // 创建你的新 customer 实例
                    var customer = new Customer
                    {
                        Name = Guid.NewGuid().ToString(),
                    };

                    col.EnsureIndex(x => x.Name, true);
                    // 插入新的 customer 文档 (Id 是自增的)
                    col.Insert(customer);
                    //col.DeleteMany(A=>A.Id<=2000);

                    string idaaaa = customer.Id.ToString();

                    idaaaa = idaaaa.PadLeft(10, '0');
                    string 单据编号 = "S" + idaaaa;
                    Thread.Sleep(20);
                    string 现在时间 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    foreach (var item1 in item)
                    {
                        string? 产品料号 = item1["产品料号"]?.ToString();
                        string? 产品名称 = item1["产品名称"]?.ToString();
                        string? 发货数量 = item1["发货数量"]?.ToString();
                        string? 发货单价 = item1["单价"]?.ToString();
                        string? 销售 = item1["销售"]?.ToString();
                        string? 客户名称 = item1["客户名称"]?.ToString();
                        //string? 单位 = item1["单位"]?.ToString();

                        产品料号 = 产品料号?.Replace(" ", "");

                        DataRow dr = dt.NewRow();
                        dr["[表头]单据编号(*)"] = 单据编号;
                        dr["[表头]日期(*)"] = 现在时间;
                        /*dr["[表头]购货单位(*)"] = 项目名称;*/
                        dr["[表头]购货单位(*)"] = 项目名称;
                        dr["[表头][自定义]项目名称："] = 客户名称;
                        dr["[表头]币别(*)"] = "人民币";
                        dr["[表头]汇率(*)"] = "1";

                        dr["[表头]结算日期(*)"] = 现在时间_天;

                        dr["[表头]销售方式"] = "";
                        dr["[表头]交货方式"] = "";
                        dr["[表头]发货地点"] = "";
                        dr["[表头]收货地址"] = "";
                        dr["[表头]结算方式"] = "";
                        dr["[表头]摘要"] = "";
                        dr["[表头]业务员"] = 销售;
                        dr["[表头][自定义]技术员"] = "邹竟";
                        dr["物料代码(*)"] = 产品料号;
                        dr["物料名称"] = "";
                        dr["规格型号"] = "";
                        dr["单位(*)"] = "个";
                        dr["数量(*)"] = 发货数量;
                        dr["税率(%)(*)"] = "0";
                        dr["折扣率(%)(*)"] = "0";
                        dr["交货日期(*)"] = 现在时间_天;
                        dr["辅助属性"] = "";
                        dr["备注"] = "";


                        dr["客户料号"] = "";
                        dr["客户商品名称"] = "";
                        if (!string.IsNullOrWhiteSpace(发货单价))
                        {
                            dr["单价"] = 发货单价;
                        }
                        else
                        {
                            dr["单价"] = "0";
                        }
                        dt.Rows.Add(dr);
                    }
                }
                _logger.Info("生成 Excel 数据完成 ");

                string namesss = 现在时间天 + "-" + DateTime.Now.ToString("mmss");
                string FinalFileResult = string.Format("{0}\\{1}.xlsx", ExcelScan.targetDir, namesss);
                //创建新的Excel
                ExcelHelper.CreateNewExcel(FinalFileResult, dt);

                _logger.Info("生成 Excel 完成。Excel的名字为：" + FinalFileResult);

                string fileNameFFF = Path.GetFileName(FinalFileResult);
                string bakDirFFF = ExcelScan.JinDieBakDir + "\\" + 现在时间天;
                if (!Directory.Exists(bakDirFFF))
                {
                    Directory.CreateDirectory(bakDirFFF);
                }
                string bakname = bakDirFFF + "\\" + fileNameFFF;
                File.Copy(FinalFileResult, bakname, true);


                _logger.Info("生成 Excel 备份完成。Excel的名字为：" + FinalFileResult);
                foreach (var item in dealwith_files)
                {
                    File.Delete(item);
                }

                string[] source_files = Directory.GetFiles(ExcelScan.sourceDir);
                foreach (var item in source_files)
                {
                    File.Delete(item);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("生成财务需要的数据出错：" + ex.Message);
            }
        }

        protected static DataTable removeEmpty(DataTable dt)
        {
            List<DataRow> rows = new List<DataRow>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string sss = dt.Rows[i]["项目名称"].ToString();
                if (string.IsNullOrWhiteSpace(sss))
                {
                    rows.Add(dt.Rows[i]);
                }
            }
            foreach (DataRow row in rows)
            {
                dt.Rows.Remove(row);
            }
            return dt;
        }
        public static DataTable MergeDataTables(List<DataTable> tables)
        {
            if (tables == null || tables.Count == 0)
                return new DataTable();

            DataTable mergedTable = tables[0].Clone();

            foreach (DataTable table in tables)
            {
                if (table != null)
                {
                    mergedTable.Merge(table);
                }
            }

            return mergedTable;
        }

        public Task Execute(IJobExecutionContext context)
        {
            ExcelDealWith();
            return Task.CompletedTask;
        }
    }
}
