using AutoTurnOver.Models;
using AutoTurnOver.Models.ApiDto;
using AutoTurnOver.Models.Report;
using AutoTurnOver.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

namespace AutoTurnOver.Services
{
    /// <summary>
    /// 在途
    /// </summary>
    public class DailyServices
    {
      

        /// <summary>
        /// 查询采购在途数据
        /// </summary>
        /// <param name="sku">sku</param>
        /// <param name="warehouse_code">仓库编码</param>
        /// <returns></returns>
        public IEnumerable<dc_purchase_daily_dto> List(string sku, string warehouse_code)
        {
            return DB.daily.List(sku, warehouse_code);
        }

        /// <summary>
        /// 查询调拨在途数据
        /// </summary>
        /// <param name="sku">sku</param>
        /// <param name="warehouse_code">仓库编码</param>
        /// <returns></returns>
        public IEnumerable<dc_transfer_daily_dto> TransferList(string sku, string warehouse_code)
        {
            return DB.daily.TransferList(sku, warehouse_code);
        }
        

        public List<dc_base_stock_dto> RealtimeList(dc_base_stock_search_dto search_data,ref int total)
        {
            List<bailun_category_new_dto> categoryModels = null;
            if (!string.IsNullOrWhiteSpace(search_data.categoryIds))
            {
                categoryModels = ApiServices.GetNewClientNodesByIds(search_data.categoryIds.Split(',').Select(s => int.Parse(s)).ToList());
            }
            return DB.daily.RealtimeList(search_data, categoryModels, ref total);
        }
        public List<dc_report_gmv_extend> GetGmvList(dc_report_gmv_request_dto search_data)
        {
            return DB.daily.GetGmvList(search_data);
        }
        public List<full_link_purchase_dto> FullLinkPurchaseList(dc_base_stock_search_dto search_data,ref int total)
        {
            List<bailun_category_new_dto> categoryModels = null;
            if (!string.IsNullOrWhiteSpace(search_data.categoryIds))
            {
                categoryModels = ApiServices.GetNewClientNodesByIds(search_data.categoryIds.Split(',').Select(s => int.Parse(s)).ToList());
            }
            return DB.daily.FullLinkPurchaseList(search_data, categoryModels, ref total);
        }
        public List<order_transfer_full_link_dto> FullLinkTransferList(dc_base_stock_search_dto search_data,ref int total)
        {
            List<bailun_category_new_dto> categoryModels = null;
            if (!string.IsNullOrWhiteSpace(search_data.categoryIds))
            {
                categoryModels = ApiServices.GetNewClientNodesByIds(search_data.categoryIds.Split(',').Select(s => int.Parse(s)).ToList());
            }
            return DB.daily.FullLinkTransferList(search_data, categoryModels, ref total);
        }

        /// <summary>
        /// 全链路在途订单
        /// </summary>
        /// <param name="search_data"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_full_link_wait_order_dto> FullLinkWaitPage(dc_base_full_link_search_dto search_data, ref int total)
        {
            List<bailun_category_new_dto> categoryModels = null;
            if (!string.IsNullOrWhiteSpace(search_data.categoryIds))
            {
                categoryModels = ApiServices.GetNewClientNodesByIds(search_data.categoryIds.Split(',').Select(s => int.Parse(s)).ToList());
            }
            return DB.dc_base_full_link_wait_order_dao.FullLinkWaitPage(search_data, categoryModels, ref total);
        }
        public List<dc_base_trans_temp_schedule_dto> TempTransferList(temp_transfer_order_search_dto search_data,ref int total)
        {
            return DB.daily.TempTransferList(search_data, ref total);
        }

        public List<dc_base_stock_fba_dto> RealtimeFbaList(dc_base_stock_search_dto search_data,ref int total)
        {
            List<bailun_category_new_dto> categoryModels = null;
            if (!string.IsNullOrWhiteSpace(search_data.categoryIds))
            {
                categoryModels = ApiServices.GetNewClientNodesByIds(search_data.categoryIds.Split(',').Select(s => int.Parse(s)).ToList());
            }
            return DB.daily.RealtimeFbaList(search_data, categoryModels, ref total);
        }

        public List<dc_auto_shortage_push_route_dto> ShortagePushList(string platform, string bailun_sku, int offset, int limit, ref int total, DateTime? start_date, DateTime? end_date, string warehousecode, string warehousetype, int? warehousearea,int type=0)
        {
            return DB.daily.ShortagePushList(platform, bailun_sku, offset, limit,ref total, start_date, end_date, warehousecode, warehousetype, warehousearea,type);
        }
        
        public List<dc_aims_transfer_warehouse_log_dto> TransferWarehouseLogList(dc_aims_transfer_warehouse_log_search_dto search_data, int offset, int limit, ref int total )
        {
            return DB.dc_aims_transfer_warehouse_dao.LogList(search_data, offset, limit,ref total);
        }
        
        public List<dc_task_download_dto> TaskDownloadList(string user_name, string task_name, int offset, int limit, ref int total, DateTime? start_date, DateTime? end_date)
        {
            return DB.daily.TaskDownloadList(user_name, task_name, offset, limit,ref total, start_date, end_date);
        }

        public string ExportShortagePush(export_sortage_push_search_dto searchData, out int orows)
        {
            try
            {
                var fileName = AppContext.BaseDirectory + $@"改在线数据-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int page = 1;
                int rows = 50000;
                orows = 0;
                while (true)
                {
                    int total = 0;
                    var list = ShortagePushList(searchData.platform, searchData.bailun_sku, (page-1)* rows, rows, ref total, searchData.start_date, searchData.end_date, searchData.warehousecode, searchData.warehousetype, searchData.warehousearea);

                    if (list == null || list.Count <= 0) break;
                    orows += list.Count();
                    DataTable table = new DataTable();
                    string[] cols = new string[] { "仓库编码","仓库名称", "sku", "平台","改0 推送时间", "补货推送时间" };
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                        row["仓库编码"] = itemData.warehouse_code;
                        row["仓库名称"] = itemData.warehouse_name;
                        row["sku"] = itemData.bailun_sku;
                        row["平台"] = itemData.platform;
                        row["改0 推送时间"] = itemData.push_date;
                        row["补货推送时间"] = itemData.push_time;
                        table.Rows.Add(row);
                    }

                    CsvFileHelper.SaveCSV(table, fileName, page == 1);
                    page++;
                }


                return fileName;
                //var memory = new MemoryStream();
                //using (var stream = new FileStream(fileName, FileMode.Open))
                //{
                //    stream.CopyTo(memory);
                //}
                //memory.Position = 0;
                //return memory;
            }
            catch (Exception)
            {
                throw;
            }

        }
        public string ExportTransferWarehouseLog(dc_aims_transfer_warehouse_log_search_dto searchData)
        {
            try
            {
                var fileName = AppContext.BaseDirectory + $@"转仓日志-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int page = 1;
                int rows = 50000;

                while (true)
                {
                    int total = 0;
                    var list = TransferWarehouseLogList(searchData, (page-1)* rows, rows, ref total);

                    if (list == null || list.Count <= 0) break;

                    DataTable table = new DataTable();
                    string[] cols = new string[] { "来源仓库编码", "来源仓库名称", "目的仓库编码", "目的仓库名称", "sku","状态","备注", "操作时间", "操作人" };
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                        row["来源仓库编码"] = itemData.from_warehouse_code;
                        row["来源仓库名称"] = itemData.from_warehouse_name;
                        row["目的仓库编码"] = itemData.to_warehouse_code;
                        row["目的仓库名称"] = itemData.to_warehouse_name;
                        row["sku"] = itemData.bailun_sku;
                        row["状态"] = itemData.status_str;
                        row["备注"] = itemData.error_message;
                        row["操作时间"] = itemData.create_date;
                        row["操作人"] = itemData.create_user;
                        table.Rows.Add(row);
                    }

                    CsvFileHelper.SaveCSV(table, fileName, page == 1);
                    page++;
                }


                return fileName;
                //var memory = new MemoryStream();
                //using (var stream = new FileStream(fileName, FileMode.Open))
                //{
                //    stream.CopyTo(memory);
                //}
                //memory.Position = 0;
                //return memory;
            }
            catch (Exception)
            {
                throw;
            }

        }


        /// <summary>
        /// 在途数据
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehouse_code"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public List<dc_estimated_arrival_dto> EstimatedArrivalList(string sku, string warehouse_code, int index)
        {
            return DB.daily.EstimatedArrivalList(sku, warehouse_code, index);
        }

        /// <summary>
        /// 缺货订单
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehouse_code"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public IEnumerable<dc_base_oms_sku_dto> OutOfStockOrderList(string sku, string warehouse_code)
        {
            return DB.daily.OutOfStockOrderList(sku, warehouse_code);
        }


        private static int export_count = 0;
        public string Export(dc_base_stock_search_dto search_data, out int orows)
        {
            try
            {
                export_count++;
                var services = new DailyServices();
                var fileName = AppContext.BaseDirectory + $@"实时库存-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int page = 1;
                int rows = 50000;
                orows = 0;
                if (export_count == 1)
                {
                    rows = 250000;
                }

                while (true)
                {
                    int total = 0;
                    search_data.offset = (page - 1)* rows;
                    search_data.limit = rows;
                    var list = services.RealtimeList(search_data,ref total);

                    if (list == null || list.Count <= 0) break;
                    orows += list.Count();
                    DataTable table = new DataTable();
                    string[] cols = new string[] { "百伦简易分类","Sku", "采购名称", "中文名","内部编码", "仓库编码", "仓库名称", "货主编码","实时采购在途",
                       "实时调拨在途(总)","实时调拨在途(调拨单)","实时调拨在途(采购临时)","实时调拨在途(暂存)"
                        ,"在途金额"
                ,"订货数量","运输在途","中转仓库存","冻结库存","供应商库存","预售库存","不良品库存","在途库存","收货待检"
                 ,"待上架","可配库存","在途+可配库存(总)","上周销量","上周销售额","入库数量","可配库存金额","销售可用库存(聚合)","销售可用库存(私有)","销售可用库存(共享)","在仓库存(共享)","在仓库存(私有)","在仓库存(聚合)","仓库占用(共享)"
                  ,"仓库占用(私有)","仓库占用(聚合)","活动占用","单占用(私有)","订单占用(共享)","订单占用(聚合)","环球更新时间","供应商","采购员","重量","单价","已发货库存","实时缺货","是否侵权",
                  "过去7日日均销量", "过去14日日均销量", "过去30日日均销量", "过去7日Eaby日均销量", "过去14日Eaby日均销量", "过去30日Eaby日均销量", "过去7日速卖通日均销量", "过去14日速卖通日均销量", "过去30日速卖通日均销量",
                        "监控状态","开发时间","昨日销量","停售状态","amazon最近7天日均销量","amazon最近14天日均销量","amazon最近30天日均销量","moq","品牌","标签","类型","产品尺寸","包装尺寸","安全库存","销售员","海外仓入库天数",
                        "采购陆运在途","采购海运在途","采购空运在途","采购铁路在途","调拨陆运在途","调拨海运在途","调拨空运在途","调拨铁路在途",
                        "调拨最快到货时间","调拨最快到货单号","调拨最快到货数量","调拨最快到货跟踪号","调拨最快到货运输方式","调拨最快到到货物流","周转表更新时间",
                        "供应链长度天数","供应链预测销量","供应链预测缺货","供应链预测冗余","walmart最近7天日均销量","walmart最近14天日均销量","walmart最近30天日均销量","库存更新时间",
                        "shopify最近7天日均销量", "shopify最近14天日均销量", "shopify最近30天日均销量",
                        "在库+调拨单在途数量","在库+调拨单在途金额","在库+在途金额(总)","产品线",
                        "头程费/一个单位","头程费/kg","产品特性","最近7天的订单数量","清货状态"
            };
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                        row["产品特性"] = itemData.character_names==null?"" : itemData.character_names.Replace(","," | ");
                        row["头程费/一个单位"] = itemData.cost_first;

                        row["最近7天的订单数量"] = itemData.orders_7;
                        row["头程费/kg"] = itemData.cost_first_weight;
                        row["产品线"] = itemData.product_line_name;
                        row["在库+调拨单在途数量"] = itemData.sum_actual_transfer_stock;
                        row["在库+调拨单在途金额"] = itemData.sum_actual_transfer_amount;
                        row["在库+在途金额(总)"] = itemData.sum_actual_stock_amount;
                        row["在途+可配库存(总)"] = itemData.sum_actual_stock;

                        row["walmart最近7天日均销量"] = itemData.history_sevenday_sales_walmart;
                        row["walmart最近14天日均销量"] = itemData.history_fourteenday_sales_walmart;
                        row["walmart最近30天日均销量"] = itemData.history_thirtyday_sales_walmart;

                        row["shopify最近7天日均销量"] = itemData.history_sevenday_sales_shopify;
                        row["shopify最近14天日均销量"] = itemData.history_fourteenday_sales_shopify;
                        row["shopify最近30天日均销量"] = itemData.history_thirtyday_sales_shopify;

                        row["供应链长度天数"] = itemData.turnover_days;
                        row["供应链预测销量"] = itemData.turnover_days_quantity;
                        row["供应链预测缺货"] = itemData.turnover_days_outofstock_quantity;
                        row["供应链预测冗余"] = itemData.turnover_days_redundancy_quantity;

                        row["调拨最快到货时间"] = itemData.lately_transfer_expect_arrival_time == null ? "" : itemData.lately_transfer_expect_arrival_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["调拨最快到货单号"] = itemData.lately_transfer_order_no;
                        row["调拨最快到货数量"] = itemData.lately_transfer_count;
                        row["调拨最快到货跟踪号"] = itemData.lately_transfer_trackingno;
                        row["调拨最快到货运输方式"] = itemData.lately_transfer_transporttype;
                        row["调拨最快到到货物流"] = itemData.lately_transfer_logisticsname;

                        row["采购陆运在途"] = itemData.quantity_land_purchase;
                        row["采购海运在途"] = itemData.quantity_ocean_purchase;
                        row["采购空运在途"] = itemData.quantity_air_purchase;
                        row["采购铁路在途"] = itemData.quantity_railway_purchase;
                        row["调拨陆运在途"] = itemData.quantity_land_transfer;
                        row["调拨海运在途"] = itemData.quantity_ocean_transfer;
                        row["调拨空运在途"] = itemData.quantity_air_transfer;
                        row["调拨铁路在途"] = itemData.quantity_railway_transfer;


                        row["百伦简易分类"] = itemData.category_simple_name;
                        row["海外仓入库天数"] = itemData.abroad_inbound_delivery;
                        row["Sku"] = itemData.bailun_sku;
                        row["入库数量"] = itemData.storage_quantity;
                        row["采购名称"] = itemData.buyer_name;
                        row["中文名"] = itemData.base_sku_name;
                        //row["英文名称"] = itemData.sku_title_en;
                        row["内部编码"] = itemData.sku_product_inner_code;
                        row["仓库编码"] = itemData.warehouse_code;
                        row["仓库名称"] = itemData.warehouse_name;
                        row["货主编码"] = itemData.owner_code;
                        row["订货数量"] = itemData.quantity_reservation;
                        row["运输在途"] = itemData.quantity_transport;
                        row["中转仓库存"] = itemData.quantity_transfer;
                        row["冻结库存"] = itemData.quantity_freeze;
                        row["供应商库存"] = itemData.quantity_supplier;
                        row["预售库存"] = itemData.quantity_presell;
                        row["不良品库存"] = itemData.quantity_defective;
                        row["在途库存"] = itemData.quantity_transit;
                        row["收货待检"] = itemData.wait_check;
                        row["待上架"] = itemData.wait_putaway;
                        row["可配库存"] = itemData.usable_stock;
                        
                        row["可配库存金额"] = itemData.usable_stock_amount;
                        row["销售可用库存(聚合)"] = itemData.usable_sales;
                        row["销售可用库存(私有)"] = itemData.usable_sales_private;
                        row["销售可用库存(共享)"] = itemData.usable_sales_share;
                        row["在仓库存(共享)"] = itemData.in_warehouse_share;
                        row["在仓库存(私有)"] = itemData.in_warehouse_private;
                        row["在仓库存(聚合)"] = itemData.in_warehouse;
                        row["仓库占用(共享)"] = itemData.occupy_stock_share;
                        row["仓库占用(私有)"] = itemData.occupy_stock_private;
                        row["仓库占用(聚合)"] = itemData.occupy_stock;
                        row["活动占用"] = itemData.occupy_activity;
                        row["单占用(私有)"] = itemData.occupy_order_private;
                        row["订单占用(共享)"] = itemData.occupy_order;
                        row["订单占用(聚合)"] = itemData.occupy_order_share;
                        row["环球更新时间"] = itemData.update_time;

                        row["实时采购在途"] = itemData.realtime_quantity_purchase;

                        row["实时调拨在途(总)"] = itemData.realtime_quantity_transfer;
                        row["实时调拨在途(调拨单)"] = itemData.quantity_transfer_order;
                        row["实时调拨在途(采购临时)"] = itemData.quantity_transfer_temp_schedule;
                        row["实时调拨在途(暂存)"] = itemData.quantity_transfer_temporary_storage;

                        row["在途金额"] = itemData.on_the_way_stock_amount;
                        row["供应商"] = itemData.suppliers_name;
                        row["采购员"] = itemData.buyer_name;
                        row["重量"] = itemData.weight;
                        row["单价"] = itemData.unit_price;
                        row["已发货库存"] = itemData.shipped_stock;
                        row["实时缺货"] = itemData.quantity_out_stock;
                        row["是否侵权"] = itemData.has_tort;

                        row["过去7日日均销量"] = itemData.history_sevenday_sales;
                        row["过去14日日均销量"] = itemData.history_fourteenday_sales;
                        row["过去30日日均销量"] = itemData.history_thirtyday_sales;
                        row["过去7日Eaby日均销量"] = itemData.history_sevenday_sales_ebay;
                        row["过去14日Eaby日均销量"] = itemData.history_fourteenday_sales_ebay;
                        row["过去30日Eaby日均销量"] = itemData.history_thirtyday_sales_ebay;
                        row["过去7日速卖通日均销量"] = itemData.history_sevenday_sales_aliexpress;
                        row["过去14日速卖通日均销量"] = itemData.history_fourteenday_sales_aliexpress;
                        row["过去30日速卖通日均销量"] = itemData.history_thirtyday_sales_aliexpress;
                        row["amazon最近7天日均销量"] = itemData.history_sevenday_sales_amazon;
                        row["amazon最近14天日均销量"] = itemData.history_fourteenday_sales_amazon;
                        row["amazon最近30天日均销量"] = itemData.history_thirtyday_sales_amazon;
                        row["监控状态"] = itemData.monitor_status == 0 ? "监控中" : "停止监控";
                        row["清货状态"] = itemData.clearance_status == 0 ? "" : "清货";
                        row["开发时间"] = itemData.develop_time == null ? "" : itemData.develop_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["昨日销量"] = itemData.oneday_sales;

                        row["停售状态"] = itemData.sku_status_str;
                        row["moq"] = itemData.moq;
                        row["品牌"] = itemData.brand;
                        row["标签"] = itemData.tags;
                        row["类型"] = itemData.product_type_desc;
                        row["产品尺寸"] = itemData.product_size;
                        
                        row["包装尺寸"] = $"{itemData.pack_length}-{itemData.pack_width}-{itemData.pack_height}";
                        row["安全库存"] = itemData.real_quantity_safe_inventory;
                        row["上周销量"] = itemData.lastweek_sales;
                        row["上周销售额"] = itemData.lastweek_sales_amount;
                        row["销售员"] = itemData.extend_sale_user_name;

                        row["周转表更新时间"] = itemData.turnover_gmt_modified == null ? "" : itemData.turnover_gmt_modified.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["库存更新时间"] = itemData.gmt_modified.ToString("yyyy-MM-dd HH:mm:ss");
                        table.Rows.Add(row);
                    } 

                    CsvFileHelper.SaveCSV(table, fileName, page == 1);
                    page++;
                }



                return fileName;
            }
            catch (Exception)
            {
                export_count--;
                throw;
            }
           
        }
        
        public string FbaExport(dc_base_stock_search_dto search_data, out int orows)
        {
            try
            {
                export_count++;
                var services = new DailyServices();
                var fileName = AppContext.BaseDirectory + $@"Fba实时库存-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int page = 1;
                int rows = 50000;
                orows = 0;
                if (export_count == 1)
                {
                    rows = 250000;
                }

                while (true)
                {
                    int total = 0;
                    search_data.offset = (page - 1)* rows;
                    search_data.limit = rows;
                    var list = services.RealtimeFbaList(search_data,ref total);

                    if (list == null || list.Count <= 0) break;
                    orows += list.Count();
                    DataTable table = new DataTable();
                    string[] cols = new string[] { "账号","站点","asin","仓库sku","产品类型","分组名称","销售名称","产品名称"
                        ,"昨日review分数","昨日reivew个数","仓库编码","仓库名称","国家"
                        ,"昨日销量","昨日销售额USD","近7天销量","近7天销售额USD","近30天销量","近30天销售额USD","1月销售额","2月销售额","1月销量","2月销量",
                        "监控状态","采购员","采购价","重量"
                        ,"实时采购在途","实时调拨在途(总)","实时调拨在途(调拨单)","实时调拨在途(采购临时)","实时调拨在途(暂存)","总在途数","广州01仓可用库存","广州02仓可用库存","FBA 可售库存"
                        ,"在途金额","可配库存金额","在途+可配总库存",
                        "采购陆运在途","采购海运在途","采购空运在途","采购铁路在途","调拨陆运在途","调拨海运在途","调拨空运在途","调拨铁路在途",
                        "调拨最快到货时间","调拨最快到货单号","调拨最快到货数量","调拨最快到货跟踪号","调拨最快到货运输方式","调拨最快到到货物流"
                        

            };
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                        row["1月销售额"] = itemData.amount_sales_usd_month_1;
                        row["2月销售额"] = itemData.amount_sales_usd_month_2;
                        row["1月销量"] = itemData.bailun_sku_quantity_ordered_month_1;
                        row["2月销量"] = itemData.bailun_sku_quantity_ordered_month_2;

                        row["调拨最快到货时间"] = itemData.lately_transfer_expect_arrival_time == null ? "" : itemData.lately_transfer_expect_arrival_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["调拨最快到货单号"] = itemData.lately_transfer_order_no;
                        row["调拨最快到货数量"] = itemData.lately_transfer_count;
                        row["调拨最快到货跟踪号"] = itemData.lately_transfer_trackingno;
                        row["调拨最快到货运输方式"] = itemData.lately_transfer_transporttype;
                        row["调拨最快到到货物流"] = itemData.lately_transfer_logisticsname;

                        row["昨日review分数"] = itemData.review_score;
                        row["昨日reivew个数"] = itemData.review_count;

                        row["采购陆运在途"] = itemData.quantity_land_purchase;
                        row["采购海运在途"] = itemData.quantity_ocean_purchase;
                        row["采购空运在途"] = itemData.quantity_air_purchase;
                        row["采购铁路在途"] = itemData.quantity_railway_purchase;
                        row["调拨陆运在途"] = itemData.quantity_land_transfer;
                        row["调拨海运在途"] = itemData.quantity_ocean_transfer;
                        row["调拨空运在途"] = itemData.quantity_air_transfer;
                        row["调拨铁路在途"] = itemData.quantity_railway_transfer;

                        row["账号"] = itemData.bailun_account;
                        row["站点"] = itemData.web_site;
                        row["asin"] = itemData.asin;
                        row["仓库sku"] = itemData.bailun_sku;
                        row["产品类型"] = itemData.product_type;
                        row["分组名称"] = itemData.group_name;
                        row["销售名称"] = itemData.sale_name;
                        row["产品名称"] = itemData.sku_title_cn;
                        row["仓库编码"] = itemData.warehouse_code;
                        row["仓库名称"] = itemData.warehouse_name;
                        row["国家"] = itemData.area_name;
                        row["昨日销量"] = itemData.bailun_sku_quantity_ordered_1;
                        row["昨日销售额USD"] = itemData.amount_sales_usd_1;
                        row["近7天销量"] = itemData.bailun_sku_quantity_ordered_7;
                        row["近7天销售额USD"] = itemData.amount_sales_usd_7;
                        row["近30天销量"] = itemData.bailun_sku_quantity_ordered_30;
                        row["近30天销售额USD"] = itemData.amount_sales_usd_30;
                        row["监控状态"] = itemData.monitor_status == 0 ? "监控中" : "停止监控";
                        row["采购员"] = itemData.buyer_name;
                        row["采购价"] = itemData.unit_price;
                        row["重量"] = itemData.weight;
                        row["实时采购在途"] = itemData.quantity_purchase;
                        row["实时调拨在途(总)"] = itemData.quantity_transfer;
                        row["实时调拨在途(调拨单)"] = itemData.quantity_transfer_order;
                        row["实时调拨在途(采购临时)"] = itemData.quantity_transfer_temp_schedule;
                        row["实时调拨在途(暂存)"] = itemData.quantity_transfer_temporary_storage;
                        row["总在途数"] = itemData.sum_mid;
                        row["广州01仓可用库存"] = itemData.usable_stock_01;
                        row["广州02仓可用库存"] = itemData.usable_stock_02;
                        row["FBA 可售库存"] = itemData.usable_stock;
                        row["在途金额"] = itemData.sum_mid_amount;
                        row["可配库存金额"] = itemData.usable_stock_amount;
                        row["在途+可配总库存"] = itemData.sum_stock;

                       
                        table.Rows.Add(row);
                    }

                    CsvFileHelper.SaveCSV(table, fileName, page == 1);
                    page++;
                }



                return fileName;
            }
            catch (Exception)
            {
                export_count--;
                throw;
            }
           
        }
        
        public string FullLinkPurchaseExport(dc_base_stock_search_dto search_data)
        {
            try
            {
                export_count++;
                var services = new DailyServices();
                var fileName = AppContext.BaseDirectory + $@"供应链采购在途-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int page = 1;
                int rows = 50000;
                if (export_count == 1)
                {
                    rows = 250000;
                }

                while (true)
                {
                    int total = 0;
                    search_data.offset = (page - 1)* rows;
                    search_data.limit = rows;
                    var list = services.FullLinkPurchaseList(search_data,ref total);

                    if (list == null || list.Count <= 0) break;

                    DataTable table = new DataTable();
                    string[] cols = new string[] { "仓库名称","仓库编码","产品编码","产品名称","可用库存","采购在途数","调拨在途数","暂存区数","临时在途数","调拨单在途数"
                        ,"商品来源","采购员","过去7天日均","过去14天日均","过去30天日均","sku状态"
                        ,"采购单号","采购数量","采购单状态","预计到货时间","最后签收时间","已到货数量","已入库数量","生产分配状态","待分配生产数","已分配生产数","已生产数"

            };
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                       
                        row["仓库名称"] = itemData.warehouse_name;
                        row["仓库编码"] = itemData.warehouse_code;
                        row["产品编码"] = itemData.bailun_sku;
                        row["产品名称"] = itemData.product_title;
                        row["可用库存"] = itemData.stock;
                        row["采购在途数"] = itemData.quantity_not_inbound;
                        row["调拨在途数"] = itemData.quantity_transfer;
                        row["暂存区数"] = itemData.quantity_transfer_temporary_storage;
                        row["临时在途数"] = itemData.quantity_transfer_temp_schedule;
                        row["调拨单在途数"] = itemData.quantity_transfer_order;

                        row["商品来源"] = itemData.product_type_desc;
                        row["采购员"] = itemData.buyer_name;
                        row["过去7天日均"] = itemData.history_sevenday_sales;
                        row["过去14天日均"] = itemData.history_fourteenday_sales;
                        row["过去30天日均"] = itemData.history_thirtyday_sales;
                        row["sku状态"] = itemData.forecast_type_str;

                        row["采购单号"] = itemData.purchase_id;
                        row["采购数量"] = itemData.quantity_purchase;
                        row["采购单状态"] = itemData.purchase_status_str;
                        row["预计到货时间"] = itemData.purchase_arrivaldate;
                        row["最后签收时间"] = itemData.last_signtime == null ? "" : itemData.last_signtime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["已到货数量"] = itemData.quantity_arrival;
                        row["已入库数量"] = itemData.quantity_inbound;
                        row["生产分配状态"] = itemData.prod_status;
                        row["待分配生产数"] = itemData.prod_not_distribution_quantity;
                        row["已分配生产数"] = itemData.prod_distribution_quantity;
                        row["已生产数"] = itemData.prod_quantity;

                        table.Rows.Add(row);
                    }

                    CsvFileHelper.SaveCSV(table, fileName, page == 1);
                    page++;
                }



                return fileName;
            }
            catch (Exception)
            {
                export_count--;
                throw;
            }
           
        }
        
        public string FullLinkTransferExport(dc_base_stock_search_dto search_data)
        {
            try
            {
                export_count++;
                var services = new DailyServices();
                var fileName = AppContext.BaseDirectory + $@"供应链调拨在途-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int page = 1;
                int rows = 50000;
                if (export_count == 1)
                {
                    rows = 250000;
                }

                while (true)
                {
                    int total = 0;
                    search_data.offset = (page - 1)* rows;
                    search_data.limit = rows;
                    var list = services.FullLinkTransferList(search_data,ref total);

                    if (list == null || list.Count <= 0) break;

                    DataTable table = new DataTable();
                    string[] cols = new string[] { "产品编码", "仓库名称","仓库编码","中文信息","可用库存","调拨单在途数","箱子在途数","过去7天日均","过去14天日均","过去30天日均",
                        "商品来源",   "采购员", "sku状态", "对应采购单", "调拨单号",
                        "物流跟踪号",  "物流转单号","头程方式","调拨单状态","物流渠道","物流渠道编码","物流节点状态","物流节点时间","物流异常","目标到货","预计到货","实际签收","实际入库"
};
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                       
                        row["产品编码"] = itemData.sku;
                        row["仓库名称"] = itemData.warehouse_name;
                        row["仓库编码"] = itemData.warehouse_code;
                        row["中文信息"] = itemData.sku_name;
                        row["可用库存"] = itemData.stock;
                        row["调拨单在途数"] = itemData.not_storage;
                        row["箱子在途数"] = itemData.box_not_storage;
                        row["过去7天日均"] = itemData.history_sevenday_sales;
                        row["过去14天日均"] = itemData.history_fourteenday_sales;
                        row["过去30天日均"] = itemData.history_thirtyday_sales;
                        row["商品来源"] = itemData.product_type_desc;
                        row["采购员"] = itemData.buyer_name;
                        row["sku状态"] = itemData.forecast_type_str;
                        row["调拨单号"] = itemData.order_no;
                        row["物流跟踪号"] = itemData.trackingno;
                        row["物流转单号"] = itemData.transfer_no;
                        row["头程方式"] = itemData.transporttype;
                        row["调拨单状态"] = itemData.state_str;
                        row["物流渠道"] = itemData.logistics_name;
                        row["物流渠道编码"] = itemData.logistics_code;
                        row["物流节点状态"] = itemData.node_name;
                        row["物流节点时间"] = itemData.node_date;
                        row["物流异常"] = itemData.sign_exe==1?"有异常":"无异常";
                        row["目标到货"] = itemData.expectarrivaltime==null ? "" : itemData.expectarrivaltime.Value.ToString("yyyy-MM-dd HH:mm:ss"); 
                        row["预计到货"] = itemData.node_expectarrivaltime==null ? "" : itemData.node_expectarrivaltime.Value.ToString("yyyy-MM-dd HH:mm:ss");

                        row["对应采购单"] = itemData.purchasecode;
                        row["实际签收"] = itemData.sign_time==null ? "" : itemData.sign_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际入库"] = itemData.put_time == null ? "" : itemData.put_time.Value.ToString("yyyy-MM-dd HH:mm:ss");


                        table.Rows.Add(row);
                    }

                    CsvFileHelper.SaveCSV(table, fileName, page == 1);
                    page++;
                }



                return fileName;
            }
            catch (Exception)
            {
                export_count--;
                throw;
            }
           
        }
        public string FullLinkWaitExport(dc_base_full_link_search_dto search_data)
        {
            try
            {
                export_count++;
                var services = new DailyServices();
                var fileName = AppContext.BaseDirectory + $@"全链路在途订单-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int page = 1;
                int rows = 50000;
                if (export_count == 1)
                {
                    rows = 250000;
                }

                while (true)
                {
                    int total = 0;
                    search_data.offset = (page - 1)* rows;
                    search_data.limit = rows;
                    var list = services.FullLinkWaitPage(search_data,ref total);

                    if (list == null || list.Count <= 0) break;

                    DataTable table = new DataTable();
                    string[] cols = new string[] { "产品编码", "仓库名称","仓库编码","中文信息","可用库存","过去7天日均","过去14天日均","过去30天日均",
                        "商品来源",   "采购员", "sku状态",
                        "采购单号","采购数量","采购在途数量","采购下单时间","采购预计到货时间","采购签收时间","采购签收数量","采购入库时间","采购入库数量",
                        "采购临时单号","采购临时数量","调拨暂存单号","调拨暂存数量","调拨计划单号","调拨计划数量",
                        "调拨单号", "调拨数量","调拨在途数量", "物流跟踪号",  "物流转单号","头程方式","物流渠道","物流渠道编码","物流节点状态","物流节点时间","调拨目标到货","调拨预计到货"
                        ,"实际揽收","实际上网","实际开船","实际上航","实际转运","实际到港","实际清关","实际签收","实际入库"
};
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                        row["实际入库"] = itemData.lms_put_time == null ? "" : itemData.lms_put_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际签收"] = itemData.lms_sign_time == null ? "" : itemData.lms_sign_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际清关"] = itemData.lms_collect_time == null ? "" : itemData.lms_collect_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际到港"] = itemData.lms_arrival_time == null ? "" : itemData.lms_arrival_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际转运"] = itemData.lms_transport_time == null ? "" : itemData.lms_transport_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际上航"] = itemData.lms_flight_time == null ? "" : itemData.lms_flight_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际开船"] = itemData.lms_sail_time == null ? "" : itemData.lms_sail_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际上网"] = itemData.lms_ascan_time == null ? "" : itemData.lms_ascan_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["实际揽收"] = itemData.lms_collect_time == null ? "" : itemData.lms_collect_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["调拨预计到货"] = itemData.lms_expectarrivaltime == null ? "" : itemData.lms_expectarrivaltime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["调拨目标到货"] = itemData.transfer_expectarrivaltime == null ? "" : itemData.transfer_expectarrivaltime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["物流节点时间"] = itemData.lms_node_date == null ? "" : itemData.lms_node_date.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["物流节点状态"] = itemData.lms_node_name;
                        row["物流渠道编码"] = itemData.transfer_logistics_code;
                        row["物流渠道"] = itemData.transfer_logistics_name;
                        row["头程方式"] = itemData.transfer_transporttype;
                        row["物流转单号"] = itemData.lms_transfer_no;
                        row["物流跟踪号"] = itemData.lms_trackingno;
                        row["调拨在途数量"] = itemData.transfer_quantity_not_inbound;
                        row["调拨数量"] = itemData.transfer_quantity;
                        row["调拨单号"] = itemData.transfer_no;
                        row["调拨计划数量"] = itemData.transfer_plan_quantity;
                        row["调拨计划单号"] = itemData.transfer_plan_no;
                        row["调拨暂存数量"] = itemData.transfer_temp_schedule_quantity;
                        row["调拨暂存单号"] = itemData.transfer_temp_schedule_no;
                        row["采购临时数量"] = itemData.transfer_temp_purchase_quantity;
                        row["采购临时单号"] = itemData.transfer_temp_purchase_no;
                        row["采购入库数量"] = itemData.purchase_quantity_inbound;
                        row["采购入库时间"] = itemData.purchase_put_time == null ? "" : itemData.purchase_put_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["采购签收数量"] = itemData.purchase_quantity_arrival;
                        row["采购签收时间"] = itemData.purchase_sign_time == null ? "" : itemData.purchase_sign_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["采购预计到货时间"] = itemData.purchase_arrivaldate == null ? "" : itemData.purchase_arrivaldate.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["采购下单时间"] = itemData.purchase_create_time == null ? "" : itemData.purchase_create_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        row["采购在途数量"] = itemData.purchase_quantity_not_inbound;
                        row["采购数量"] = itemData.purchase_quantity;
                        row["采购单号"] = itemData.purchase_no;
                        row["sku状态"] = itemData.forecast_type_str;
                        row["采购员"] = itemData.buyer_name;
                        row["商品来源"] = itemData.product_type_desc;
                        row["过去30天日均"] = itemData.history_thirtyday_sales;
                        row["过去14天日均"] = itemData.history_fourteenday_sales;
                        row["过去7天日均"] = itemData.history_sevenday_sales;
                        row["可用库存"] = itemData.stock;
                        row["中文信息"] = itemData.product_title;
                        row["仓库编码"] = itemData.warehouse_code;
                        row["仓库名称"] = itemData.warehouse_name;
                        row["产品编码"] = itemData.bailun_sku;
                        table.Rows.Add(row);
                    }

                    CsvFileHelper.SaveCSV(table, fileName, page == 1);
                    page++;
                }



                return fileName;
            }
            catch (Exception)
            {
                export_count--;
                throw;
            }
           
        }

        public async void GenerateData()
        {
            try
            {
               //var  total = 0;
               // var memory = Export(new UserData { UserAccount = "admin" },null, null, null, null, null, 0, 0, ref total, "国内仓", null);
               // var fileData = await QiNiuCloudHelper.UploadAsync(memory, $"stock_{DateTime.Now.ToString("yyyyMMddHmmss")}.csv");
               // ApiServices.QiYeJiQiRenMsPush(new QiYeJiQiRenMsDto { msgtype = "text", text = new QiYeJiQiRenMsDto.text_dto { content = "国内仓实时库存：" + fileData } });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


        }

        public IEnumerable<product_api_dto> GetSkus(string skus)
        {
            return DB.daily.GetSkus(skus);
        }
        
        public IEnumerable<product_type_dto> GetProductTypeList()
        {
            return DB.daily.GetProductTypeList();
        }
    }
}
