using AutoTurnOver.Models;
using Bailun.ServiceFabric;
using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoTurnOver.Utility;
using System.Transactions;
using AutoTurnOver.Models.Report;

namespace AutoTurnOver.DB
{
    public class dc_auto_return_goods_config_dao : connectionHelper
    {
        /// <summary>
        /// 计算可以退货的sku
        /// </summary>
        public static void Calculation()
        {
            var conn = _connection;
            var configs = conn.Query<dc_auto_return_goods_config>(" select * from dc_auto_return_goods_config where status=0 ");
            foreach (var item in configs)
            {
                var skus = GetSkus(MyMySqlConnection._connection_read_only, item);
                if (skus != null && skus.Count >= 1)
                {
                    var max_days = Math.Max(item.sales_days_1, item.sales_days_2);
                    // 销量过滤
                    foreach (var itemSku in skus)
                    {
                        var order_dates = GetOrderDateList(MyMySqlConnection._connection_read_only, itemSku.bailun_sku, itemSku.warehouse_code, Math.Max(30, max_days));
                        var sales_days_1_date = DateTime.Now.AddDays(0 - item.sales_days_1).ToDayHome();
                        var sales_days_1_val = order_dates.Where(s => s.paid_time >= sales_days_1_date).Sum(s => s.bailun_sku_quantity_ordered);
                        var sales_days_2_date = DateTime.Now.AddDays(0 - item.sales_days_2).ToDayHome();
                        var sales_days_2_val = order_dates.Where(s => s.paid_time >= sales_days_2_date).Sum(s => s.bailun_sku_quantity_ordered);

                        var sales_days_14_date = DateTime.Now.AddDays(0 - 14).ToDayHome();
                        var sales_days_7_date = DateTime.Now.AddDays(0 - 7).ToDayHome();
                        var sales_days_30_date = DateTime.Now.AddDays(0 - 30).ToDayHome();
                        var temp_val = (sales_days_1_val * item.sales_weight_1) + (sales_days_2_val * item.sales_weight_2);
                        var sales_days_7_val = order_dates.Where(s => s.paid_time >= sales_days_7_date).Sum(s => s.bailun_sku_quantity_ordered);
                        var sales_days_14_val = order_dates.Where(s => s.paid_time >= sales_days_14_date).Sum(s => s.bailun_sku_quantity_ordered);
                        var sales_days_30_val = order_dates.Where(s => s.paid_time >= sales_days_30_date).Sum(s => s.bailun_sku_quantity_ordered);
                        if (temp_val < item.sales_average_upper_limit)
                        {
                            var new_data = new dc_auto_return_goods_sku
                            {
                                approval_remarks = "",
                                bailun_sku = itemSku.bailun_sku,
                                monitor_status = "",
                                config_id = item.id,
                                config_name = item.title,
                                create_date = DateTime.Now,
                                no_library_sys_out_status = 0,
                                no_library_sys_push_status = 0,
                                oms_out_status = 0,
                                oms_push_status = 0,
                                retun_quantity = 0,
                                sales_average_14 = order_dates.Where(s => s.paid_time >= sales_days_14_date).Sum(s => s.bailun_sku_quantity_ordered),
                                sales_average_7 = order_dates.Where(s => s.paid_time >= sales_days_7_date).Sum(s => s.bailun_sku_quantity_ordered),
                                sales_average_weight = (sales_days_7_val * 0.5M) + (sales_days_14_val * 0.25M) + (sales_days_30_val * 0.25M),
                                sku_title = itemSku.sku_title,
                                status = 0,
                                stock = itemSku.stock,
                                stock_amount = itemSku.stock * itemSku.unit_price,
                                unit_price = itemSku.unit_price,
                                suppliers_id = itemSku.suppliers_id,
                                suppliers_name = itemSku.suppliers_name,
                                warehouse_code = itemSku.warehouse_code,
                                warehouse_name = itemSku.warehouse_name,
                                approval_date = new DateTime(1991, 1, 1)
                            };
                            conn.Insert(new_data);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 查询规则命中的sku
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static List<sku_dto> GetSkus(MySqlConnection conn, dc_auto_return_goods_config config)
        {
            var sql = @" select 
t1.bailun_sku,
t1.warehouse_code,
t3.warehouse_name,
t2.sku_title_cn as 'sku_title',
t2.suppliers_id,
t2.suppliers_name,
t2.unit_price,
t1.usable_stock as 'stock'
from dc_base_stock as t1 
left join dc_base_sku as t2 on t1.bailun_sku = t2.bailun_sku 
left join dc_base_warehouse as t3 on t1.warehouse_code = t3.warehouse_code
left join dc_base_supplier as t4 on t2.suppliers_id = t4.sup_value
where t1.usable_stock>0
";
            DynamicParameters parameters = new DynamicParameters();

            if (!string.IsNullOrWhiteSpace(config.warehouse_code))
            {
                sql += " and t1.warehouse_code =@warehouse_code ";
                parameters.Add("warehouse_code", config.warehouse_code);
            }
            if (config.has_no_library == 1)
            {
                sql += " and t4.nostock =1 ";
            }
            if (config.has_return == 1)
            {
                sql += " and t4.isaccept_refund =1 ";
            }
            if (config.suppliers_id > 0)
            {
                sql += " and t2.suppliers_id =@suppliers_id ";
                parameters.Add("suppliers_id", config.suppliers_id);
            }
            if (config.first_inbound_days_min > 0)
            {
                sql += " and t1.first_inbound_date <= @first_inbound_days_min ";
                parameters.Add("first_inbound_days_min", DateTime.Now.AddDays(0 - (int)config.first_inbound_days_min));
            }
            if (config.first_inbound_days_max > 0)
            {
                sql += " and t1.first_inbound_date >= @first_inbound_days_max ";
                parameters.Add("first_inbound_days_max", DateTime.Now.AddDays(0 - (int)config.first_inbound_days_max));
            }
            return conn.Query<sku_dto>(sql, parameters).AsList();
        }

        /// <summary>
        /// 查询订单时间
        /// </summary>
        /// <param name="bailun_sku"></param>
        /// <param name="warehouse_code"></param>
        /// <param name="days">天数</param>
        /// <returns></returns>
        public static List<order_dto> GetOrderDateList(MySqlConnection conn, string bailun_sku, string warehouse_code, int days)
        {
            var table_name = "dc_base_oms_sku_30";
            if (days > 90)
            {
                table_name = "dc_base_oms_sku";
            }
            var sql = $@" select paid_time,bailun_sku_quantity_ordered from {table_name} where 
has_delete = 0
and has_scalp = 0
and has_buyer_remark = 0
and has_platsku_remark = 0
and has_innersale = 0
and bailun_sku=@bailun_sku and warehouse_code=@warehouse_code ";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("bailun_sku", bailun_sku);
            parameters.Add("warehouse_code", warehouse_code);
            if (days != 30)
            {
                sql += " paid_time>=@days ";
                parameters.Add("days", DateTime.Now.AddDays(0 - days).ToString("yyyy-MM-dd 00:00:00"));
            }
            return conn.Query<order_dto>(sql, parameters).AsList();
        }


        public static List<dc_auto_return_goods_sku_dto> SkuPage(dc_auto_return_goods_sku_search_dto m, int offset, int limit, ref int total)
        {
            var list = new List<dc_auto_return_goods_sku_dto>();

            try
            {
                var sql = @"select 
t1.*,
( case when t5.`status`=0 or t5.`status` is null then '监控中' else '停止监控' end ) as 'monitor_status_str'
from dc_auto_return_goods_sku as t1 
left join dc_base_warehouse as t2 on t1.warehouse_code = t2.warehouse_code
left join dc_auto_config_sku_warehouse as t5 on t1.bailun_sku = t5.bailun_sku and t1.warehouse_code = t5.warehouse_code
where 1 = 1 ";
                DynamicParameters parameters = new DynamicParameters();
                if (m.monitor_status != null)
                {
                    if (m.monitor_status == 1)
                    {
                        sql += " and t5.`status`=1 ";
                    }
                    else if (m.monitor_status == 2)
                    {
                        sql += " and ( t5.`status`=0 or t5.`status` is null  ) ";
                    }
                }
                if (m.btime != null)
                {
                    sql += " and t1.create_date>=@btime ";
                    parameters.Add("btime", m.btime.Value.ToDayHome());
                }
                if (m.etime != null)
                {
                    sql += " and t1.create_date<=@etime ";
                    parameters.Add("etime", m.etime.Value.ToDayEnd());
                }
                if (!string.IsNullOrWhiteSpace(m.warehousetype))
                {
                    sql += " and t2.hq_type=@warehousetype";
                    parameters.Add("warehousetype", m.warehousetype);
                }
                if (!string.IsNullOrWhiteSpace(m.sku))
                {
                    sql += " and t1.bailun_sku=@bailun_sku";
                    parameters.Add("bailun_sku", m.sku);
                }
                if (m.warehousearea > 0)
                {
                    sql += " and t2.area_id=" + m.warehousearea;
                }
                if (m.warehouse_code != null)
                {
                    sql += $" and t1.warehouse_code=@warehouse_code ";
                    parameters.Add("warehouse_code", m.warehouse_code);
                }
                if (!string.IsNullOrWhiteSpace(m.supplier_name))
                {
                    sql += " and t1.suppliers_name =@suppliers_name ";
                    parameters.Add("suppliers_name", m.supplier_name);
                }
                if (m.status != null)
                {
                    sql += " and t1.status=" + m.status;
                }
                if (m.oms_out_status != null)
                {
                    sql += " and t1.oms_out_status=" + m.oms_out_status;
                }
                if (m.no_library_sys_push_status > 0)
                {
                    sql += " and t1.no_library_sys_push_status=" + m.no_library_sys_push_status;
                }

                total = _connection.QuerySingleOrDefault<int>("select count(0) from (" + sql + ") tb1", parameters);

                var obj = _connection.Query<dc_auto_return_goods_sku_dto>(sql + " limit " + offset + "," + limit, parameters);

                return obj.AsList();

            }
            catch (Exception ex)
            {
                return list;
            }
        }

        /// <summary>
        /// 批量审批
        /// </summary>
        /// <param name="input_data"></param>
        /// <param name="user"></param>
        public static void BatchApproval(batch_approval_input_dto input_data, UserData user)
        {
            _connection.Execute(" update dc_auto_return_goods_sku set `status`=@status,approval_date=now() where `status`=0 and id in @ids", new
            {
                status = input_data.status,
                ids = input_data.ids.Split(',').Select(s => int.Parse(s)).ToList(),
                approval_remarks = input_data.approval_remarks
            });
        }

        /// <summary>
        /// 批量推送
        /// </summary>
        /// <param name="m"></param>
        public static void BatchPush(dc_auto_return_goods_sku_search_dto m, UserData user)
        {
            int total = 0;
            m.status = 1;
            var datas = SkuPage(m, 0, int.MaxValue, ref total);
            if (datas == null || datas.Count <= 0)
            {
                throw new Exception("当前查询条件下，没有审批通过的数据");
            }

            var order_list = GenerateOrder(datas);

            try
            {
                ApiUtility.PushOmsReturnSkuInfo(order_list.Select(s => new Models.ApiDto.api_oms_return_order_push_input_dto()
                {
                    originOrderNo = s.order_data.order_no,
                    receiptAddress = new Models.ApiDto.api_oms_return_order_push_input_dto.receiptAddress_dto
                    {
                        phone = s.order_data.contactphone,
                        address = s.order_data.companyaddress,
                        address2 = "",
                        city = "",
                        CountryCode = "CN",
                        phone2 = "",
                        postalCode = "",
                        stateOrRegion = "",
                        receiver = user.UserName
                    },
                    sellerName = "无库退货",
                    wareHouseNo = s.order_data.warehouse_code,
                    proSkuItems = s.skus.Select(sku => new Models.ApiDto.api_oms_return_order_push_input_dto.proSkuItems_dto()
                    {
                        quantity = sku.quantity,
                        skuNo = sku.bailun_sku
                    }).ToList()
                }).ToList());

                ApiUtility.PushSupplierReturnSkuInfo(order_list.Select(s => new Models.ApiDto.api_distribution_return_order_push_input_dto
                {
                    returnDate = s.order_data.date,
                    returnOrderNo = s.order_data.order_no,
                    returnWarehouse = s.order_data.warehouse_name,
                    returnWarehouseCode = s.order_data.warehouse_code,
                    supplierId = s.order_data.suppliers_id,
                    skuList = s.skus.Select(v => new Models.ApiDto.api_distribution_return_order_push_input_dto.sku_dto
                    {
                        skuCode = v.bailun_sku,
                        skuReturn = v.quantity,
                        skuReturnMonry = v.amount
                    }).ToList()
                }).ToList());



                // 推送成功，修改状态
                _connection.Execute(" update dc_auto_return_goods_order set no_library_push_msg='成功',no_library_push_date=now(),no_library_push_status=1 where id in @ids ", new { ids = order_list.Select(s => s.order_data.id) });
                _connection.Execute(" update dc_auto_return_goods_sku set no_library_sys_push_status=1 where order_id in @order_ids ", new { order_ids = order_list.Select(s => s.order_data.id) });
            }
            catch (Exception ex)
            {
                // 推送成功，修改状态
                _connection.Execute(" update dc_auto_return_goods_order set no_library_push_msg=@no_library_push_msg,no_library_push_date=now(),no_library_push_status=1 where id in @ids ", new { ids = order_list.Select(s => s.order_data.id), no_library_push_msg = ex.Message });
            }




        }

        /// <summary>
        /// 生成订单
        /// </summary>
        public static List<order_list_dto> GenerateOrder(List<dc_auto_return_goods_sku_dto> datas)
        {
            List<order_list_dto> order_list = new List<order_list_dto>();

            using (var conn = MyMySqlConnection._connection)
            {
                conn.Open();
                using (var t = conn.BeginTransaction())
                {
                    foreach (var item in datas.GroupBy(s => new { s.suppliers_id, s.suppliers_name, s.warehouse_code, s.warehouse_name }))
                    {
                        var sup_data = conn.QueryFirstOrDefault<dc_base_supplier>(" select * from dc_base_supplier where sup_value=@sup_value ", new { sup_value = item.Key.suppliers_id });
                        var new_order_data = new dc_auto_return_goods_order
                        {
                            warehouse_name = item.Key.warehouse_name,
                            warehouse_code = item.Key.warehouse_code,
                            suppliers_name = item.Key.suppliers_name,
                            suppliers_id = item.Key.suppliers_id,
                            companyaddress = sup_data.companyaddress,
                            contactname = sup_data.contactname,
                            contactphone = sup_data.contactphone,
                            date = DateTime.Now,
                            oms_push_status = 0,
                            no_library_push_status = 0
                        };

                        // 计算单号
                        // 查询当前最大单号
                        var max_order_no = conn.QueryFirstOrDefault<string>(" select dc_auto_return_goods_order from dc_auto_return_goods_order order by id desc limit 1 ");
                        var number_str = "001";
                        if (!string.IsNullOrWhiteSpace(max_order_no))
                        {
                            // 提取流水号
                            var str_list = max_order_no.Split('-');
                            number_str = str_list[str_list.Length - 1];
                        }

                        new_order_data.order_no = $"{sup_data.city}-{sup_data.short_name}-{new_order_data.date.ToString("yyyyMMdd")}-退-{number_str}";
                        var new_order_id = conn.Insert(new_order_data, t) ?? 0;
                        order_list_dto order_list_item = new order_list_dto() { skus = new List<dc_auto_return_goods_order_sku>() };
                        new_order_data.id = new_order_id;
                        order_list_item.order_data = new_order_data;
                        foreach (var itemSku in item.AsEnumerable())
                        {
                            var new_sku_data = new dc_auto_return_goods_order_sku
                            {
                                order_id = new_order_id,
                                amount = itemSku.stock_amount,
                                bailun_sku = itemSku.bailun_sku,
                                quantity = (int)itemSku.stock
                            };
                            new_sku_data.id = conn.Insert(new_sku_data, t) ?? 0;
                            order_list_item.skus.Add(new_sku_data);
                        }

                        conn.Execute(" update dc_auto_return_goods_sku set order_id=@order_id where id in @ids ", new { order_id = new_order_id, ids = item.Select(s => s.id).ToList() }, t);
                    }

                    t.Commit();
                }
            }


            return order_list;
        }



        public class order_dto
        {
            public DateTime paid_time { get; set; }
            public int bailun_sku_quantity_ordered { get; set; }
        }
        public class sku_dto
        {
            public string bailun_sku { get; set; }
            public string warehouse_code { get; set; }
            public string warehouse_name { get; set; }
            public string sku_title { get; set; }
            public int suppliers_id { get; set; }
            public string suppliers_name { get; set; }
            public decimal unit_price { get; set; }
            public decimal stock { get; set; }
        }

        /// <summary>
        /// 计算可以退货的sku
        /// </summary>
        public static void NewCalculation()
        {
            var nowHome = DateTime.Now.ToDayHome();
            var conn = _connection;
            var configs = conn.Query<dc_auto_return_goods_config>(" select * from dc_auto_return_goods_config where status=0 ");
            foreach (var item in configs)
            {
                var skus = NewGetSkus(MyMySqlConnection._connection_read_only, item);
                if (skus != null && skus.Count >= 1)
                {
                    var max_days = Math.Max((int)item.sum_sales_days, Math.Max(item.sales_days_1, item.sales_days_2));
                    // 销量过滤
                    foreach (var itemSku in skus)
                    {
                        var order_dates = GetOrderDateList(MyMySqlConnection._connection_read_only, itemSku.bailun_sku, itemSku.warehouse_code, Math.Max(30, max_days));
                        var sales_days_1_date = DateTime.Now.AddDays(0 - item.sales_days_1).ToDayHome();
                        var sales_days_1_val = order_dates.Where(s => s.paid_time >= sales_days_1_date).Sum(s => s.bailun_sku_quantity_ordered);
                        var sales_days_2_date = DateTime.Now.AddDays(0 - item.sales_days_2).ToDayHome();
                        var sales_days_2_val = order_dates.Where(s => s.paid_time >= sales_days_2_date).Sum(s => s.bailun_sku_quantity_ordered);

                        var sales_days_14_date = DateTime.Now.AddDays(0 - 14).ToDayHome();
                        var sales_days_7_date = DateTime.Now.AddDays(0 - 7).ToDayHome();
                        var sales_days_30_date = DateTime.Now.AddDays(0 - 30).ToDayHome();
                        var temp_val = (sales_days_1_val * item.sales_weight_1) + (sales_days_2_val * item.sales_weight_2);
                        var sales_days_7_val = order_dates.Where(s => s.paid_time >= sales_days_7_date).Sum(s => s.bailun_sku_quantity_ordered);
                        var sales_days_14_val = order_dates.Where(s => s.paid_time >= sales_days_14_date).Sum(s => s.bailun_sku_quantity_ordered);
                        var sales_days_30_val = order_dates.Where(s => s.paid_time >= sales_days_30_date).Sum(s => s.bailun_sku_quantity_ordered);

                        //指定天数的销量汇总
                        var sum_sales_days_date = DateTime.Now.AddDays(0 - (int)(item.sum_sales_days)).ToDayHome();
                        var sum_sales_days_sum = order_dates.Where(s => s.paid_time >= sum_sales_days_date).Sum(s => s.bailun_sku_quantity_ordered);

                        // 判断销量是否达标
                        if (item.sales_average_upper_limit > 0)
                        {
                            if (item.sales_average_upper_limit > temp_val)
                            {
                                //日均加权销量不合格
                                continue;
                            }
                        }


                        if (item.sum_sales_min > 0)
                        {
                            if (sum_sales_days_sum < item.sum_sales_min)
                            {
                                //累积销量不合格
                                continue;
                            }
                        }

                        if (item.sum_sales_max > 0)
                        {
                            if (sum_sales_days_sum > item.sum_sales_max)
                            {
                                //累积销量不合格
                                continue;
                            }
                        }

                        // 查询这个sku所有的采购单
                        var purchase_list = _connection.Query<dc_base_purchase_details>(@" select * from dc_base_purchase_details as t1 
where t1.bailun_sku=@bailun_sku and t1.warehouse_from_code=@warehouse_code  and `status`!=-1 and t1.can_7day_refund=1 ", new
                        {
                            bailun_sku = itemSku.bailun_sku,
                            warehouse_code = itemSku.warehouse_code
                        }).ToList();
                        foreach (var itemPurchase in purchase_list)
                        {
                            // 看看是否过了退货期
                            if (itemPurchase.last_signtime != null)
                            {
                                var latest_return_date = itemPurchase.last_signtime.Value.AddDays(6).ToDayEnd();
                                if (latest_return_date > nowHome)
                                {
                                    var db_data = new dc_aims_return_goods
                                    {
                                        bailun_sku = itemPurchase.bailun_sku,
                                        suppliers_name = itemPurchase.deliver_name ?? "",
                                        confirm_return_count = 0,
                                        date = DateTime.Now,
                                        date_str = DateTime.Now.ToString("yyyy-MM-dd"),
                                        purchase_count = itemPurchase.quantity_purchase,
                                        buy_name = itemPurchase.buyer_name ?? "",
                                        latest_return_date = latest_return_date,
                                        order_1688_no = itemPurchase.alibaba_order_id ?? "",
                                        purchase_id = itemPurchase.purchase_id ?? "",
                                        retuen_goods_count = 0,
                                        return_addrs = "",
                                        rule_title = item.title,
                                        sign_date = itemPurchase.last_signtime.Value,
                                        stock = itemSku.stock,
                                        unit_price = itemSku.unit_price,
                                        warehouse_code = itemSku.warehouse_code,
                                        warehouse_name = itemSku.warehouse_name
                                    };

                                    db_data.id = _connection.QueryFirstOrDefault<int?>(" select * from dc_aims_return_goods where bailun_sku=@bailun_sku and warehouse_code=@warehouse_code and purchase_id=@purchase_id and date_str=@date_str ",new {
                                        bailun_sku = db_data.bailun_sku,
                                        warehouse_code = db_data.warehouse_code,
                                        purchase_id = db_data.purchase_id,
                                        date_str= db_data.date_str
                                    }) ??0;
                                    if (db_data.id <= 0)
                                    {
                                        _connection.Insert(db_data);
                                    }
                                    
                                }

                            }

                        }

                    }
                }
            }
        }

        /// <summary>
        /// 查询规则命中的sku
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static List<sku_dto> NewGetSkus(MySqlConnection conn, dc_auto_return_goods_config config)
        {
            var sql = @" select 
t1.bailun_sku,
t1.warehouse_code,
t3.warehouse_name,
t2.sku_title_cn as 'sku_title',
t2.suppliers_id,
t2.suppliers_name,
t2.unit_price,
t1.usable_stock as 'stock'
from dc_base_stock as t1 
left join dc_base_sku as t2 on t1.bailun_sku = t2.bailun_sku 
left join dc_base_warehouse as t3 on t1.warehouse_code = t3.warehouse_code
left join dc_base_supplier as t4 on t2.suppliers_id = t4.sup_value
where t1.usable_stock>0
";
            DynamicParameters parameters = new DynamicParameters();

            if (!string.IsNullOrWhiteSpace(config.warehouse_code))
            {
                sql += " and t1.warehouse_code =@warehouse_code ";
                parameters.Add("warehouse_code", config.warehouse_code);
            }
            if (!string.IsNullOrWhiteSpace(config.bailun_skus))
            {
                sql += " and t1.bailun_sku in @bailun_skus ";
                parameters.Add("bailun_skus", config.bailun_skus.Split(',').ToList());
            }
            if (!string.IsNullOrWhiteSpace(config.goods_codes))
            {
                sql += " and t2.product_code in @goods_codes ";
                parameters.Add("goods_codes", config.goods_codes.Split(',').ToList());
            }
            //if (config.has_no_library == 1)
            //{
            //    sql += " and t4.nostock =1 ";
            //}
            //if (config.has_return == 1)
            //{
            //    sql += " and t4.isaccept_refund =1 ";
            //}
            if (config.suppliers_id > 0)
            {
                sql += " and t2.suppliers_id =@suppliers_id ";
                parameters.Add("suppliers_id", config.suppliers_id);
            }
            if (config.first_inbound_days_min > 0)
            {
                sql += " and t1.first_inbound_date <= @first_inbound_days_min ";
                parameters.Add("first_inbound_days_min", DateTime.Now.AddDays(0 - (int)config.first_inbound_days_min));
            }
            if (config.first_inbound_days_max > 0)
            {
                sql += " and t1.first_inbound_date >= @first_inbound_days_max ";
                parameters.Add("first_inbound_days_max", DateTime.Now.AddDays(0 - (int)config.first_inbound_days_max));
            }
            return conn.Query<sku_dto>(sql, parameters).AsList();
        }
    }

}
