using System;
using System.Collections.Generic;
using System.Text;
using AutoTurnOver.Models;
using AutoTurnOver.DB;
using System.Linq;
using AutoTurnOver.Utility;
using AutoTurnOver.Models.Report;
using System.Data;
using AutoTurnOver.Models.ApiDto;
using System.Dynamic;
using System.IO;
using System.Threading.Tasks;
using AutoTurnOver.Models.Base;
using AutoTurnOver.Models.stock;

namespace AutoTurnOver.Services
{
    public class ReportServices
    {
        /// <summary>
        /// 获取预测销售+入库+库存+缺货数
        /// </summary>
        /// <param name="sku">sku编码</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <returns></returns>
        public List<string> ForecastSalePutinStockShort(string sku, string warehousecode)
        {
            var list = new List<string>();

            //获取预测销量
            //var sales = DB.SaleVolume.GetBySkuWarehouseCode(sku, warehousecode);

            var sales = DB.dc_auto_turnover.GetModel(sku, warehousecode);

            //获取预计采购入库
            //var buyputin = DB.dc_auto_turnover.GetAutoInboundBySkuWH(sku, warehousecode,1);

            //获取预计调拨入库
            //var allotputin = DB.dc_auto_turnover.GetAutoInboundBySkuWH(sku, warehousecode, 2);

            // 预计入库
            var putin = DB.dc_auto_turnover.GetAutoInboundBySkuWH(sku, warehousecode, 0);

            //可用库存
            var inventory = DB.dc_auto_turnover.GetAutoInventoryBySkuWH(sku, warehousecode);

            //缺货数量
            var shortsupply = DB.dc_auto_turnover.GetAutoShortSupplyBySkuWH(sku, warehousecode);


            list.Add(sales != null ? sales.sales_details.ToObj<List<decimal>>().Select(s => (int)Math.Ceiling(s)).ToJson() : "[]");
            list.Add(sales != null ? sales.sales_explain_details.Replace("[", "").Replace("]", "").Split(',').ToJson() : "[]");
            //list.Add(buyputin != null ? buyputin.details : "[]");
            //list.Add(allotputin != null ? allotputin.details : "[]");
            list.Add(sales != null ? sales.inbound_details.ToObj<List<decimal>>().Select(s => (int)Math.Ceiling(s)).ToJson() : "[]");
            list.Add(sales != null ? sales.inventory_details.ToObj<List<decimal>>().Select(s => (int)Math.Ceiling(s)).ToJson() : "[]");
            list.Add(sales != null ? sales.short_supply_details.ToObj<List<decimal>>().Select(s => (int)Math.Ceiling(s)).ToJson() : "[]");

            // 计算涉及的总天数
            int count = list.Max(s => s.Split(',').Length);

            DateTime today = DateTime.Now.AddDays(-7);
            DateTime endDay = today.AddDays(count);
            // 查询这些时间范围的 特殊销量情况
            var configPromotionList = DB.dc_auto_turnover.ListConfigPromotion(sku, warehousecode, today, endDay);

            // 查询这些时间范围的 市场因素情况
            var correctionList = DB.dc_auto_turnover.ListCorrection(sku, warehousecode, today, endDay);

            //查询这些时间范围的 采购下单数量
            var purchaseDetailList = DB.purchase_advise.DetailList(sku, warehousecode, today, endDay);

            // 用于存储特殊销量规则
            List<int> tempStrList = new List<int>();

            // 用于存储市场因素规则
            List<decimal> tempCorrectionStrList = new List<decimal>();
            // 建议下单数
            List<decimal> tempAdviseStrList = new List<decimal>();
            // 实际下单数
            List<decimal> tempActualStrList = new List<decimal>();
            for (var i = 0; i < count; i++)
            {
                var tempDate = today.AddDays(i);
                var tempDateHome = DateTime.Parse(tempDate.ToString("yyyy-MM-dd 00:00:00"));
                var tempDateEnd = DateTime.Parse(tempDate.ToString("yyyy-MM-dd 23:59:59"));
                var tempData = configPromotionList.FirstOrDefault(s => s.promotion_time >= tempDateHome && s.promotion_time <= tempDateEnd);
                if (tempData == null)
                {
                    tempStrList.Add(0);
                }
                else
                {
                    tempStrList.Add(tempData.count);
                }

                var tempCorrectionData = correctionList.FirstOrDefault(s => s.end_time >= tempDateHome && s.start_time <= tempDateEnd);
                if (tempCorrectionData == null)
                {
                    tempCorrectionStrList.Add(1);
                }
                else
                {
                    tempCorrectionStrList.Add(tempCorrectionData.param);
                }

                // 只查询历史

                var tempPurchaseDetailData = purchaseDetailList.FirstOrDefault(s => s.create_time >= tempDateHome && s.create_time <= tempDateEnd);
                if (tempPurchaseDetailData == null)
                {
                    if (tempDateEnd < DateTime.Now)
                    {
                        tempAdviseStrList.Add(0);
                    }

                    tempActualStrList.Add(0);
                }
                else
                {
                    if (tempDateEnd < DateTime.Now)
                    {
                        tempAdviseStrList.Add(tempPurchaseDetailData.quantity_final_advise);
                    }

                    tempActualStrList.Add(tempPurchaseDetailData.quantity_actual);
                }

            }

            // 预测未来采购数量
            // 只预测一个周转期
            if (sales.advised_details != null)
            {
                tempAdviseStrList.AddRange(sales.advised_details.ToObj<List<decimal>>());
            }



            list.Add(tempStrList != null ? tempStrList.ToJson() : "[]");
            list.Add(tempCorrectionStrList != null ? tempCorrectionStrList.Select(s => (int)s).ToJson() : "[]");
            list.Add(tempAdviseStrList != null ? tempAdviseStrList.Select(s => (int)s).ToJson() : "[]");
            list.Add(tempActualStrList != null ? tempActualStrList.Select(s => (int)s).ToJson() : "[]");

            ////添加预测销量
            //list.Add(new mforecast {
            //    typename = "预测销量",
            //    today = sales!=null?sales.forecast_today_sales:0,
            //    oneday = sales != null ? sales.oneday_sales : 0,
            //    twoday = sales != null ? sales.twoday_sales : 0,
            //    thirtday = sales != null ? sales.threeday_sales : 0,
            //    forthday = sales != null ? sales.fourthday_sales : 0,
            //    fiveday = sales != null ? sales.fiveday_sales : 0,
            //    sixday = sales != null ? sales.sixday_sales : 0,
            //    sevenday =  sales != null ? sales.sevenday_sales : 0,
            //    eightday = sales!=null?sales.eightday_sales:0,
            //    nineday = sales != null ? sales.nineday_sales : 0,
            //    tenday = sales != null ? sales.tenday_sales : 0,

            //    elevenday = sales != null ? sales.elevenday_sales : 0,
            //    twelveday = sales != null ? sales.twelveday_sales : 0,
            //    thirteenday = sales != null ? sales.thridteenday_sales : 0,
            //    fourteenday = sales != null ? sales.fourteenday_sales : 0,
            //    fifteenday = sales != null ? sales.fifteenday_sales : 0,
            //    sixteenday = sales != null ? sales.sixteenday_sales : 0,
            //    seventeenday = sales != null ? sales.seventeenday_sales : 0,
            //    eighteenday = sales != null ? sales.eighteenday_sales : 0,
            //    nineteenday = sales != null ? sales.nineteenday_sales : 0,
            //    twentyday = sales != null ? sales.twentyday_sales : 0,


            //    twentyoneday = sales != null ? sales.twenty_oneday_sales : 0,
            //    twentytwoday = sales != null ? sales.twenty_twoday_sales : 0,
            //    twentythreeday = sales != null ? sales.twenty_threeday_sales : 0,
            //    twentyfourday = sales != null ? sales.twenty_fourthday_sales : 0,
            //    twentyfiveday = sales != null ? sales.twenty_fiveday_sales : 0,
            //    twentysixday = sales != null ? sales.twenty_sixday_sales : 0,
            //    twentysevenday = sales != null ? sales.twenty_seveneday_sales : 0,
            //    twentyeightday = sales != null ? sales.twenty_eightday_sales : 0,
            //    twentynineday = sales != null ? sales.twenty_nineday_sales : 0,
            //    thirtyday = sales != null ? sales.thirtyday_sales : 0,
            //    skucode = sales != null ? sales.bailun_sku : "",
            //    skuname = "",
            //    warehousecode = sales != null ? sales.warehouse_code : "",
            //    warehousename = sales != null ? sales.warehouse_name : "",
            //});

            ////添加预计入库
            //list.Add(new mforecast {
            //    typename = "预计入库数量",
            //    today = putin!=null?putin.forecast_today_inbound:0,
            //    oneday = putin != null ? putin.forecast_oneday_inbound : 0,
            //    twoday = putin != null ? putin.forecast_twoday_inbound : 0,
            //    thirtday = putin != null ? putin.forecast_threeday_inbound : 0,
            //    forthday = putin != null ? putin.forecast_fourthday_inbound : 0,
            //    fiveday = putin != null ? putin.forecast_fiveday_inbound : 0,
            //    sixday = putin != null ? putin.forecast_sixday_inbound : 0,
            //    sevenday = putin != null ? putin.forecast_sevenday_inbound : 0,
            //    eightday = putin != null ? putin.forecast_eightday_inbound : 0,
            //    nineday = putin != null ? putin.forecast_nineday_inbound : 0,
            //    tenday = putin != null ? putin.forecast_tenday_inbound : 0,

            //    elevenday = putin != null ? putin.forecast_elevenday_inbound : 0,
            //    twelveday = putin != null ? putin.forecast_twelveday_inbound : 0,
            //    thirteenday = putin != null ? putin.forecast_thridteenday_inbound : 0,
            //    fourteenday = putin != null ? putin.forecast_fourteenday_inbound : 0,
            //    fifteenday = putin != null ? putin.forecast_fifteenday_inbound : 0,
            //    sixteenday = putin != null ? putin.forecast_sixteenday_inbound : 0,
            //    seventeenday = putin != null ? putin.forecast_seventeenday_inbound : 0,
            //    eighteenday = putin != null ? putin.forecast_eighteenday_inbound : 0,
            //    nineteenday = putin != null ? putin.forecast_nineteenday_inbound : 0,
            //    twentyday = putin != null ? putin.forecast_twentyday_inbound : 0,


            //    twentyoneday = putin != null ? putin.forecast_twenty_oneday_inbound : 0,
            //    twentytwoday = putin != null ? putin.forecast_twenty_twoday_inbound : 0,
            //    twentythreeday = putin != null ? putin.forecast_twenty_threeday_inbound : 0,
            //    twentyfourday = putin != null ? putin.forecast_twenty_fourthday_inbound : 0,
            //    twentyfiveday = putin != null ? putin.forecast_twenty_fiveday_inbound : 0,
            //    twentysixday = putin != null ? putin.forecast_twenty_sixday_inbound : 0,
            //    twentysevenday = putin != null ? putin.forecast_twenty_seveneday_inbound : 0,
            //    twentyeightday = putin != null ? putin.forecast_twenty_eightday_inbound : 0,
            //    twentynineday = putin != null ? putin.forecast_twenty_nineday_inbound : 0,
            //    thirtyday = putin != null ? putin.forecast_thirtyday_inbound : 0,
            //    skucode = putin != null ? putin.bailun_sku : "",
            //    skuname = "",
            //    warehousecode = putin != null ? putin.warehouse_code : "",
            //    warehousename = "",
            //});

            ////预测可用库存
            //list.Add(new mforecast {
            //    typename = "预测可用库存",
            //    today = inventory != null ? inventory.forecast_today_inventory : 0,
            //    oneday = inventory != null ? inventory.forecast_oneday_inventory : 0,
            //    twoday = inventory != null ? inventory.forecast_twenty_twoday_inventory : 0,
            //    thirtday = inventory != null ? inventory.forecast_threeday_inventory : 0,
            //    forthday = inventory != null ? inventory.forecast_fourthday_inventory : 0,
            //    fiveday = inventory != null ? inventory.forecast_fiveday_inventory : 0,
            //    sixday = inventory != null ? inventory.forecast_sixday_inventory : 0,
            //    sevenday = inventory != null ? inventory.forecast_sevenday_inventory : 0,
            //    eightday = inventory != null ? inventory.forecast_eightday_inventory : 0,
            //    nineday = inventory != null ? inventory.forecast_nineday_inventory : 0,
            //    tenday = inventory != null ? inventory.forecast_tenday_inventory : 0,

            //    elevenday = inventory != null ? inventory.forecast_elevenday_inventory : 0,
            //    twelveday = inventory != null ? inventory.forecast_twelveday_inventory : 0,
            //    thirteenday = inventory != null ? inventory.forecast_thridteenday_inventory : 0,
            //    fourteenday = inventory != null ? inventory.forecast_fourteenday_inventory : 0,
            //    fifteenday = inventory != null ? inventory.forecast_fifteenday_inventory : 0,
            //    sixteenday = inventory != null ? inventory.forecast_sixteenday_inventory : 0,
            //    seventeenday = inventory != null ? inventory.forecast_seventeenday_inventory : 0,
            //    eighteenday = inventory != null ? inventory.forecast_eighteenday_inventory : 0,
            //    nineteenday = inventory != null ? inventory.forecast_nineteenday_inventory : 0,
            //    twentyday = inventory != null ? inventory.forecast_twentyday_inventory : 0,


            //    twentyoneday = inventory != null ? inventory.forecast_twenty_oneday_inventory : 0,
            //    twentytwoday = inventory != null ? inventory.forecast_twenty_twoday_inventory : 0,
            //    twentythreeday = inventory != null ? inventory.forecast_twenty_threeday_inventory : 0,
            //    twentyfourday = inventory != null ? inventory.forecast_twenty_fourthday_inventory : 0,
            //    twentyfiveday = inventory != null ? inventory.forecast_twenty_fiveday_inventory : 0,
            //    twentysixday = inventory != null ? inventory.forecast_twenty_sixday_inventory : 0,
            //    twentysevenday = inventory != null ? inventory.forecast_twenty_seveneday_inventory : 0,
            //    twentyeightday = inventory != null ? inventory.forecast_twenty_eightday_inventory : 0,
            //    twentynineday = inventory != null ? inventory.forecast_twenty_nineday_inventory : 0,
            //    thirtyday = inventory != null ? inventory.forecast_thirtyday_inventory : 0,
            //    skucode = inventory != null ? inventory.bailun_sku : "",
            //    skuname = "",
            //    warehousecode = inventory != null ? inventory.warehouse_code : "",
            //    warehousename = "",
            //});

            ////预测缺货数
            //list.Add(new mforecast {
            //    typename = "预测缺货数量",
            //    today = shortsupply != null ? shortsupply.forecast_today_short_supply : 0,
            //    oneday = shortsupply != null ? shortsupply.forecast_oneday_short_supply : 0,
            //    twoday = shortsupply != null ? shortsupply.forecast_twenty_twoday_short_supply : 0,
            //    thirtday = shortsupply != null ? shortsupply.forecast_threeday_short_supply : 0,
            //    forthday = shortsupply != null ? shortsupply.forecast_fourthday_short_supply : 0,
            //    fiveday = shortsupply != null ? shortsupply.forecast_fiveday_short_supply : 0,
            //    sixday = shortsupply != null ? shortsupply.forecast_sixday_short_supply : 0,
            //    sevenday = shortsupply != null ? shortsupply.forecast_sevenday_short_supply : 0,
            //    eightday = shortsupply != null ? shortsupply.forecast_eightday_short_supply : 0,
            //    nineday = shortsupply != null ? shortsupply.forecast_nineday_short_supply : 0,
            //    tenday = shortsupply != null ? shortsupply.forecast_tenday_short_supply : 0,

            //    elevenday = shortsupply != null ? shortsupply.forecast_elevenday_short_supply : 0,
            //    twelveday = shortsupply != null ? shortsupply.forecast_twelveday_short_supply : 0,
            //    thirteenday = shortsupply != null ? shortsupply.forecast_thridteenday_short_supply : 0,
            //    fourteenday = shortsupply != null ? shortsupply.forecast_fourteenday_short_supply : 0,
            //    fifteenday = shortsupply != null ? shortsupply.forecast_fifteenday_short_supply : 0,
            //    sixteenday = shortsupply != null ? shortsupply.forecast_sixteenday_short_supply : 0,
            //    seventeenday = shortsupply != null ? shortsupply.forecast_seventeenday_short_supply : 0,
            //    eighteenday = shortsupply != null ? shortsupply.forecast_eighteenday_short_supply : 0,
            //    nineteenday = shortsupply != null ? shortsupply.forecast_nineteenday_short_supply : 0,
            //    twentyday = shortsupply != null ? shortsupply.forecast_twentyday_short_supply : 0,


            //    twentyoneday = shortsupply != null ? shortsupply.forecast_twenty_oneday_short_supply : 0,
            //    twentytwoday = shortsupply != null ? shortsupply.forecast_twenty_twoday_short_supply : 0,
            //    twentythreeday = shortsupply != null ? shortsupply.forecast_twenty_threeday_short_supply : 0,
            //    twentyfourday = shortsupply != null ? shortsupply.forecast_twenty_fourthday_short_supply : 0,
            //    twentyfiveday = shortsupply != null ? shortsupply.forecast_twenty_fiveday_short_supply : 0,
            //    twentysixday = shortsupply != null ? shortsupply.forecast_twenty_sixday_short_supply : 0,
            //    twentysevenday = shortsupply != null ? shortsupply.forecast_twenty_seveneday_short_supply : 0,
            //    twentyeightday = shortsupply != null ? shortsupply.forecast_twenty_eightday_short_supply : 0,
            //    twentynineday = shortsupply != null ? shortsupply.forecast_twenty_nineday_short_supply : 0,
            //    thirtyday = shortsupply != null ? shortsupply.forecast_thirtyday_short_supply : 0,
            //    skucode = shortsupply != null ? shortsupply.bailun_sku : "",
            //    skuname = "",
            //    warehousecode = shortsupply != null ? shortsupply.warehouse_code : "",
            //    warehousename = "",
            //});

            return list;
        }

        public List<quantity_out_stock_dto> QuantityOutStockList(quantity_out_stock_search_dto m, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            return report.QuantityOutStockList(m, offset, limit, ref total, order, sort);
        }

        public List<quantity_out_stock_detail_dto> QuantityOutStockDetailList(quantity_out_stock_detail_search_dto m, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            var datas = report.QuantityOutStockDetailList(m, offset, limit, ref total, order, sort);

            if (datas.Count <= 200 && datas.Count >= 1 && !m.isSum)
            {
                var orders = datas.Select(s => ("ebay".Equals(s.platform_type, StringComparison.OrdinalIgnoreCase) ? s.transaction_id : s.origin_order_id)).ToList();
                //var crm_case_order_list = ApiServices.CrmCaseOrder(orders);
                //var crm_case_message_list = ApiServices.CrmMessage(orders);
                //var crm_case_message_reply_list = ApiServices.CrmMessageReply(orders);
                //foreach (var item in datas)
                //{
                //    item.crm_case_count = crm_case_order_list.Where(s =>
                //    item.platform_type.Equals(s.platform_type, StringComparison.OrdinalIgnoreCase) && (
                //    ("ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.transaction_id.Equals(s.order_no))
                //    ||
                //    (!"ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.origin_order_id.Equals(s.order_no))
                //    )
                //    ).Count();

                //    item.crm_message_count = crm_case_message_list.Where(s =>
                //      item.platform_type.Equals(s.platform_type, StringComparison.OrdinalIgnoreCase) && (
                //    ("ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.transaction_id.Equals(s.order_no))
                //    ||
                //    (!"ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.origin_order_id.Equals(s.order_no))
                //    )
                //    ).Count();

                //    item.crm_message_reply_count = crm_case_message_reply_list.Where(s =>
                //      item.platform_type.Equals(s.platform_type, StringComparison.OrdinalIgnoreCase) && (
                //    ("ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.transaction_id.Equals(s.order_no))
                //    ||
                //    (!"ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.origin_order_id.Equals(s.order_no))
                //    )
                //    ).Count();

                //    item.aims_message_reply_count = crm_case_message_reply_list.Where(s =>
                //    s.letterType == 6 &&
                //     item.platform_type.Equals(s.platform_type, StringComparison.OrdinalIgnoreCase) && (
                //   ("ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.transaction_id.Equals(s.order_no))
                //   ||
                //   (!"ebay".Equals(item.platform_type, StringComparison.OrdinalIgnoreCase) && item.origin_order_id.Equals(s.order_no))
                //   )
                //   ).Count();
                //}
            }
            return datas;
        }

        public List<out_stock_dto> OutStockList(out_stock_search_dto m, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            return report.OutStockList(m, offset, limit, ref total, order, sort);
        }

        public List<return_speed_change_dto> ReturnSpeedChange(return_speed_change_search_dto m, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            return report.ReturnSpeedChange(m, offset, limit, ref total, order, sort);
        }

        /// <summary>
        /// 标记回货
        /// </summary>
        /// <param name="m"></param>
        public int MarkReturnSpeedChange(return_speed_change_search_dto m)
        {
            return report.MarkReturnSpeedChange(m);
        }

        /// <summary>
        /// 批量出信
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public DataTable BatchSendMessage(BatchSendMessageInputDto data)
        {
            DataTable result_data = new DataTable();
            result_data.Columns.Add("百伦单号");
            result_data.Columns.Add("平台单号");
            result_data.Columns.Add("发送结果");
            result_data.Columns.Add("备注");
            result_data.Columns.Add("异常");

            // 查询相关的数据
            var order_data_list = report.GetOmsOrder(data.bailun_order_ids);

            foreach (var item in order_data_list)
            {
                try
                {
                    var send_data = new ApiSendMessageInputDto()
                    {
                        saas_company_id = 1,
                        content = data.content,
                        letterType = 6,
                        order_no = item.order_id,
                        platform = item.platform_type,
                        remarks = data.remarks,
                        subject = data.subject,
                        user = "API_AIMS"
                    };
                    ApiServices.SendMessage(send_data);

                    var row = result_data.NewRow();
                    row["百伦单号"] = item.bailun_order_id;
                    row["平台单号"] = item.order_id;
                    row["发送结果"] = "成功";
                    row["备注"] = "";
                    row["异常"] = "";
                    result_data.Rows.Add(row);
                }
                catch (Exception ex)
                {
                    var row = result_data.NewRow();
                    row["百伦单号"] = item.bailun_order_id;
                    row["平台单号"] = item.order_id;
                    row["发送结果"] = "失败";
                    row["备注"] = ex.Message;
                    row["异常"] = ex.StackTrace;
                    result_data.Rows.Add(row);
                }
            }

            return result_data;
        }

        public void ShortagePush(bool is_all = false,string platform = null)
        {
           
            // 国内仓
            List<string> platform1s = new List<string> {"ebay","amazon", "aliexpress", "shopee", "wish", "lazada" };
            foreach (var item in platform1s.Where(s=> string.IsNullOrWhiteSpace(platform) || platform==s))
            {
                try
                {
                    List<dc_auto_shortage_push> datas = new List<dc_auto_shortage_push>();
                    datas.AddRange(report.ChinaShortagePush(item, is_all)); 
                    var err_datas = ApiServices.ShortagePush(datas, item);
                    // 记录推送状态
                    report.AddShortagePush(datas.Where(s => !err_datas.Any(e => e.warehouseCode == s.warehouse_code && s.bailun_sku == e.sku)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
                
            }

            //国外仓1
            List<string> platform2s = new List<string> { "ebay", "wish" };
            List<string> rule1 = new List<string> { "GBYKD", "JZHYBLGC", "MDBLWYT", "MXBLWYT", "BLUSGDC", "GBBMHBL", "GB4PXBL", "DEBLDG", "USGCBL", "USHWBL", "US4PXBL", "AUWYTBL", "AU4PXBL", "GBWYTUK", "GBLQST" };
            foreach (var item in platform2s.Where(s => string.IsNullOrWhiteSpace(platform) || platform == s))
            {
                try
                {
                    List<dc_auto_shortage_push> datas = new List<dc_auto_shortage_push>();
                    datas.AddRange(report.NotChinaShortagePush(rule1, item, is_all));
                    var err_datas = ApiServices.ShortagePush(datas, item);
                    // 记录推送状态
                    report.AddShortagePush(datas.Where(s => !err_datas.Any(e => e.warehouseCode == s.warehouse_code && s.bailun_sku == e.sku)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
                
            }

            // 国外仓2
            List<string> platform3s = new List<string> { "opensky", "sears", "walmart" };
            List<string> rule2 = new List<string> {"MDBLWYT", "MXBLWYT", "BLUSGDC", "USGCBL", "USHWBL", "US4PXBL" };
            foreach (var item in platform3s.Where(s => string.IsNullOrWhiteSpace(platform) || platform == s))
            {
                try
                {
                    List<dc_auto_shortage_push> datas = new List<dc_auto_shortage_push>();
                    datas.AddRange(report.NotChinaShortagePush(rule2, item, is_all));
                    var err_datas = ApiServices.ShortagePush(datas, item);
                    // 记录推送状态
                    report.AddShortagePush(datas.Where(s => !err_datas.Any(e => e.warehouseCode == s.warehouse_code && s.bailun_sku == e.sku)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
                
            }

        }

        /// <summary>
        /// 过滤掉一部分不需要改在0的数据
        /// </summary>
        public List<dc_auto_shortage_push> ShortagePushFilter(List<dc_auto_shortage_push> datas,string platform)
        {
            var new_datas = datas.ToJson().ToObj<List<dc_auto_shortage_push>>();

            // 规则一 如果不是ebay 过滤掉 张莹霞国内仓的数据
            if (!"ebay".Equals(platform))
            {
                var buyers = new List<string> { "张莹霞", "张莹霞1" };
                new_datas  = new_datas.Where(s => !(buyers.Any(v => s.buyer_name == v) && s.warehouse_type == "国内仓")).ToList();
            }
            return new_datas;
        }

        /// <summary>
        /// 缺货推送
        /// </summary>
        public void EbayShortagePush(bool is_all = false)
        {
            var datas = report.EbayShortagePush(is_all);
            var err_datas = ApiServices.ShortagePush(datas, "ebay");

            // 记录推送状态
            report.AddShortagePush(datas.Where(s => !err_datas.Any(e => e.warehouseCode == s.warehouse_code && s.bailun_sku == e.sku)));
        }
        public void ReturnGoodsPush(string platform = null)
        {
            var platform_list = new List<string> { "ebay", "amazon", "aliexpress", "shopee", "wish", "lazada","opensky", "sears", "walmart" };
            foreach (var item in platform_list.Where(s => string.IsNullOrWhiteSpace(platform) || platform == s))
            {
                PlatformReturnGoodsPush(item);
            }
        }
        public void PlatformReturnGoodsPush(string platform)
        {
           
            var datas = report.ReturnGoodsPush(platform);
            // 先走一遍过滤条件，把数据过滤一遍
            var filter_datas = ReturnGoodsPushFilter(datas);
            var err_datas = ApiServices.ReturnGoodsPush(filter_datas, platform);

            // 记录推送状态
            report.AddReturnGoodsPush(filter_datas.Where(s => !err_datas.Any(e => e.warehouseCode == s.warehouse_code && s.bailun_sku == e.sku)));
            // 移除缺货改零记录 （如果以后再没有库存，继续改零）
            report.removeShortagePush(datas.Where(s => !err_datas.Any(e => e.warehouseCode == s.warehouse_code && s.bailun_sku == e.sku)).Select(s=>s.shortage_push_id));
        }

        /// <summary>
        /// 过滤掉一部分不需要改在线的数据
        /// </summary>
        public List<dc_return_goods_push> ReturnGoodsPushFilter(List<dc_return_goods_push> datas)
        {
            var new_datas = datas.ToJson().ToObj<List<dc_return_goods_push>>();
            // 规则一
            var not_push_list = db_config.ReturnGoodsList(datas.Select(s=>s.bailun_sku).ToList());
            if(not_push_list!=null && not_push_list.Count >= 1)
            {
                new_datas = new_datas.Where(s => !not_push_list.Any(p=>p.bailun_sku==s.bailun_sku && p.warehouse_code==s.warehouse_code)).ToList();
            }
           

            // 规则二
            var buyers = new List<string> { "张莹霞", "张莹霞1", "黄静洁" };
            var warehouse_codes = new List<string> { "GBLQST" };
            return new_datas.Where(s => !(buyers.Any(v=>s.buyer_name==v) && warehouse_codes.Any(v => s.warehouse_code == v))).ToList();
        }

        public List<dynamic> GetSkuWebsiteSales(bailun_sku_website_sales_search_dto search_data)
        {
            var order_list = report.GetSkuWebsiteSales(search_data);
            List<dynamic> datas = new List<dynamic>();
            foreach (var item in order_list)
            {
                dynamic o = new ExpandoObject();
                o.label = item.label;
                o.platform_type = item.platform_type;
                o.website = item.website_show;
                o.data_website = item.website;
                foreach (var dat_item in item.days)
                {
                    var dic = (IDictionary<string, object>)o;
                    dic["count_" + (dat_item.month + "-" + dat_item.day)] = new { val = Math.Round(dat_item.count, 2), year = dat_item.year, month = dat_item.month, day = dat_item.day };
                    dic["sum_" + (dat_item.month + "-" + dat_item.day)] = Math.Round(dat_item.sum,2);
                }
               
                datas.Add(o);
            }

            return datas;
            
        }

        public MemoryStream SkuWebsiteSalesExport(bailun_sku_website_sales_detailed_search_dto search_data,UserData user)
        {
            try
            {
                var fileName = AppContext.BaseDirectory + $@"Result\RealtimeStock\{user.UserAccount}商品分类明细-{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";


                var list = report.GetSkuWebsiteSalesDetailed(search_data);

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

                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.bailun_order_id;
                    row["平台单号"] = itemData.origin_order_id; 
                     row["sku"] = itemData.bailun_sku;
                    row["标签"] = itemData.label;
                    row["销售数量"] = itemData.bailun_sku_quantity_ordered;
                    row["单价_美元"] = itemData.amount_sales * itemData.order_to_usd_exchange_rate;
                    row["付款时间"] = itemData.pay_time;
                    row["平台"] = itemData.platform_type;
                    row["站点"] = itemData.website;
                    table.Rows.Add(row);
                }

                CsvFileHelper.SaveCSV(table, fileName, true);



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

        }


        public List<supplier_sales_dto> SupplierSalesList(supplier_sales_search_dto m, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            return report.SupplierSalesList(m, offset, limit, ref total, order, sort);
        }

        public List<dynamic> GetGoods(bailun_sku_goods_search_dto search_data, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            var order_list = report.GetGoods(search_data,offset,limit,ref total,order,sort);
            List<dynamic> datas = new List<dynamic>();
            foreach (var item in order_list)
            {
                dynamic o = new ExpandoObject();
                o.product_inner_code = item.product_inner_code;
                o.sku_title_cn = item.sku_title_cn;
                o.bailun_category_name = item.bailun_category_name;
                foreach (var dat_item in item.websites)
                {
                    var dic = (IDictionary<string, object>)o;
                    dic["yesterday_count_" + (dat_item.platform_type + "-" + dat_item.website)] = Math.Round(dat_item.yesterday_count, 2);
                    dic["yesterday_average_7_" + (dat_item.platform_type + "-" + dat_item.website)] = Math.Round(dat_item.yesterday_average_7, 2);
                    dic["yesterday_amount_" + (dat_item.platform_type + "-" + dat_item.website)] = Math.Round(dat_item.yesterday_amount, 2);
                    dic["amount_7_" + (dat_item.platform_type + "-" + dat_item.website)] = Math.Round(dat_item.amount_7, 2);
                }

                datas.Add(o);
            }

            return datas;

        }

        public MemoryStream GetGoodsExport(bailun_sku_goods_search_dto search_data,UserData user)
        {
            

            try
            {
                var qiniuname = $"{user.UserAccount}商品汇总-{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                var fileName = AppContext.BaseDirectory + $@"Result\RealtimeStock\{user.UserAccount}商品汇总-{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";

                var total = 0;
                var list = GetGoods(search_data, 0, int.MaxValue, ref total);

                // 查询站点，组织列头
                var web_sites = ApiServices.PlatformtypeWebsiteList(search_data.platform_type);

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

                DataTable table = new DataTable();
                List<string> cols = new List<string>() { "内部商品编码", "分类", "产品名称" };
                foreach (var item in web_sites)
                {
                    cols.Add($"{item.platform_type}-{item.website}-昨日销量");
                    cols.Add($"{item.platform_type}-{item.website}-近7天日均销量");
                    cols.Add($"{item.platform_type}-{item.website}-昨日销售额");
                    cols.Add($"{item.platform_type}-{item.website}-近7天总销售额");
                }
               
                foreach (var item in cols)
                {
                    table.Columns.Add(item);
                }

                foreach (var itemData in list)
                {
                    DataRow row = table.NewRow();
                    row["内部商品编码"] = itemData.product_inner_code;
                    row["分类"] = itemData.bailun_category_name;
                    row["产品名称"] = itemData.sku_title_cn;
                    foreach (var dat_item in web_sites)
                    {
                        var dic = (IDictionary<string, object>)itemData;
                        row[($"{dat_item.platform_type}-{dat_item.website}-昨日销量")] = dic["yesterday_count_" + (dat_item.platform_type + "-" + dat_item.website)];
                        row[($"{dat_item.platform_type}-{dat_item.website}-近7天日均销量")] = dic["yesterday_average_7_" + (dat_item.platform_type + "-" + dat_item.website)];
                        row[($"{dat_item.platform_type}-{dat_item.website}-昨日销售额")] = dic["yesterday_amount_" + (dat_item.platform_type + "-" + dat_item.website)];
                        row[($"{dat_item.platform_type}-{dat_item.website}-近7天总销售额")] = dic["amount_7_" + (dat_item.platform_type + "-" + dat_item.website)];
                    }
                    table.Rows.Add(row);
                }

                CsvFileHelper.SaveCSV(table, fileName, true);



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

                return memory;
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        /// <summary>
        /// 安全报表
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public Page<quantity_safe_inventory_dto> GetInventoryStock(quantity_safe_inventory_search_dto search)
        {
            return report.GetInventoryStock(search);
        }
        
        public Page<dc_base_wip_stock_dto> GetWipStockPage(dc_base_wip_stock_search_dto search)
        {
            return report.GetWipStockPage(search);
        }

        public Page<dc_base_sku> GetSkuPage(dc_base_sku_search_dto search)
        {
            return base_sku_dao.GetPage(search);
        }



    }
}
