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

namespace AutoTurnOver.Services
{
    /// <summary>
    /// 自动周转
    /// </summary>
    public class SkuAutoTurnServices
    {
        /// <summary>
        /// 获取自动周转分页
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="total">符合条件的总记录数</param>
        /// <param name = "order" > 排序类型 </ param >
        /// <param name="sort">排序字段</param>
        /// <returns></returns>
        public List<dc_auto_turnover_list_dto> List(Condition_AutoTurnOver m,int offset, int limit, ref int total,string order="",string sort="",bool isSum = false)
        {
            if (!string.IsNullOrWhiteSpace(m.categoryIds))
            {
                m.categoryModels = ApiServices.GetNewClientNodesByIds(m.categoryIds.Split(',').Select(s=>int.Parse(s)).ToList());
            }
            return DB.dc_auto_turnover.List(m,offset, limit, ref total,order,sort, isSum);
        }

        public IEnumerable<string> GetLabelList() {
            return DB.dc_auto_turnover.GetLabelList();
        }

        #region 特殊销售设置

        /// <summary>
        /// 获取特殊销售设置分页列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_auto_config_promotion> List(Condition_ConfigPromotion m, int offset, int limit,ref int total)
        {
            return DB.dc_auto_turnover.ListConfigPromotion(m, offset, limit,ref total);
        }

        /// <summary>
        /// 查询未来指定时间范围内的特殊销量数据
        /// </summary>
        /// <param name="days"></param>
        /// <returns></returns>
        public IEnumerable<dc_auto_config_promotion> List(string sku,string warehousecode,int days)
        {
            var now = DateTime.Now;
            return DB.dc_auto_turnover.ListConfigPromotion(sku, warehousecode, now, now.AddDays(days));
        }


        /// <summary>
        /// 保存销售设置
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveSaleSetting(Models.dc_auto_config_promotion m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.bailun_sku))
            {
                return "Sku不能为空！";
            }

            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            if (m.count <= 0)
            {
                return "增量必须大于0！";
            }

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

            m.warehouse_name = objWarehouse.warehouse_name;

            if (m.promotion_time < DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(1))
            {
                return "销售日期必须大于今天！";
            }

            return DB.dc_auto_turnover.SaveSaleSetting(m, username);
        }

        public void AddsSaleSetting(List<dc_auto_config_promotion_input> datas)
        {
            foreach (var m in datas)
            {
                if (string.IsNullOrWhiteSpace(m.sku))
                {
                    throw new Exception("Sku不能为空！");
                }

                if (string.IsNullOrWhiteSpace(m.warehousecode))
                {
                    throw new Exception("请选择仓库！");
                }

                if (m.count <= 0)
                {
                    throw new Exception("增量必须大于0！");
                }

                var objWarehouse = DB.common.GetWareHouseByCode(m.warehousecode);
                if (objWarehouse == null)
                {
                    throw new Exception("系统找不到该仓库");
                }

                m.warehouse_name = objWarehouse.warehouse_name;

                if (m.time < DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(1))
                {
                    throw new Exception("销售日期必须大于今天");
                }
            }
            

            DB.dc_auto_turnover.AddsSaleSetting(datas);
        }

        /// <summary>
        /// 获取特殊销售设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_auto_config_promotion GetSaleSettingById(int id)
        {
            return DB.dc_auto_turnover.GetSaleSettingById(id);
        }

        #endregion

        #region 市场因素设置

        /// <summary>
        /// 获取市场因素设置分页列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<dc_auto_config_correction> CorrectionList(Condition_ConfigPromotion m, int offset, int limit, ref int total)
        {
            return DB.dc_auto_turnover.ListCorrection(m, offset, limit, ref total);
        }

        /// <summary>
        /// 查询未来指定时间范围内的特殊销量数据
        /// </summary>
        /// <param name="days"></param>
        /// <returns></returns>
        public IEnumerable<dc_auto_config_correction> CorrectionList(string sku, string warehousecode, int days)
        {
            var now = DateTime.Now;
            return DB.dc_auto_turnover.ListCorrection(sku, warehousecode, now, now.AddDays(days));
        }


        /// <summary>
        /// 保存销售设置
        /// </summary>
        /// <param name="m">销售设置model</param>
        /// <param name="username">当前操作人</param>
        /// <returns></returns>
        public string SaveCorrection(Models.dc_auto_config_correction m, string username)
        {
            if (string.IsNullOrWhiteSpace(m.bailun_sku))
            {
                return "Sku不能为空！";
            }

            if (string.IsNullOrWhiteSpace(m.warehouse_code))
            {
                return "请选择仓库！";
            }

            if (m.param <= 0)
            {
                return "比例必须大于0！";
            }

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

            m.warehouse_name = objWarehouse.warehouse_name;

            if (m.start_time < DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(1))
            {
                return "开始时间必须大于今天！";
            }

            if (m.end_time < DateTime.Parse(DateTime.Now.ToShortDateString()).AddDays(1))
            {
                return "结束时间必须大于今天！";
            }

            if (DateTime.Parse(m.end_time.ToShortDateString()) < DateTime.Parse(m.start_time.ToShortDateString()))
            {
                return "结束时间不能小于开始时间！";
            }


            return DB.dc_auto_turnover.SaveCorrection(m, username);
        }

        

        /// <summary>
        /// 获取市场因素设置详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public dc_auto_config_correction GetCorrectionById(int id)
        {
            return DB.dc_auto_turnover.GetCorrectionById(id);
        }

        #endregion

        #region 预估库存

        /// <summary>
        /// 获取预估库存详情
        /// </summary>
        /// <param name="sku">sku编码</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <returns></returns>
        public dc_auto_inventory GetAutoInventoryBySkuWH(string sku,string warehousecode)
        {
            return DB.dc_auto_turnover.GetAutoInventoryBySkuWH(sku, warehousecode);
        }

        #endregion

        public dc_auto_turnover GetModel(string sku, string wCode)
        {
            return DB.dc_auto_turnover.GetModel(sku, wCode);
        }

        /// <summary>
        /// 查询SKU基础配置数据
        /// </summary>
        /// <returns></returns>
        public List<dc_sku_config_dto> SkuConfigList()
        {
            return DB.dc_auto_turnover.SkuConfigList();
        }

        /// <summary>
        /// 查询SKU基础配置数据
        /// </summary>
        /// <returns></returns>
        public List<new_supplier_delivery_dto> SkuNewSupplierDeliveryList()
        {
            return DB.dc_auto_turnover.SkuNewSupplierDeliveryList();
        }

        public MemoryStream Export(UserData user, Condition_AutoTurnOver m,string order,string sort)
        {
            var fileName = AppContext.BaseDirectory + $@"Result\RealtimeStock\{user.UserAccount}周转表.csv";

            

            var total = 0;
            var service = new Services.SkuAutoTurnServices();


            int page = 1;
            int rows = 50000;
            while (true)
            {
                var list = service.List(m, (page - 1) * rows, rows, ref total, order, sort);
                if (list == null || list.Count <= 0) break;
                DataTable table = new DataTable();
                string[] cols = new string[] { "Sku","商品编码", "内部编码", "sku标题", "仓库编码", "仓库名称", "MOQ",
                "采购在途", "调拨在途", "昨日销量", "明日销量", "未来7天日均", "未来14天日均", "建议采购数", "活动促销数量",
                "实际库存", "安全库存", "周转天数", "供应商交期", "质检入库天数", "调拨头程天数", "预测是否断货", "缺货数量","监控状态","供应商","采购员","交期异常",
                "过去7天日均","过去14天日均","过去30天日均","重量","单价","实时库存","ebay最近7天日均销量","ebay最近14天日均销量","ebay最近30天日均销量"
                ,"速卖通最近7天日均销量","速卖通最近14天日均销量","速卖通最近30天日均销量"
                ,"已发货库存","开发时间","是否侵权","停止监控时间","标签","停售","最近7天+预测销量","amazon最近7天日均销量","amazon最近14天日均销量","amazon最近30天日均销量","品牌","简易分类"
                ,"采购陆运在途数量","采购海运在途数量","采购空运在途数量","采购铁路在途数量"
                ,"调拨陆运在途数量","调拨海运在途数量","调拨空运在途数量","调拨铁路在途数量"
            };
                foreach (var item in cols)
                {
                    table.Columns.Add(item);
                }

                foreach (var itemData in list)
                {
                    DataRow row = table.NewRow();
                    row["采购陆运在途数量"] = itemData.quantity_land_purchase;
                    row["采购海运在途数量"] = itemData.quantity_ocean_purchase;
                    row["采购空运在途数量"] = itemData.quantity_air_purchase;
                    row["采购铁路在途数量"] = itemData.quantity_railway_purchase;
                    row["调拨陆运在途数量"] = itemData.quantity_land_transfer;
                    row["调拨海运在途数量"] = itemData.quantity_ocean_transfer;
                    row["调拨空运在途数量"] = itemData.quantity_air_transfer;
                    row["调拨铁路在途数量"] = itemData.quantity_railway_transfer;

                    row["Sku"] = itemData.bailun_sku;
                    row["商品编码"] = itemData.product_code;
                    row["内部编码"] = itemData.product_inner_code;
                    row["sku标题"] = itemData.sku_title;
                    row["仓库编码"] = itemData.warehouse_code;
                    row["仓库名称"] = itemData.warehouse_name;
                    row["MOQ"] = itemData.quantity_minimum_order;
                    row["采购在途"] = itemData.quantity_purchase;
                    row["调拨在途"] = itemData.quantity_transfer;
                    row["昨日销量"] = itemData.oneday_sales;
                    row["明日销量"] = itemData.forecast_oneday_sales2;
                    row["未来7天日均"] = itemData.forecast_sevenday_sales;
                    row["未来14天日均"] = itemData.forecast_fourteenday_sales;
                    row["建议采购数"] = itemData.quantity_final_advise;
                    row["活动促销数量"] = itemData.quantity_promotion;
                    row["实际库存"] = itemData.quantity_inventory;
                    row["安全库存"] = itemData.quantity_safe_inventory;
                    row["周转天数"] = itemData.turnover_days;
                    row["供应商交期"] = itemData.supplier_delivery;
                    row["质检入库天数"] = itemData.inspection_delivery;
                    row["调拨头程天数"] = itemData.transfer_delivery;
                    row["预测是否断货"] = itemData.status == 1 ? "是" : "否";
                    row["缺货数量"] = itemData.quantity_out_stock;
                    row["监控状态"] = itemData.monitor_status == 1 ? "停止监控" : "监控中";
                    row["供应商"] = itemData.supplier_name;
                    row["采购员"] = itemData.buyer_name;
                    row["交期异常"] = itemData.delivery_days_error;
                    row["过去7天日均"] = itemData.history_sevenday_sales;
                    row["过去14天日均"] = itemData.history_fourteenday_sales;
                    row["过去30天日均"] = itemData.history_thirtyday_sales;
                    row["重量"] = itemData.weight;
                    row["单价"] = itemData.unit_price;
                    row["实时库存"] = itemData.usable_stock;
                    row["ebay最近7天日均销量"] = itemData.history_sevenday_sales_ebay;
                    row["ebay最近14天日均销量"] = itemData.history_fourteenday_sales_ebay;
                    row["ebay最近30天日均销量"] = itemData.history_thirtyday_sales_ebay;
                    row["速卖通最近7天日均销量"] = itemData.history_sevenday_sales_aliexpress;
                    row["速卖通最近14天日均销量"] = itemData.history_fourteenday_sales_aliexpress;
                    row["速卖通最近30天日均销量"] = itemData.history_thirtyday_sales_aliexpress;
                    row["amazon最近7天日均销量"] = itemData.history_sevenday_sales_amazon;
                    row["amazon最近14天日均销量"] = itemData.history_fourteenday_sales_amazon;
                    row["amazon最近30天日均销量"] = itemData.history_thirtyday_sales_amazon;
                    row["已发货库存"] = itemData.shipped_stock;
                    row["开发时间"] = itemData.develop_time;
                    row["是否侵权"] = itemData.has_tort;
                    row["停止监控时间"] = itemData.stop_monitor_create==null?"":itemData.stop_monitor_create.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    //row["动态备货规则组"] = itemData.group_name;
                    row["标签"] = itemData.sku_label;
                    row["停售"] = itemData.sku_status_str;
                    row["最近7天+预测销量"] = itemData.sales_details==null?"": itemData.sales_details.Replace("[","").Replace("]","");
                    row["品牌"] = itemData.brand;
                    row["简易分类"] = itemData.category_simple_name;
                    table.Rows.Add(row);
                }


                CsvFileHelper.SaveCSV(table, fileName, page == 1);
                page++;
            }

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

            return memory;
        }

        /// <summary>
        /// 生产数据
        /// </summary>
        /// <returns></returns>
        public async void GenerateData()
        {
            try
            {
                var memory = Export(new UserData { UserAccount = "admin" }, new Condition_AutoTurnOver { warehouse_code = "GZBLWH" }, "", "");
                var fileData = await QiNiuCloudHelper.UploadAsync(memory, $"zhouzhuangshuj_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv");
                ApiServices.QiYeJiQiRenMsPush(new QiYeJiQiRenMsDto { msgtype = "text", text = new QiYeJiQiRenMsDto.text_dto { content = "广州01周转数据：" + fileData } });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
           

        }



    }
}
