using AutoTurnOver.DB;
using AutoTurnOver.Models;
using AutoTurnOver.Models.ApiDto;
using AutoTurnOver.Models.auto;
using Bailun.ServiceFabric;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;

namespace AutoTurnOver.Services
{
    public class PurchaseAdviseServices
    {
        /// <summary>
        /// 创建采购计划
        /// </summary>
        public static void Generate(string title ,DateTime date,bool is_bak = true,bool is_clear_data  =false)
        {
            try
            {
                // 检查是否有可以切换渠道的sku
                purchase_advise.ReplaceLogistics(date);

                //等待后台重算任务
                purchase_advise.WaitReplaceLogisticsTask();

                // 创建一个采购计划
                var mainID = purchase_advise.Add(new dc_auto_purchase_advise { create_time = DateTime.Now, no = purchase_advise.GenerateOrderNo() ,buy_sys_plan_no = "Generate", title = title });
                if (mainID == null) throw new Exception("创建采购建议失败");

                purchase_advise.ImportDetailed(mainID.Value,date, is_clear_data: is_clear_data);

                if (is_bak)
                {
                    dc_task_download_dao.PushData<dc_base_stock_search_dto>(new dc_task_download
                    {
                        parameter = new { }.ToJson(),
                        task_name = "周转表"
                    }, new UserData { UserName = "sys-bak" });
                }
               
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public static void GenerateTemp(DateTime date)
        {
            try
            {
                // 检查是否有可以切换渠道的sku
                //purchase_advise.ReplaceLogistics(date);

                //等待后台重算任务
                //purchase_advise.WaitReplaceLogisticsTask();

                // 创建一个采购计划
                var mainID = purchase_advise.Add(new dc_auto_purchase_advise { create_time = DateTime.Now, no = purchase_advise.GenerateOrderNo(), buy_sys_plan_no = "Generate" });
                if (mainID == null) throw new Exception("创建采购建议失败");

                purchase_advise.ImportDetailedTemp(mainID.Value, date);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }





        /// <summary>
        /// 获取采购建议列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public static List<dc_auto_purchase_advise> List(dc_auto_purchase_advise_search_dto m, int offset, int limit, ref int total)
        {
            return purchase_advise.List(m, offset, limit, ref total);
        }

        /// <summary>
        /// 获取采购建议明细列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public static List<dc_auto_purchase_advise_detailed_dto> DetailList(dc_auto_purchase_advise_detailed_search_dto m, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            return purchase_advise.DetailList(m, offset, limit, ref total, order, sort);
        }

        public string Export(dc_auto_purchase_advise_detailed_search_dto searchData)
        {
            var fileName = AppContext.BaseDirectory + $@"采购建议-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
            var total = 0;
            var list = PurchaseAdviseServices.DetailList(searchData, 0, int.MaxValue, ref total);

            DataTable table = new DataTable();
            string[] cols = new string[] { "初始建议数", "系统建议数", "采购数量", "是否已推送","jit备货类型", "时间", "sku", "产品名称", "产品14日日均", "仓库编码","仓库名称","源仓库",
                 "内部商品编码", "商品建议采购", "商品14日日均", "商品moq", "日均加权销量", "缺货","实时缺货", "调拨在途", "调拨单在途", "调拨在途（采购临时数据）", "调拨在途（暂存）", "采购在途", "库存数",
                 "采购金额", "供应链长度", "供应商名称", "采购类型","采购员","突增关注","待发货百伦单号","7日日均","14日日均","30日日均","海外仓入库天数",
                 "采购单价" ,"历史7天日均","历史14日均","历史30日均","加权日均","安全库存","今日实际缺货","供应链累积销量","供应链到货当天的销量"
                 ,"预测销量","累积入库数量","实际库存","moq","多备天数","多备数量","预测销量配置","实际推送下单数量","总下单金额","转仓来源仓库编码","转仓来源仓库名称","仓库类型","最新计算时间"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

            foreach (var itemData in list)
            {
                DataRow row = table.NewRow();
                row["最新计算时间"] = itemData.calculation_time;
                row["仓库类型"] = itemData.hq_type;
                row["转仓来源仓库编码"] = itemData.transfer_warehouse_from_code;
                row["转仓来源仓库名称"] = itemData.transfer_warehouse_from_name;

                row["采购单价"] = itemData.fixed_unit_price;
                row["历史7天日均"] = itemData.fixed_history_sevenday_sales;
                row["历史14日均"] = itemData.fixed_history_fourteenday_sales;
                row["历史30日均"] = itemData.fixed_history_thirtyday_sales;
                row["加权日均"] = itemData.fixed_daily_weighted_sales;
                row["安全库存"] = itemData.fixed_quantity_safe_inventory;
                row["今日实际缺货"] = itemData.fixed_quantity_out_stock;
                row["供应链累积销量"] = itemData.fixed_turnover_sales;
                row["供应链到货当天的销量"] = itemData.fixed_turnover_date_sales;
                row["预测销量"] = itemData.fixed_sales_explain_details;
                row["累积入库数量"] = itemData.fixed_turnover_inbound;
                row["实际库存"] = itemData.fixed_quantity_inventory;
                row["moq"] = itemData.fixed_moq;
                row["多备天数"] = itemData.fixed_stock_up_days;
                row["多备数量"] = itemData.fixed_stock_up_sales;
                row["预测销量配置"] = itemData.fixed_dc_auto_sales_forecast_title;
                row["实际推送下单数量"] = itemData.quantity_actual_push;
                row["总下单金额"] = itemData.quantity_actual_amount;

                row["调拨单在途"] = itemData.quantity_transfer_order;
                row["调拨在途（采购临时数据）"] = itemData.quantity_transfer_temp_schedule;
                row["调拨在途（暂存）"] = itemData.quantity_transfer_temporary_storage;

                row["7日日均"] = itemData.t_history_sevenday_sales;
                row["14日日均"] = itemData.t_history_fourteenday_sales;
                row["30日日均"] = itemData.t_history_thirtyday_sales;
                row["源仓库"] = itemData.source_warehouse_code_name_str;
                row["初始建议数"] = itemData.quantity_init_advise;
                row["系统建议数"] = itemData.quantity_final_advise;
                row["采购数量"] = itemData.quantity_actual;
                row["是否已推送"] = itemData.ispush == 1 ? "是" : "否";
                row["jit备货类型"] = itemData.purchase_type_jit_str;
                row["时间"] = itemData.create_time_str;
                row["sku"] = itemData.bailun_sku;
                row["产品名称"] = itemData.sku_name;
                row["产品14日日均"] = itemData.history_fourteenday_sales;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["内部商品编码"] = itemData.product_inner_code;
                row["商品建议采购"] = itemData.goods_quantity_init_advise;
                row["商品14日日均"] = itemData.goods_history_fourteenday_sales;
                row["商品moq"] = itemData.goods_moq;
                row["日均加权销量"] = itemData.daily_weighted_sales;
                row["缺货"] = itemData.quantity_out_stock;
                row["实时缺货"] = itemData.realtime_quantity_out_stock;
                row["调拨在途"] = itemData.quantity_transfer;
                row["采购在途"] = itemData.quantity_purchase;
                row["库存数"] = itemData.quantity_inventory;
                row["采购金额"] = itemData.quantity_final_advise_price;
                row["供应链长度"] = itemData.turnover_days;
                row["供应商名称"] = itemData.suppliers_name;
                row["采购类型"] = itemData.type_str;
                row["采购员"] = itemData.buyer_name;
                row["突增关注"] = itemData.sudden_increase;
                row["待发货百伦单号"] = itemData.bailun_order_ids;
                row["海外仓入库天数"] = itemData.abroad_inbound_config_delivery;
                table.Rows.Add(row);
            }

           

            CsvFileHelper.SaveCSV(table, fileName);

            return fileName;

        }

        /// <summary>
        /// 设置采购数量
        /// </summary>
        /// <param name="id"></param>
        public static void SetQuantityActual(int id, int quantity_actual)
        {
            purchase_advise.SetQuantityActual(id, quantity_actual);
        }

        /// <summary>
        /// 批量设置采购数量
        /// </summary>
        /// <param name="id"></param>
        public static void BatchSetQuantityActual(List<BatchSetQuantityActualInputDto> datas)
        {
            purchase_advise.BatchSetQuantityActual(datas);
        }


        /// <summary>
        /// 查询历史采购建议
        /// </summary>
        /// <param name="id"></param>
        public static dc_auto_purchase_advise_detailed DetailInfo(string sku, string warehousecode, DateTime dateTime)
        {
            return purchase_advise.DetailInfo(sku, warehousecode, dateTime);
        }



        public static void Del(int id)
        {
            purchase_advise.Del(id);
        }

        private static object _push_lock = new object();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">1= 正常推送 2= 改渠道推送</param>
        /// <param name="datas"></param>
        /// <param name="user"></param>
        /// <param name="is_skip_error">是否跳过异常</param>
        public static void PushBuySys(int type,List<dc_auto_purchase_advise_detailed_dto> original_datas, UserData user,bool is_skip_error,string remarks = "")
        {
            lock (_push_lock)
            {
                try
                {
                    //查询最近一个采购建议
                    if (original_datas == null || original_datas.Count <= 0)
                    {
                        Console.WriteLine(" 推送缺货发现没数据：line 124 ");
                        return;
                    }
                    var json_datas = original_datas.ToJson().ToObject<List<dc_auto_purchase_advise_detailed_dto>>();
                    var datas = new List<dc_auto_purchase_advise_detailed_dto>();
                    if (type == 1)
                    {
                        
                        PushBuySys(2, original_datas, user, is_skip_error, remarks);

                        datas = json_datas.Where(s => s.auto_replace_logistics_task_id == null || s.auto_replace_logistics_task_id <= 0).ToList();
                    }
                    else if(type==2){
                        datas = json_datas.Where(s => s.auto_replace_logistics_task_id >0).ToList();
                        remarks  = ((remarks ?? "") +"\n"+string.Join(",",datas.Select(s=> s.bailun_sku+":" +s.replace_logistics_remarks??"")));
                    }

                    if (datas == null || datas.Count<=0)
                    {
                        Console.WriteLine(" 推送缺货发现没数据：line 143 ");
                        return;
                    }

                    List<string> planNos = new List<string>();
                    DateTime now = DateTime.Now;
                    // 查询未推送成功的采购建议的明细
                    var detailList = purchase_advise.BuyDetailList(datas.Select(s => s.id).ToList(), false);
                    foreach (var item in detailList.GroupBy(s => new { s.warehouse_code,s.area_name, s.warehouse_type,s.task_transport_type }))
                    {

                        mPlanToPurchaseDto data = new mPlanToPurchaseDto
                        {
                            bp_send = item.Key.warehouse_type != "国内仓" ? 1 : 0,
                            bp_sendfromCode = item.Key.warehouse_type != "国内仓" ? "GZBLZZG" : item.Key.warehouse_code,
                            bp_sendtoCode = item.Key.warehouse_type != "国内仓" ? item.Key.warehouse_code : null,
                            sys_source = item.Any(s => s.type == 2) ? 2 : item.Any(s => s.type == 1) ? 1 : 3,
                            bi_buyplandetail = new List<bi_buyplandetail>(),
                            bp_remark = $"用户{user.UserName} 在 aims 操作推送- "+ remarks,
                            logistics_code = item.Min(v=>v.logistics_code)
                        };

                        if (type == 1)
                        {
                            // 走旧的运输方式逻辑
                            data.bp_sendtype = data.bp_send == 1 ? 4 : -1;
                            if ("FBA仓".Equals(item.Key.warehouse_type, StringComparison.OrdinalIgnoreCase))
                            {
                                if ("美国".Equals(item.Key.area_name, StringComparison.OrdinalIgnoreCase))
                                {
                                    data.bp_sendtype = 2;
                                }
                                else if ("英国".Equals(item.Key.area_name, StringComparison.OrdinalIgnoreCase)
                                   || "法国".Equals(item.Key.area_name, StringComparison.OrdinalIgnoreCase)
                                   || "德国".Equals(item.Key.area_name, StringComparison.OrdinalIgnoreCase)
                                   || "意大利".Equals(item.Key.area_name, StringComparison.OrdinalIgnoreCase)
                                   || "西班牙".Equals(item.Key.area_name, StringComparison.OrdinalIgnoreCase)
                                   )
                                {
                                    data.bp_sendtype = 4;
                                }
                            }
                            else if ("第三方仓库".Equals(item.Key.warehouse_type, StringComparison.OrdinalIgnoreCase))
                            {
                                data.bp_sendtype = 3;
                            }

                            var sendtype = item.Max(s => s.sendtype);
                            if (sendtype > 0)
                            {
                                data.bp_sendtype = sendtype.Value;
                            }
                        }
                        else if (type == 2)
                        {
                            var task_transport_type = item.Key.task_transport_type;
                            if (string.IsNullOrWhiteSpace(task_transport_type))
                            {
                                throw new Exception("命中只能切换物流的规则，未查询到运输方式");
                            }
                            if (task_transport_type == "海运")
                            {
                                data.bp_sendtype = 2;
                            }else if (task_transport_type == "空运")
                            {
                                data.bp_sendtype = 3;
                            }else if (task_transport_type == "陆运")
                            {
                                data.bp_sendtype = 1;
                            }else if (task_transport_type == "铁路运输")
                            {
                                data.bp_sendtype = 4;
                            }
                        }
                       

                        data.bi_buyplandetail = item.GroupBy(s=>s.bailun_sku).Select(s => new bi_buyplandetail
                        {
                            bd_count = s.Sum(g=> g.quantity_actual > 0 ? g.quantity_actual : g.quantity_final_advise),
                            bd_price = s.Max(g=>g.unit_price),
                            bd_sku = s.Key,
                            sys_source = s.Any(g => g.type == 2) ? 2 : s.Any(g => g.type == 1) ? 1 : 3,
                        }).ToList();
                        if(datas==null || datas.Count <= 0)
                        {
                            Console.WriteLine(" 推送缺货发现没数据：line 228 ");
                        }
                        var result = ApiServices.PushBuyPlan(data, is_skip_error);
                        if (result.IsSuccessed)
                        {
                            //把采购数量没有填的都补上 建议采购数
                            var sql = " update dc_auto_purchase_advise_detailed set quantity_actual=quantity_final_advise where quantity_actual<=0 and id in @ids ";
                            DynamicParameters parameters = new DynamicParameters();
                            parameters.Add("ids", item.Select(s => s.id).ToList());
                            if(result.fail_skus!=null && result.fail_skus.Count >= 1)
                            {
                                sql += " and bailun_sku not in @bailunSku ";
                                parameters.Add("bailunSku", result.fail_skus.ToList());
                            }
                            connectionHelper._connection.Execute(sql, parameters);

                            // 把相关的采购明细都标记成已推送
                            var sql2 = " update  dc_auto_purchase_advise_detailed set ispush=1,push_date=now(),plan_nos=@plan_nos,push_user_name=@push_user_name where id in @ids ";
                            DynamicParameters parameters2 = new DynamicParameters();
                            parameters2.Add("ids", item.Select(s => s.id).ToArray());
                            parameters2.Add("plan_nos", result.planNo);
                            parameters2.Add("push_user_name", user.UserName);
                            if (result.fail_skus != null && result.fail_skus.Count >= 1)
                            {
                                sql2 += " and bailun_sku not in @bailunSku ";
                                parameters2.Add("bailunSku", result.fail_skus.ToList());
                            }
                            connectionHelper._connection.Execute(sql2, parameters2);
                        }
                        planNos.Add(result.planNo);

                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

        }



        /// <summary>
        /// 速卖通的挑出来单独下
        /// </summary>
        public static void PushBuySysSplit_bak(List<dc_auto_purchase_advise_detailed_dto> datas, UserData user, bool is_skip_error)
        {
            if (datas == null || datas.Count <= 0) return;
            var amazon_datas = new List<dc_auto_purchase_advise_detailed_dto>();
            var ali_datas = new List<dc_auto_purchase_advise_detailed_dto>();
            var other_datas = new List<dc_auto_purchase_advise_detailed_dto>();

            foreach (var item in datas)
            {
                if("张莹霞".Equals(item.buyer_name))
                {
                    if (item.quantity_out_stock_other > 0)
                    {
                        var temp_other_data = item.ToJson().ToObject<dc_auto_purchase_advise_detailed_dto>();
                        temp_other_data.quantity_final_advise = Math.Min((int)item.quantity_out_stock_other, item.quantity_final_advise);
                        if (temp_other_data.quantity_final_advise > 0)
                        {
                            other_datas.Add(temp_other_data);
                            item.quantity_final_advise = Math.Max(0, (int)item.quantity_final_advise - temp_other_data.quantity_final_advise);
                        }
                    }

                    if (item.quantity_final_advise > 0 && item.quantity_out_stock_amazon > 0)
                    {
                        var temp_amazon_data = item.ToJson().ToObject<dc_auto_purchase_advise_detailed_dto>();
                        temp_amazon_data.quantity_final_advise =Math.Min( (int)item.quantity_out_stock_amazon.Value, item.quantity_final_advise);
                        if (temp_amazon_data.quantity_final_advise > 0)
                        {
                            amazon_datas.Add(temp_amazon_data);
                            item.quantity_final_advise = Math.Max(0, (int)item.quantity_final_advise - temp_amazon_data.quantity_final_advise);
                        }
                    }

                    if (item.quantity_final_advise > 0)
                    {
                        ali_datas.Add(item);
                    }
                }
                else
                {
                    ali_datas.Add(item);
                }
            }

            if (amazon_datas != null && amazon_datas.Count > 0)
            {
                PushBuySys(1,amazon_datas, user, is_skip_error, "亚马逊");
            }
            if (ali_datas!=null && ali_datas.Count > 0)
            {
                PushBuySys(1,ali_datas, user, is_skip_error,"速卖通");
            }
            if (other_datas != null && other_datas.Count > 0)
            {
                PushBuySys(1,other_datas, user, is_skip_error,"其他");
            }
                
        }


        /// <summary>
        /// 指定平台（ebay, wish）的挑出来单独下
        /// </summary>
        public static void PushBuySysSplit(List<dc_auto_purchase_advise_detailed_dto> datas, UserData user, bool is_skip_error)
        {
            if (datas == null || datas.Count <= 0) return;
            var alone_datas = new List<dc_auto_purchase_advise_detailed_dto>();
            var other_datas = new List<dc_auto_purchase_advise_detailed_dto>();

            // 查询当前有缺货的sku
            Console.WriteLine($"拆分ebay+wish 的逻辑");
            var shortageSkuList = purchase_advise.ShortageSkuList(new List<string> { "ebay","wish"},new List<string> { "张莹霞" });
            alone_datas = datas.Where(s => shortageSkuList.Any(v => v == s.bailun_sku)).ToList();
            other_datas = datas.Where(s => !shortageSkuList.Any(v => v == s.bailun_sku)).ToList();
            Console.WriteLine($"ebay+wish 总数：{alone_datas.Count()}");
            Console.WriteLine($"其他总数：{other_datas.Count()}");
            if (alone_datas != null && alone_datas.Count > 0)
            {
                PushBuySys(1,alone_datas, user, is_skip_error,"ebay+wish");
            }
            if (other_datas != null && other_datas.Count > 0)
            {
                PushBuySys(1,other_datas, user, is_skip_error,"其他");
            }
                
        }

        /// <summary>
        /// 自动推送采购单
        /// </summary>
        /// <param name="type">1：张莹霞  2：赵美聪 3:陈嘉雯1 </param>
        public static void AutoPushBuySys(int type)
        {
            try
            {
                // 生产jit采购建议
                var mainID = 0;
                if (type == 1)
                {
                    mainID = purchase_advise.ImportJITShortageDetailed(0);
                }
                else if (type == 2)
                {
                    mainID = purchase_advise.ImportFuZhuangShortageDetailed(0);
                }
                else if (type == 3)
                {
                    mainID = purchase_advise.ImportShoujiShortageDetailed(0);
                }else if(type==4)
                {
                    mainID = purchase_advise.ImportJITShortageDetailed1(0); 
                }
                else if (type == 5)
                {
                    mainID = purchase_advise.ImportFuZhuangShortageIncreaseDetailed(0);
                }
                else if (type == 6)
                {
                    mainID = purchase_advise.ImportYiWuShortageDetailed(0);
                }
                else if (type == 7)
                {
                    mainID = purchase_advise.ImportDuLiShortageDetailed(0);
                }

                Console.WriteLine($"采购建议生成，id:{mainID}");
                List<dc_auto_purchase_advise_detailed_dto> datas = new List<dc_auto_purchase_advise_detailed_dto>();

                var total = 0;
                System.Threading.Thread.Sleep( 10 * 1000);
                datas.AddRange(PurchaseAdviseServices.DetailList(new dc_auto_purchase_advise_detailed_search_dto { data_base_type = 1, main_id = mainID,  ispush = false }, 0, int.MaxValue, ref total));
                Console.WriteLine($"查询建议数，total:{datas.Count}");
                //datas.AddRange(PurchaseAdviseServices.DetailList(new dc_auto_purchase_advise_detailed_search_dto { main_id = mainID,  ispush = false }, 0, int.MaxValue, ref total));
                if (true)
                {
                    Console.WriteLine($"进入推送逻辑");
                    PurchaseAdviseServices.PushBuySysSplit(datas, new UserData { UserName = "admin" }, true);
                    Console.WriteLine($"完成推送");
                }
                else
                {
                    PurchaseAdviseServices.PushBuySys(1,datas, new UserData { UserName = "admin" }, true);
                }
                
            }
            catch (Exception ex)
            {
               
                report.AddError(new dc_task_error_log
                {
                    date = DateTime.Now,
                    message = ex.Message,
                    stack_trace = ex.StackTrace,
                    task_name = "AutoPushBuySys"
                });
                Console.WriteLine(ex.Message);
                ApiServices.QiYeJiQiRenMsPush(new QiYeJiQiRenMsDto { msgtype = "text",text = new QiYeJiQiRenMsDto.text_dto { content = " 海丽，aims 采购单推送失败，请手动推送 "} });
                ApiServices.QiYeJiQiRenMsPush(new QiYeJiQiRenMsDto { msgtype = "text", text = new QiYeJiQiRenMsDto.text_dto { content = " 泽锋，查收异常消息： "+ex.Message } });
            }

        }

        /// <summary>
        /// 提取sku
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static List<string> ExtractSku(string message)
        {
            if (!message.Contains("SKU") && !message.Contains("sku"))
            {
                return null;
            }
            else
            {
                Regex skuRegex = new Regex(@"【[\s\S]+】");
                var skus = skuRegex.Matches(message);
                if (skus != null && skus.Count == 1)
                {
                    return skus[0].Value.Split(',').ToList();
                }
                else if (skus.Count > 1)
                {
                    report.AddError(new dc_task_error_log
                    {
                        date = DateTime.Now,
                        message = "异常中包含多个【】，识别异常",
                        stack_trace = message,
                        task_name = "AutoPushBuySys_ExtractSku"
                    });
                    return null;
                }
                else
                {
                    return null;
                }
            }
        }

        
        public static void CheckTurnoveCount(DateTime time)
        {
          var count =  MyMySqlConnection._connection_read_only.QuerySingleOrDefault<int>("select count(1) from  dc_auto_turnover where gmt_modified>=@time ",new { time = time });
            ApiServices.QiYeJiQiRenMsPush(new QiYeJiQiRenMsDto { msgtype = "text", text = new QiYeJiQiRenMsDto.text_dto { content = $" 骆宾， 当前已更新的周转数  {count}" } });
        }

        public List<dc_aims_return_goods_dto> ReturnGoodsList(dc_aims_return_goods_search_dto search_data, int offset, int limit, ref int total)
        {
            return DB.purchase_advise.ReturnGoodsList(search_data, offset, limit, ref total);
        }
        
        public List<dc_auto_purchase_advise> GetToDayDatas()
        {
            return DB.purchase_advise.GetToDayDatas();
        }

        public string ExportReturnGoods(dc_aims_return_goods_search_dto searchData)
        {
            try
            {
                var fileName = AppContext.BaseDirectory + $@"退货汇总-{DateTime.Now.ToString("yyyyMMddHHmmss")}{Guid.NewGuid()}.csv";
                int total = 0;
                var list = ReturnGoodsList(searchData, 0, int.MaxValue, ref total);

                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.rule_title;
                    row["仓库"] = itemData.warehouse_name;
                    row["sku"] = itemData.bailun_sku;
                    row["库存"] = itemData.stock;
                    row["采购员"] = itemData.buy_name;
                    row["供应商"] = itemData.suppliers_name;
                    row["采购价"] = itemData.unit_price;
                    row["采购单号"] = itemData.purchase_id;
                    row["采购数量"] = itemData.purchase_count;
                    row["淘宝单号"] = itemData.order_1688_no;
                    row["最后签收时间"] = itemData.sign_date;
                    table.Rows.Add(row);
                }

                CsvFileHelper.SaveCSV(table, fileName);


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

        }
    }
}
