using AutoTurnOver.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using AutoTurnOver.Utility;
using System.Linq;

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


            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, UserData user)
        {
            return DB.db_config.BatchMonitorStatus(ids, monitor_status, user);
        }

        public string BatchTortStatus(string ids, int monitor_status, UserData user)
        {
            return DB.db_config.BatchTortStatus(ids, monitor_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;
        }

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