using AutoTurnOver.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using AutoTurnOver.Utility;
using System.Linq;
using AutoTurnOver.Models.Base;
using AutoTurnOver.Models.Report;
using AutoTurnOver.Models.auto;
using AutoTurnOver.DB;
using Dapper;
using AutoTurnOver.Models.ApiDto;

namespace AutoTurnOver.Services
{
    public class ConfigServices
    {
        #region 安全库存规则配置

        /// <summary>
        /// 获取安全库存规则设置分页列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_auto_config_safe_inventoryDto> InventoryList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.InventoryList(m, offset, limit, ref total);
        }


        /// <summary>
        /// 保存安全库存规则
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveInventory(Models.dc_auto_config_safe_inventory m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            var objWarehouse = DB.common.GetWareHouseByCode(m.warehouse_code);
            if (objWarehouse == null)
            {
                return "系统找不到该仓库。";
            }
            m.warehouse_name = objWarehouse.warehouse_name;

            if (m.type == (int)Safe_inventoryType.仓库_SKU_定值)
            {
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "Sku不能为空！";
                }
                if (m.param <= 0)
                {
                    return "安全库存必填";
                }
            }
            else if (m.type == (int)Safe_inventoryType.仓库_分类_定值)
            {
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "请选择分类";
                }
                if (m.param <= 0)
                {
                    return "安全库存必填";
                }
                var cID = 0;
                if (!int.TryParse(m.variable_code, out cID))
                {
                    return "请选择分类";
                }
                var cModel = ApiServices.GetCategoryById(cID);
                m.variable_name = cModel.C_CNAME;
            }
            else if (m.type == (int)Safe_inventoryType.仓库_SKU_按历史计算 || m.type == (int)Safe_inventoryType.仓库_SKU_按预测计算 || m.type == (int)Safe_inventoryType.仓库_按历史计算)
            {
                if (m.weighting_coefficient_seven <= 0)
                {
                    return "请填写7天权重";
                }
                if (m.weighting_coefficient_fourteen <= 0)
                {
                    return "请填写14天权重";
                }
                if (m.weighting_coefficient_thirty <= 0)
                {
                    return "请填写30天权重";
                }
                if (m.weighting_coefficient_thirty + m.weighting_coefficient_seven + m.weighting_coefficient_fourteen != 1)
                {
                    return "三个权重加起来不等于 1";
                }
            }

            if (m.type == (int)Safe_inventoryType.仓库_按历史计算)
            {
                if (m.param < 0)
                {
                    return "倍数必填";
                }
                m.variable_code = "";
                m.variable_name = "";
            }


            if (m.type == (int)Safe_inventoryType.仓库_SKU_定值 || m.type == (int)Safe_inventoryType.仓库_SKU_按历史计算 || m.type == (int)Safe_inventoryType.仓库_SKU_按预测计算)
            {
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "Sku不能为空！";
                }
                var objProduct = DB.common.GetPrductBySku(m.variable_code);
                if (objProduct == null)
                {
                    return "系统找不到该Sku。";
                }
                m.variable_name = objProduct.sku_title_cn;
            }


            return DB.db_config.SaveInventory(m, username);
        }



        /// <summary>
        /// 获取安全库存规则设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_auto_config_safe_inventory GetInventoryById(int id)
        {
            return DB.db_config.GetInventoryById(id);
        }

        #endregion

        #region 销量上限规则配置

        /// <summary>
        /// 获取安全库存规则设置分页列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_auto_config_sales_upper_limitDto> SalesUpperLimitList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.SalesUpperLimitList(m, offset, limit, ref total);
        }


        /// <summary>
        /// 保存安全库存规则
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveSalesUpperLimit(Models.dc_auto_config_sales_upper_limit m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            var objWarehouse = DB.common.GetWareHouseByCode(m.warehouse_code);
            if (objWarehouse == null)
            {
                return "系统找不到该仓库。";
            }
            m.warehouse_name = objWarehouse.warehouse_name;

            if (m.type == (int)Safe_UpperLimitType.仓库_SKU_定值)
            {
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "Sku不能为空！";
                }
                if (m.param <= 0)
                {
                    return "安全库存必填";
                }
            }
            else if (m.type == (int)Safe_UpperLimitType.仓库_分类_定值)
            {
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "请选择分类";
                }
                if (m.param <= 0)
                {
                    return "安全库存必填";
                }
                var cID = 0;
                if (!int.TryParse(m.variable_code, out cID))
                {
                    return "请选择分类";
                }
                var cModel = ApiServices.GetCategoryById(cID);
                m.variable_name = cModel.C_CNAME;
            }
            else if (m.type == (int)Safe_UpperLimitType.仓库_SKU_按历史计算)
            {
                if (m.param < 0)
                {
                    return "倍数必填";
                }
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "Sku不能为空！";
                }
                if (m.weighting_coefficient_seven <= 0)
                {
                    return "请填写7天权重";
                }
                if (m.weighting_coefficient_fourteen <= 0)
                {
                    return "请填写14天权重";
                }
                if (m.weighting_coefficient_thirty <= 0)
                {
                    return "请填写30天权重";
                }
                if (m.weighting_coefficient_thirty + m.weighting_coefficient_seven + m.weighting_coefficient_fourteen != 1)
                {
                    return "三个权重加起来不等于 1";
                }
            }




            if (m.type == 1 || m.type == 11 || m.type == 12)
            {
                var objProduct = DB.common.GetPrductBySku(m.variable_code);
                if (objProduct == null)
                {
                    return "系统找不到该Sku。";
                }
                m.variable_name = objProduct.sku_title_cn;
            }


            return DB.db_config.SaveSalesUpperLimit(m, username);
        }



        /// <summary>
        /// 获取安全库存规则设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_auto_config_sales_upper_limit GetSalesUpperLimitById(int id)
        {
            return DB.db_config.GetSalesUpperLimitById(id);
        }

        #endregion

        #region 供应链长度规则配置

        /// <summary>
        /// 获取供应链长度规则设置分页列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_auto_config_delivery_dto> ConfigDeliveryList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.ConfigDeliveryList(m, offset, limit, ref total);
        }


        /// <summary>
        /// 保存安全库存规则
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveConfigDelivery(Models.dc_auto_config_delivery m, string username)
        {

            if (m.tranfer_bale <= 0)
            {
                return "调拨打包天数必填！";
            }
            if (m.tranfer_head <= 0)
            {
                return "调拨头程天数必填！";
            }
            if (m.abroad_inbound <= 0)
            {
                return "海外仓入库天数必填！";
            }

            if (m.type == (int)dc_auto_config_delivery_dto.type_enum.仓库)
            {
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "仓库不能为空！";
                }

                var objWarehouse = DB.common.GetWareHouseByCode(m.variable_code);
                if (objWarehouse == null)
                {
                    return "系统找不到该仓库。";
                }
                m.variable_name = objWarehouse.warehouse_name;
            }
           
            else if (m.type == (int)dc_auto_config_delivery_dto.type_enum.仓库编码_SKU)
            {
                if (string.IsNullOrWhiteSpace(m.variable_code))
                {
                    return "Sku不能为空！";
                }
                var objProduct = DB.common.GetPrductBySku(m.variable_code);
                if (objProduct == null)
                {
                    return "系统找不到该Sku。";
                }
                m.variable_name = objProduct.sku_title_cn;
            }

            m.bailun_sku = (m.bailun_sku ?? "");
            return DB.db_config.SaveConfigDelivery(m, username);
        }



        /// <summary>
        /// 获取安全库存规则设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_auto_config_delivery GetConfigDeliveryById(int id)
        {
            return DB.db_config.GetConfigDeliveryById(id);
        }

        #endregion

        #region 备货天数配置

        /// <summary>
        /// 获取备货天数设置分页列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_auto_config_stock_up_days> StockUpList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.StockUpList(m, offset, limit, ref total);
        }


        /// <summary>
        /// 保存备货天数
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveStockUp(Models.dc_auto_config_stock_up_days m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            var objWarehouse = DB.common.GetWareHouseByCode(m.warehouse_code);
            if (objWarehouse == null)
            {
                return "系统找不到该仓库。";
            }
            m.warehouse_name = objWarehouse.warehouse_name;

            if (m.stock_up_days < 1)
            {
                return "备货天数不可小于1";
            }

            return DB.db_config.SaveStockUp(m, username);
        }



        /// <summary>
        /// 获取备货天数设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_auto_config_stock_up_days GetStockUpById(int id)
        {
            return DB.db_config.GetStockUpById(id);
        }

        #endregion

        /// <summary>
        /// 获取安全库存规则设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string MonitorStatus(string bailun_sku, string warehouse_code, int monitor_status, UserData user)
        {
            return DB.db_config.MonitorStatus(bailun_sku, warehouse_code, monitor_status, user);
        }

        public string BatchMonitorStatus(string ids, int monitor_status, int time_type, UserData user, string explain)
        {
            try
            {
                return DB.db_config.BatchMonitorStatus(ids, monitor_status, time_type, user, explain);
            }
            catch (Exception ex)
            {

                throw;
            }
            
        }

        /// <summary>
        /// 监控操作日志查询
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public Page<dc_base_monitor_status_log_output_dto> GetMonitorStatusLogPageList(dc_base_monitor_status_log_input_dto search)
        {
            return db_config.GetMonitorStatusLogPageList(search);
        }


        public string BatchClearanceStatus(string ids, int monitor_status, int time_type, UserData user)
        {
            try
            {
                return DB.db_config.BatchClearanceStatus(ids, monitor_status, time_type, user);
            }
            catch (Exception ex)
            {

                throw;
            }
            
        }
        public string BatchReturnGoodsStatus(string ids, int monitor_status, UserData user)
        {
            return DB.db_config.BatchReturnGoodsStatus(ids, monitor_status, user);
        }

        public string BatchTortStatus(string ids, int monitor_status, UserData user)
        {
            return DB.db_config.BatchTortStatus(ids, monitor_status, user);
        }
        
        
        public string UpdateStorageCapacity(string ids, int status, UserData user)
        {
            return DB.db_config.UpdateStorageCapacity(ids, status, user);
        }
        


        #region fba共享仓发货仓配置

        /// <summary>
        /// fba共享仓发货仓配置
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_base_stock_config_fba> StockFbaList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.StockFbaList(m, offset, limit, ref total);
        }

        public List<dc_base_stock_config_fba_lose> StockFbaLoseList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.StockFbaLoseList(m, offset, limit, ref total);
        }

        /// <summary>
        /// 保存备货天数
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveStockFba(Models.dc_base_stock_config_fba m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            if (string.IsNullOrWhiteSpace(m.platform_sku))
            {
                return "请填写平台sku！";
            }

            // 查询百伦sku

            var objWarehouse = DB.common.GetWareHouseByCode(m.warehouse_code);
            if (objWarehouse == null)
            {
                return "系统找不到该仓库。";
            }
            m.warehouse_name = objWarehouse.warehouse_name;


            return DB.db_config.SaveStockFba(m, username);
        }



        /// <summary>
        /// 获取备货天数设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_base_stock_config_fba GetStockFbaById(int id)
        {
            return DB.db_config.GetStockFbaById(id);
        }

        #endregion

        #region 销量配置
        /// <summary>
        /// 获取销量配置设置分页列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_auto_sales_config> SalesConfigList(dc_auto_sales_config_search_dto m, int offset, int limit, ref int total)
        {
            return DB.db_config.SalesConfigList(m, offset, limit, ref total);
        }

        /// <summary>
        /// 保存安全库存规则
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveSalesConfig(Models.dc_auto_sales_config m, string username)
        {
            return DB.db_config.SaveSalesConfig(m, username);
        }

        /// <summary>
        /// 获取安全库存规则设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_auto_sales_config GetSalesConfigById(int id)
        {
            return DB.db_config.GetSalesConfigById(id);
        }

        /// <summary>
        /// 获取所有平台
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<string> ListPlatformType()
        {
            return DB.db_config.ListPlatformType();
        }

        /// <summary>
        /// 获取所有站点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<string> ListWebSite()
        {
            return DB.db_config.ListWebSite();
        }

        #endregion

        #region 动态备货sku

        public List<dc_auto_stock_up_range_dto> StockUpRangeList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.StockUpRangeList(m, offset, limit, ref total);
        }

        public string SaveStockUpRange(Models.dc_auto_stock_up_range m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            // 查询百伦sku
            var objWarehouse = DB.common.GetWareHouseByCode(m.warehouse_code);
            if (objWarehouse == null)
            {
                return "系统找不到该仓库。";
            }
            m.warehouse_name = objWarehouse.warehouse_name;


            return DB.db_config.SaveStockUpRange(m, username);
        }

        public dc_auto_stock_up_range GetStockUpRangeById(int id)
        {
            return DB.db_config.GetStockUpRangeById(id);
        }

        #endregion

        #region 动态备货sku

        public List<dc_auto_jit_tag_group> JitTagGroupList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.JitTagGroupList(m, offset, limit, ref total);
        }

        public string SaveJitTagGroup(Models.dc_auto_jit_tag_group m, string username)
        {
            return DB.db_config.SaveJitTagGroup(m, username);
        }

        public dc_auto_jit_tag_group GetJitTagGroupById(int id)
        {
            return DB.db_config.GetJitTagGroupById(id);
        }

        public List<dc_auto_jit_tag_group> JitTagGroupAll()
        {
            return DB.db_config.JitTagGroupAll();
        }

      public void  BatchStockUp(batch_stock_up_input_dto data)
        {
            DB.db_config.BatchStockUp(data);
        }

        #endregion

        #region 预测销量 人工

        public List<dc_config_forecast_sales> ForecastSalesConfigList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.db_config.ForecastSalesConfigList(m, offset, limit, ref total);
        }

        public string SaveForecastSalesConfig(Models.dc_config_forecast_sales m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            var objWarehouse = DB.common.GetWareHouseByCode(m.warehouse_code);
            if (objWarehouse == null)
            {
                return "系统找不到该仓库。";
            }
            m.warehouse_name = objWarehouse.warehouse_name;
           return DB.db_config.SaveForecastSalesConfig(m, username);
        }

        public dc_config_forecast_sales GetForecastSalesConfigById(int id)
        {
            return DB.db_config.GetForecastSalesConfigById(id);
        }

        public DataTable ForecastSalesConfigImport(Stream fileInfo, UserData user)
        {
            var data_set = EPPlusHelper.ReadExcel(fileInfo);
            var table = data_set.Tables[0];
            if (!table.Columns.Contains("导入结果")) table.Columns.Add("导入结果");
            if (!table.Columns.Contains("导入异常")) table.Columns.Add("导入异常");

            var warehouse_list = DB.common.ListWareHouse(null,null);
            
            DateTime now = DateTime.Now;
            
            int index = 1;
            foreach (DataRow row in table.Rows)
            {
                index++;
                try
                {
                    var bailun_sku = row["SKU"].ToString();
                    var warehouse_code = row["仓库编码"].ToString();
                    var start_date_str = row["开始时间"].ToString();
                    var end_date_str = row["结束时间"].ToString();
                    var sales_str = row["预测销量"].ToString();

                    if (string.IsNullOrWhiteSpace(bailun_sku)) throw new Exception("SKU必填");
                    if (string.IsNullOrWhiteSpace(warehouse_code)) throw new Exception("warehouse_code必填");
                    var warehouse_data = warehouse_list.SingleOrDefault(s => s.warehouse_code.Equals(warehouse_code, StringComparison.OrdinalIgnoreCase));
                    if (warehouse_data == null) { throw new Exception("仓库在系统中找不到"); }
                    var warehouse_name = warehouse_data.warehouse_name;

                    decimal sales = 0;
                    if(!decimal.TryParse(sales_str,out sales))
                    {
                        throw new Exception("销量格式异常");
                    }

                    DateTime start_date = DateTime.Now;
                    if (!DateTime.TryParse(start_date_str, out start_date))
                    {
                        throw new Exception("开始时间格式异常");
                    }

                    DateTime end_date = DateTime.Now;
                    if (!DateTime.TryParse(end_date_str, out end_date))
                    {
                        throw new Exception("结束时间格式异常");
                    }

                    var new_data = new dc_config_forecast_sales
                    {
                        bailun_sku = bailun_sku,
                        warehouse_name = warehouse_name,
                        warehouse_code = warehouse_code,
                        create_user = user.UserName,
                        sales = sales,
                        start_date = start_date,
                        end_date = end_date
                    };

                    DB.db_config.SaveForecastSalesConfig(new_data, user.UserName);

                    row["导入结果"] = "成功";
                    row["导入异常"] = "";
                }
                catch (Exception ex)
                {
                    row["导入结果"] = "失败";
                    row["导入异常"] = ex.Message;
                }
            }
            return table;
        }
        public DataTable SalesDayConfigImport(Stream fileInfo, UserData user)
        {
            var data_set = EPPlusHelper.ReadExcel(fileInfo);
            var table = data_set.Tables[0];
            if (!table.Columns.Contains("导入结果")) table.Columns.Add("导入结果");
            if (!table.Columns.Contains("导入异常")) table.Columns.Add("导入异常");

            var warehouse_list = DB.common.ListWareHouse(null,null);
            
            DateTime now = DateTime.Now;
            
            int index = 1;
            foreach (DataRow row in table.Rows)
            {
                index++;
                try
                {
                    var bailun_sku = row["SKU"].ToString();
                    var warehouse_code = row["仓库编码"].ToString();

                    if (string.IsNullOrWhiteSpace(bailun_sku)) throw new Exception("SKU必填");
                    if (string.IsNullOrWhiteSpace(warehouse_code)) throw new Exception("warehouse_code必填");
                    var warehouse_data = warehouse_list.SingleOrDefault(s => s.warehouse_code.Equals(warehouse_code, StringComparison.OrdinalIgnoreCase));
                    if (warehouse_data == null) { throw new Exception("仓库在系统中找不到"); }
                    var warehouse_name = warehouse_data.warehouse_name;

                    //if (action == "作废")
                    //{
                    //    var count =  MyMySqlConnection._connection.Execute(" delete from sales_day_config where bailun_sku_warehouse_code=@bailun_sku_warehouse_code ",new {
                    //        bailun_sku_warehouse_code = $"{bailun_sku}{warehouse_code}"
                    //    });
                    //    if (count <= 0)
                    //    {
                    //        throw new Exception("数据不存在");
                    //    }
                    //}
                    //else
                    {



                        var cols = table.Columns;
                        foreach (DataColumn col in cols)
                        {
                            if (col.ColumnName.Contains("销量") && col.ColumnName.Length>20)
                            {
                                decimal sales = 0;
                                var salesObj = row[col.ColumnName];
                                if (salesObj != null)
                                {
                                    if (!decimal.TryParse(salesObj.ToString(), out sales))
                                    {
                                        throw new Exception("销量格式异常");
                                    }

                                    // 取开始结束时间
                                    var btime = DateTime.Parse(col.ColumnName.Substring(2,10));
                                    var etime = DateTime.Parse(col.ColumnName.Substring(13,10));
                                    var s_sales =( sales / ((int)Math.Ceiling((etime - btime).TotalDays +1)) ) ;
                                    while (btime.ToDayHome()<= etime.ToDayEnd())
                                    {
                                        var new_data = new sales_day_config_input_dto
                                        {
                                            bailun_sku = bailun_sku,
                                            warehouse_code = warehouse_code,
                                            sales = s_sales,
                                            date = btime
                                        };
                                        DB.db_config.SaveSalesDayConfig(new_data, user,false);

                                        btime = btime.AddDays(1);
                                    }
                                  
                                }
                             
                            }
                            
                        }

                       
                    }

                    dc_base_stock_dao.AddData(new dc_base_stock {
                    bailun_sku = bailun_sku,
                    warehouse_code = warehouse_code,
                    gmt_create = DateTime.Now,
                    gmt_modified = DateTime.Now,
                        create_time =DateTime.Now,
                       update_time = DateTime.Now,
                        source_from = 4 // 标记来源是导销量
                    });

                    MyMySqlConnection._connection.Insert(new dc_base_queue
                    {
                        submit_date = DateTime.Now,
                        error_message = "",
                        consume_date = null,
                        error_stack_trace = "",
                        message = new { bailun_sku = bailun_sku, warehouse_code = warehouse_code }.ToJson(),
                        type = "刷新周转表",
                        remarks = "配置预测销量"
                    });


                    row["导入结果"] = "成功";
                    row["导入异常"] = "";
                }
                catch (Exception ex)
                {
                    row["导入结果"] = "失败";
                    row["导入异常"] = ex.Message;
                }
            }
            return table;
        }

        /// <summary>
        /// 默认头程方式
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public DataTable HeadConfigImport(Stream fileInfo, UserData user)
        {
            var data_set = EPPlusHelper.ReadExcel(fileInfo);
            var table = data_set.Tables[0];
            if (!table.Columns.Contains("导入结果")) table.Columns.Add("导入结果");
            if (!table.Columns.Contains("导入异常")) table.Columns.Add("导入异常");

            var warehouse_list = DB.common.ListWareHouse(null,null);
            
            DateTime now = DateTime.Now;

            var logs = ApiUtility.ShipLogisticsList();
            int index = 1;
            foreach (DataRow row in table.Rows)
            {
                index++;
                try
                {
                    var bailun_sku = row["SKU"].ToString();
                    var warehouse_code = row["仓库编码"].ToString();
                    var head_transport = row["头程运输方式"].ToString();
                    var logistics_code = row["渠道"].ToString();

                    if (string.IsNullOrWhiteSpace(bailun_sku)) throw new Exception("SKU必填");
                    if (string.IsNullOrWhiteSpace(warehouse_code)) throw new Exception("warehouse_code必填");
                    var warehouse_data = warehouse_list.SingleOrDefault(s => s.warehouse_code.Equals(warehouse_code, StringComparison.OrdinalIgnoreCase));
                    if (warehouse_data == null) { throw new Exception("仓库在系统中找不到"); }
                    var warehouse_name = warehouse_data.warehouse_name;

                    if (!string.IsNullOrWhiteSpace(logistics_code))
                    {
                        var log_data = logs.SingleOrDefault(s => s.Line_Code.Equals(logistics_code, StringComparison.OrdinalIgnoreCase));
                        if (log_data == null) { throw new Exception("渠道在系统中找不到"); }
                    }
                    

                    if (string.IsNullOrWhiteSpace(head_transport))
                    {
                        throw new Exception("运输方式必填");
                    }
                    else
                    {
                        if(head_transport!="空运" && head_transport!="海运" && head_transport != "铁路运输")
                        {
                            throw new Exception("运输方式异常: 目前只支持 （空运、海运、铁路运输）");
                        }
                    }


                    var new_data = new batch_set_head_transport_input_dto
                    {
                        head_transport = head_transport,
                        logistics_code = logistics_code,
                        ids = new List<string> {
                            (MyMySqlConnection._connection_read_only.QueryFirstOrDefault<int?>(" select * from dc_auto_turnover where bailun_sku=@bailun_sku and warehouse_code=@warehouse_code ",new{
                            bailun_sku = bailun_sku,
                            warehouse_code = warehouse_code
                            })??0).ToString()
                        }
                    };

                    DB.db_config.BatchSetHeadTransport(new_data, user);


                    row["导入结果"] = "成功";
                    row["导入异常"] = "";
                }
                catch (Exception ex)
                {
                    row["导入结果"] = "失败";
                    row["导入异常"] = ex.Message;
                }
            }
            return table;
        }

        #endregion

        #region 暴增

        public List<dc_auto_uprush_config_dto> UprushConfigList(dc_auto_uprush_config_search_dto m, int offset, int limit, ref int total)
        {
            return DB.db_config.UprushConfigList(m, offset, limit, ref total);
        }

        public string SaveUprushConfig(Models.dc_auto_uprush_config m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code) && string.IsNullOrWhiteSpace(m.hq_type))
            {
                return "请选择仓库或仓库类型！";
            }

            if (!string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                // 查询百伦sku
                var objWarehouse = DB.common.GetWareHouseByCode(m.warehouse_code);
                if (objWarehouse == null)
                {
                    return "系统找不到该仓库。";
                }
            }
           
            return DB.db_config.SaveUprushConfig(m, username);
        }

        public dc_auto_uprush_config GetUprushConfigById(int id)
        {
            return DB.db_config.GetUprushConfigById(id);
        }

        #endregion

        #region 销量预测配置

        public Page<dc_auto_sales_forecast_config_dto> SalesForecastConfigList(dc_auto_sales_forecast_config_search_dto m)
        {
            return DB.db_config.SalesForecastConfigList(m);
        }

        public void SaveSalesForecastConfig(Models.dc_auto_sales_forecast_config_dto m, string username)
        {
            if (m.screen_type <=0)
            {
                throw new Exception("筛选类型必选");
            }
            if (string.IsNullOrWhiteSpace(m.warehouse_area_id)&& string.IsNullOrWhiteSpace(m.warehouse_code)&& string.IsNullOrWhiteSpace(m.warehouse_type))
            {
                throw new Exception("仓库类型、国家、仓库 中，至少选择一种");
            }
            if (string.IsNullOrWhiteSpace(m.title))
            {
                throw new Exception("规则标题必填");
            }
            foreach (var item in m.stages)
            {
                if (item.index == 1
                    ||
                    (m.screen_type==1 && (item.duration_upper_limit>0 || item.duration_lower_limit>0))
                    ||
                     (m.screen_type == 2 && (item.sales_upper_limit > 0 || item.sales_lower_limit > 0))
                    )
                {
                    if (item.one_ratio + item.two_ratio + item.three_ratio != 1)
                    {
                        throw new Exception($" 第 {item.index} 阶段的 三个时间段范围比例相加不等 1 ");
                    }

                    if (item.one_n2 + item.one_n4 + item.one_n6 != 1)
                    {
                        throw new Exception($" 第 {item.index} 阶段的 第 1 个时间段范围 的 3个加权值相加不等与1 ");
                    }
                    if (item.two_n2 + item.two_n4 + item.two_n6 != 1 && item.two_ratio > 0)
                    {
                        throw new Exception($" 第 {item.index} 阶段的  第 2 个时间段范围 的 3个加权值相加不等与1 ");
                    }
                    if (item.three_n2 + item.three_n4 + item.three_n6 != 1 && item.three_ratio>0)
                    {
                        throw new Exception($" 第 {item.index} 阶段的  第 3 个时间段范围 的 3个加权值相加不等与1 ");
                    }
                }
                else
                {
                    if (item.index == 1)
                    {
                        throw new Exception($"第1阶段的 {(m.screen_type==1?"入库时长":"销量范围")} 必填");
                    }
                }
               
            }
             DB.db_config.SaveSalesForecastConfig(m, username);
        }

        public dc_auto_sales_forecast_config_dto GetSalesForecastConfigById(int id)
        {
            return DB.db_config.GetSalesForecastConfigById(id);
        }
        public void DelSalesForecastConfig(int id)
        {
            DB.db_config.DelSalesForecastConfig(id);
        }

        #endregion

        #region 现金流结算方式

        public List<dc_report_cash_flow_config_dto> CashFlowList(dc_report_cash_flow_config_search_dto m, int offset, int limit, ref int total)
        {
            return DB.db_config.CashFlowList(m, offset, limit, ref total);
        }


        public string SaveCashFlow(Models.dc_report_cash_flow_config m, string username)
        {

            return DB.db_config.SaveCashFlow(m);
        }
        public string SaveSalesDayConfig(sales_day_config_input_dto m,UserData user)
        {

            return DB.db_config.SaveSalesDayConfig(m, user);
        }
        
        public string BatchSaveSalesDayConfig(batch_sales_day_config_input_dto m,UserData user)
        {

            return DB.db_config.BatchSaveSalesDayConfig(m, user);
        }
        
        public string SaveSalesDayConfigDelete(int id )
        {

            return DB.db_config.SaveSalesDayConfigDelete(id);
        }
        public string BatchSaveSalesDayConfigDelete(string bailun_sku, string warehouse_code)
        {

            return DB.db_config.BatchSaveSalesDayConfigDelete(bailun_sku, warehouse_code);
        }


        public dc_report_cash_flow_config GetCashFlowById(int id)
        {
            return DB.db_config.GetCashFlowById(id);
        }

        #endregion

        #region 物流商账期

        public List<dc_report_logistics_company_config_dto> LogisticsCompanyConfigPage(dc_report_logistics_company_config_search_dto m, int offset, int limit, ref int total)
        {
            return DB.db_config.LogisticsCompanyConfigPage(m, offset, limit, ref total);
        }


        public string SaveLogisticsCompanyConfig(dc_report_logistics_company_config m)
        {

            return DB.db_config.SaveLogisticsCompanyConfig(m);
        }


        public dc_report_logistics_company_config GetLogisticsCompanyConfigById(int id)
        {
            return DB.db_config.GetLogisticsCompanyConfigById(id);
        }

        #endregion

        #region 退货规则配置

        public List<dc_auto_return_goods_config_dto> ReturnGoodsConfigPage(dc_auto_return_goods_config_search_dto m, int offset, int limit, ref int total)
        {
            return DB.db_config.ReturnGoodsConfigPage(m, offset, limit, ref total);
        }


        public string SaveReturnGoodsConfig(dc_auto_return_goods_config m,UserData user)
        {
            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                throw new Exception("请选择仓库");
            }
            if(m.first_inbound_days_min==0 && m.first_inbound_days_max==0)
            {
                throw new Exception("请填写入库天数");
            }
            //if (m.sales_average_upper_limit == 0)
            //{
            //    throw new Exception("请填写日均加权销量上限");
            //}
            return DB.db_config.SaveReturnGoodsConfig(m,user);
        }


        public dc_auto_return_goods_config_dto GetReturnGoodsConfigById(int id)
        {
            return DB.db_config.GetReturnGoodsConfigById(id);
        }



        #endregion


        #region 月度系数配置

        public List<dc_report_sales_trend_year_config_dto> SalesTrendYearConfigPage(dc_auto_return_goods_config_search_dto m, int offset, int limit, ref int total)
        {
            return DB.db_config.SalesTrendYearConfigPage(m, offset, limit, ref total);
        }


        public string SaveSalesTrendYearConfig(dc_report_sales_trend_year_config m,UserData user)
        {
          
            return DB.db_config.SaveSalesTrendYearConfig(m,user);
        }


        public dc_report_sales_trend_year_config GetSalesTrendYearConfigById(int id)
        {
            return DB.db_config.GetSalesTrendYearConfigById(id);
        }



        #endregion

        /// <summary>
        /// 批量设置默认头程运输方式
        /// </summary>
        /// <param name="input_data"></param>
        /// <param name="user"></param>
        public void BatchSetHeadTransport(batch_set_head_transport_input_dto input_data, UserData user)
        {
            DB.db_config.BatchSetHeadTransport(input_data, user);
        }
        public void ApiBatchHeadTransport(api_batch_head_transport_input_dto input_data)
        {
            DB.db_config.ApiBatchHeadTransport(input_data);
        }

        /// <summary>
        /// 批量转仓
        /// </summary>
        /// <param name="input_data"></param>
        /// <param name="user"></param>
        public void TransferWarehouse(dc_aims_transfer_warehouse_input_dto input_data, UserData user)
        {
            DB.dc_aims_transfer_warehouse_dao.TransferWarehouse(input_data, user);
        }
    }
}
