using AutoTurnOver.Models;
using AutoTurnOver.Models.ApiDto;
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(int? monitor_status,int? searchType, string key_words, string warehouse_code,string supplier_name, int offset, int limit, ref int total, string warehousetype, int? warehousearea,bool isSum = false,string order = null,string sort = null,int? has_tort  = null,string categoryIds = null,string buyer_name = null,
             DateTime? start_date = null, DateTime? end_date = null, DateTime? f_start_date = null, DateTime? f_end_date = null,int? product_type = null, bool is_warehouse_sum = false)
        {
            List<bailun_category_new_dto> categoryModels = null;
            if (!string.IsNullOrWhiteSpace(categoryIds))
            {
                categoryModels = ApiServices.GetNewClientNodesByIds(categoryIds.Split(',').Select(s => int.Parse(s)).ToList());
            }
            return DB.daily.RealtimeList(monitor_status, searchType, key_words, warehouse_code, supplier_name, offset, limit, ref total,warehousetype,warehousearea, isSum, order, sort, has_tort:has_tort, categoryModels: categoryModels, buyer_name:buyer_name, start_date: start_date, end_date: end_date, f_start_date: f_start_date, f_end_date: f_end_date, product_type: product_type, is_warehouse_sum);
        }

        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)
        {
            return DB.daily.ShortagePushList(platform, bailun_sku, offset, limit,ref total, start_date, end_date, warehousecode, warehousetype, warehousearea);
        }

        public MemoryStream ExportShortagePush(string platform, string bailun_sku, DateTime? start_date, DateTime? end_date, UserData user, string warehousecode, string warehousetype, int? warehousearea)
        {
            try
            {
                var fileName = AppContext.BaseDirectory + $@"Result\RealtimeStock\{user.UserAccount}修改在线数量日志-{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                int page = 1;
                int rows = 50000;

                while (true)
                {
                    int total = 0;
                    var list = ShortagePushList(platform, bailun_sku, (page-1)* rows, rows, ref total, start_date, end_date, warehousecode, warehousetype, warehousearea);

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

                    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++;
                }



                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 MemoryStream Export(UserData user,int? monitor_status, int? searchType, string key_words, string warehousecode, string supplier_name, int offset, int limit, ref int total, string warehousetype, int? warehousearea, bool isSum = false, string order = null, string sort = null, int? has_tort = null,string buyer_name  =null,
           DateTime? start_date = null, DateTime? end_date = null, DateTime? f_start_date = null, DateTime? f_end_date = null,int? product_type = null)
        {
            try
            {
                export_count++;
                var services = new DailyServices();
                var fileName = AppContext.BaseDirectory + $@"Result\RealtimeStock\{user.UserAccount}实时库存-{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                int page = 1;
                int rows = 50000;
                if (export_count == 1)
                {
                    rows = 250000;
                }

                while (true)
                {
                    var list = services.RealtimeList(monitor_status, searchType, key_words, warehousecode, supplier_name, (page - 1) * rows, rows, ref total, warehousetype, warehousearea, has_tort: has_tort, buyer_name: buyer_name, start_date: start_date, end_date: end_date, f_start_date: f_start_date, f_end_date: f_end_date, product_type:product_type);

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

                    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","品牌","标签","类型","产品尺寸","包装尺寸","安全库存","销售员"
            };
                    foreach (var item in cols)
                    {
                        table.Columns.Add(item);
                    }

                    foreach (var itemData in list)
                    {
                        DataRow row = table.NewRow();
                        row["百伦简易分类"] = itemData.category_simple_name;
                        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.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.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;
                        table.Rows.Add(row);
                    }

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



                var memory = new MemoryStream();
                using (var stream = new FileStream(fileName, FileMode.Open))
                {
                    stream.CopyTo(memory);
                }
                memory.Position = 0;
                export_count--;
                return memory;
            }
            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();
        }
    }
}
