using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
using AutoTurnOver.Models;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Cors;
using AutoTurnOver.Utility;
using System.Data;
using AutoTurnOver.Common;
using System.IO;
using AutoTurnOver.Services;

namespace AutoTurnOver.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SkuAutoTurnController : BaseController
    {

        /// <summary>
        /// 获取sku周转列表
        /// </summary>
        /// <param name="page">当前分页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult List(int limit, int offset, string order, string sort, int? searchType, string key_words, string buyer_name, int? IsRedundant, int? IsStockOut, string warehousecode,string supplier_name, string warehousetype, int? warehousearea, bool? hasDefectConfig, bool? hasAadvise = null, string categoryIds = null, int? monitor_status = null)
        {

            var m = new Condition_AutoTurnOver
            {
                searchType = searchType,
                key_words = key_words,
                out_of_stock = IsStockOut,
                redundancy = IsRedundant,
                warehouse_code = warehousecode,
                warehousetype = warehousetype,
                warehousearea = warehousearea,
                hasDefectConfig = hasDefectConfig,
                hasAadvise = hasAadvise,
                categoryIds = categoryIds,
                monitor_status = monitor_status,
                buyer_name = buyer_name,
                supplier_name = supplier_name

            };

            var total = 0;
            var service = new Services.SkuAutoTurnServices();
            var list = service.List(m, offset, limit, ref total, order, sort).Select(p => new
            {
                p.bailun_sku,
                p.sku_title,
                p.warehouse_code,
                p.warehouse_name,
                p.quantity_minimum_order,
                p.quantity_final_advise,
                p.quantity_promotion,
                p.quantity_inventory,
                p.turnover_days,
                p.quantity_safe_inventory,
                p.inspection_delivery,
                p.status,
                p.id,
                p.quantity_out_stock,
                p.supplier_delivery,
                p.transfer_delivery,
                p.quantity_purchase,
                p.quantity_transfer,
                p.forecast_fourteenday_sales,
                p.forecast_sevenday_sales,
                p.history_thirtyday_sales,
                p.oneday_sales,
                p.forecast_oneday_sales2,
                p.product_inner_code,
                p.product_code,
                p.bailun_category_name,
                p.history_fourteenday_sales,
                p.history_sevenday_sales,
                p.monitor_status,
                p.suppliers_name,
                p.history_sevenday_sales_ebay,
                p.history_fourteenday_sales_ebay,
                p.history_thirtyday_sales_ebay,
                p.shipped_stock,
                p.suppliers_link,
                p.buyer_name,
                p.develop_time

            });

            return new JsonResult(new
            {
                rows = list,
                total = total,
                pagecount = (total / limit + (total % limit > 0 ? 1 : 0))
            });
        }

        public JsonResult ListSumFooter(string supplier_name, int limit, int offset, string order, string sort,  int? searchType, string key_words,string buyer_name, string sku_prefix, int? IsRedundant, int? IsStockOut, string warehousecode, string warehousetype, int? warehousearea, bool? hasDefectConfig,  bool? hasAadvise = null, string categoryIds = null, int? monitor_status = null)
        {
            var m = new Condition_AutoTurnOver
            {
                searchType = searchType,
                key_words = key_words,
                out_of_stock = IsStockOut,
                redundancy = IsRedundant,
                warehouse_code = warehousecode,
                warehousetype = warehousetype,
                warehousearea = warehousearea,
                hasDefectConfig = hasDefectConfig,
                hasAadvise = hasAadvise,
                categoryIds = categoryIds,
                monitor_status = monitor_status,
                buyer_name = buyer_name,
                supplier_name = supplier_name
            };
            var total = 0;
            var service = new Services.SkuAutoTurnServices();
            var list = service.List(m, offset, limit, ref total, order, sort, true);

            return new JsonResult(list == null || list.Count <= 0 ? new dc_auto_turnover_Extend() : list[0]);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public FileResult Export(string supplier_name, int limit, int offset, string order, string sort,  int? searchType, string key_words, string buyer_name, string sku_prefix, int? IsRedundant, int? IsStockOut, string warehousecode, string warehousetype, int? warehousearea, bool? hasDefectConfig, bool? hasAadvise = null, string categoryIds = null, int? monitor_status = null)
        {
            var m = new Condition_AutoTurnOver
            {
                searchType = searchType,
                key_words = key_words,
                out_of_stock = IsStockOut,
                redundancy = IsRedundant,
                warehouse_code = warehousecode,
                warehousetype = warehousetype,
                warehousearea = warehousearea,
                hasDefectConfig = hasDefectConfig,
                hasAadvise = hasAadvise,
                categoryIds = categoryIds,
                monitor_status = monitor_status,
                buyer_name = buyer_name,
                supplier_name = supplier_name
            };

            var total = 0;
            var service = new Services.SkuAutoTurnServices();
            var list = service.List(m, 0, int.MaxValue, ref total, order, sort).Select(p => new
            {
                p.bailun_sku,
                p.sku_title,
                p.warehouse_code,
                p.warehouse_name,
                p.quantity_minimum_order,
                p.quantity_final_advise,
                p.quantity_promotion,
                p.quantity_inventory,
                p.turnover_days,
                p.quantity_safe_inventory,
                p.inspection_delivery,
                p.status,
                p.id,
                p.quantity_out_stock,
                p.supplier_delivery,
                p.transfer_delivery,
                p.quantity_purchase,
                p.quantity_transfer,
                p.forecast_fourteenday_sales,
                p.forecast_sevenday_sales,
                p.oneday_sales,
                p.forecast_oneday_sales2,
                p.product_inner_code,
                p.product_code,
                p.bailun_category_name,
                p.monitor_status,
                p.supplier_name,
                p.buyer_name,
                p.delivery_days_error,
                p.history_sevenday_sales,
                p.history_fourteenday_sales,
                p.history_thirtyday_sales,
                p.unit_price,
                p.weight,
                p.usable_stock,
                p.suppliers_name,
                p.history_sevenday_sales_ebay,
                p.history_fourteenday_sales_ebay,
                p.history_thirtyday_sales_ebay,
                p.shipped_stock,
                p.develop_time
            });

            DataTable table = new DataTable();
            string[] cols = new string[] { "Sku","商品编码", "内部编码", "sku标题", "仓库编码", "仓库名称", "MOQ",
                "采购在途", "调拨在途", "昨日销量", "明日销量", "未来7天日均", "未来14天日均", "建议采购数", "活动促销数量",
                "实际库存", "安全库存", "周转天数", "供应商交期", "质检入库天数", "调拨头程天数", "预测是否断货", "缺货数量","监控状态","供应商","采购员","交期异常",
                "过去7天日均","过去14天日均","过去30天日均","重量","单价","实时库存","ebay最近7天日均销量","ebay最近14天日均销量","ebay最近30天日均销量","已发货库存","开发时间"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

            foreach (var itemData in list)
            {
                DataRow row = table.NewRow();

                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["已发货库存"] = itemData.shipped_stock;
                row["开发时间"] = itemData.develop_time;
                table.Rows.Add(row);
            }

            var fileName = AppContext.BaseDirectory + @"Result\RealtimeStock\周转表.csv";

            DataTableHelper.SaveCSV(table, fileName);

            var memory = new MemoryStream();
            using (var stream = new FileStream(fileName, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            return File(memory, "text/csv", "周转表.csv");
        }

        #region 特殊销售设置

        /// <summary>
        /// 获取特殊销售设置列表
        /// </summary>
        /// <param name="limit">每页记录数</param>
        /// <param name="offset">偏移量</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序还是降序</param>
        /// <param name="sku">sku编码</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="IsEffective">是否有效数据</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult ListSaleSetting(int limit, int offset, string order, string sort, string sku, string warehousecode, string warehousetype, int? warehousearea, bool? IsEffective = null)
        {
            var m = new Condition_ConfigPromotion
            {
                sku = sku,
                warehousecode = warehousecode,
                IsEffective = IsEffective,
                warehousetype = warehousetype,
                warehousearea = warehousearea
            };

            var total = 0;
            var service = new Services.SkuAutoTurnServices();
            var list = service.List(m, offset, limit, ref total).Select(p => new
            {
                p.bailun_sku,
                p.warehouse_code,
                p.warehouse_name,
                promotion_time = p.promotion_time.ToString("yyyy-MM-dd"),
                p.count,
                p.remark,
                p.bl_auditor,
                p.status,
                p.id
            });

            return new JsonResult(new
            {
                rows = list,
                total = total,
            });
        }

        /// <summary>
        /// 保存特殊销售设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult SaveSaleSetting(int id, string sku, string warehousecode, DateTime time, int count, string note, string username)
        {
            var m = new Models.dc_auto_config_promotion
            {
                id = id,
                bailun_sku = sku,
                count = count,
                bl_operator = username,
                bl_auditor = "",
                gmt_create = DateTime.Now,
                gmt_modified = DateTime.Now,
                promotion_time = time,
                remark = note,
                status = 0,
                warehouse_code = warehousecode,
                warehouse_name = "",
            };

            var result = new Services.SkuAutoTurnServices().SaveSaleSetting(m, username);
            return new JsonResult(result);
        }

        [HttpPost]
        public JsonResult AddsSaleSetting([FromForm]string datasStr)
        {
            var datasObj = datasStr.ToObj<List<dc_auto_config_promotion_input>>();
            try
            {
                new Services.SkuAutoTurnServices().AddsSaleSetting(datasObj);
                return new JsonResult(new
                {
                    success = true
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    success = false,
                    message = ex.Message
                });
            }

        }

        /// <summary>
        /// 获取特殊销售设置详情
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetSaleSettingById(int id)
        {
            var m = new Services.SkuAutoTurnServices().GetSaleSettingById(id);

            return new JsonResult(new
            {
                m.id,
                m.bailun_sku,
                m.bl_auditor,
                m.bl_operator,
                m.count,
                vtime = m.promotion_time.ToString("yyyy-MM-dd"),
                m.remark,
                m.status,
                m.warehouse_code,
                m.warehouse_name
            });
        }

        #endregion

        #region 预计断货Sku

        public JsonResult ListOutStock(string sku, string warehousecode, int offset, int limit, string warehousetype, int? warehousearea)
        {
            var m = new Condition_AutoTurnOver
            {
                bailun_sku = sku,
                warehouse_code = warehousecode,
                out_of_stock = 1,
                warehousetype = warehousetype,
                warehousearea = warehousearea
            };

            var total = 0;
            var service = new Services.SkuAutoTurnServices();
            var list = service.List(m, offset, limit, ref total, "", "short_supply_time").Select(p => new
            {
                gmt_modified = p.gmt_modified.ToString("yyyy-MM-dd HH:mm:ss"),
                p.bailun_sku,
                p.warehouse_name,
                short_supply_time = "",
                short_supply_days = 0,
                p.id,
                p.warehouse_code
            });

            return new JsonResult(new
            {
                rows = list,
                total = total
            });
        }

        #endregion

        #region 市场因素配置

        /// <summary>
        /// 获取市场因素设置列表
        /// </summary>
        /// <param name="limit">每页记录数</param>
        /// <param name="offset">偏移量</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序还是降序</param>
        /// <param name="sku">sku编码</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="IsEffective">是否有效数据</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult ListCorrection(int limit, int offset, string order, string sort, string sku, string warehousecode, string warehousetype, int? warehousearea, bool? IsEffective = null)
        {
            var m = new Condition_ConfigPromotion
            {
                sku = sku,
                warehousecode = warehousecode,
                IsEffective = IsEffective,
                warehousetype = warehousetype,
                warehousearea = warehousearea
            };

            var total = 0;
            var service = new Services.SkuAutoTurnServices();
            var list = service.CorrectionList(m, offset, limit, ref total).Select(p => new
            {
                p.bailun_sku,
                p.warehouse_code,
                p.warehouse_name,
                start_time = p.start_time.ToString("yyyy-MM-dd"),
                end_time = p.end_time.ToString("yyyy-MM-dd"),
                p.param,
                p.remark,
                p.id
            });

            return new JsonResult(new
            {
                rows = list,
                total = total,
            });
        }

        /// <summary>
        /// 保存市场因素设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult SaveCorrection(int id, string sku, string warehousecode, DateTime btime, DateTime etime, decimal param, string note, string username)
        {
            var m = new Models.dc_auto_config_correction
            {
                id = id,
                bailun_sku = sku,
                param = param,
                bl_operator = username,
                gmt_create = DateTime.Now,
                gmt_modified = DateTime.Now,
                start_time = btime,
                end_time = etime,
                remark = note,
                warehouse_code = warehousecode,
                warehouse_name = "",
            };

            var result = new Services.SkuAutoTurnServices().SaveCorrection(m, username);
            return new JsonResult(result);
        }


        /// <summary>
        /// 获取市场因素设置详情
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetCorrectionById(int id)
        {
            var m = new Services.SkuAutoTurnServices().GetCorrectionById(id);

            return new JsonResult(new
            {
                m.id,
                m.bailun_sku,
                m.bl_operator,
                m.param,
                bvtime = m.start_time.ToString("yyyy-MM-dd"),
                evtime = m.end_time.ToString("yyyy-MM-dd"),
                m.remark,
                m.warehouse_code,
                m.warehouse_name
            });
        }

        #endregion


        /// <summary>
        /// 导出sku基础配置
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public FileResult ExportSkuConfig()
        {

            var list = new SkuAutoTurnServices().SkuConfigList();

            DataTable table = new DataTable();
            string[] cols = new string[] { "仓库类型", "仓库编码", "仓库名称", "SKU", "产品编码", "内部编码", "标题",
                "采购员", "头程调拨初始值", "头程调拨平均值", "海外仓入库天数初始值", "海外仓入库天数平均值", "海外仓打包天数初始", "海外仓打包天数平均值",
                "初始采购交期","最近一个单的预计到货时间", "安全库存波峰天数(平均逾期天数)", "moq", "安全库存数量", "实际到货平均值", "实际库存",
                "日均加权销量", "未来7天日均", "周转天数（供应链长度）", "采购在途", "调拨在途", "缺货数量", "监控状态",
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

            foreach (var itemData in list)
            {
                DataRow row = table.NewRow();

                row["仓库类型"] = itemData.warehouse_type;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["SKU"] = itemData.bailun_sku;
                row["产品编码"] = itemData.product_code;
                row["内部编码"] = itemData.product_inner_code;
                row["标题"] = itemData.sku_title;
                row["采购员"] = itemData.buyer_name;
                row["头程调拨初始值"] = itemData.transfer_config_delivery;
                row["头程调拨平均值"] = itemData.transfer_delivery;
                row["海外仓入库天数初始值"] = itemData.abroad_inbound_config_delivery;
                row["海外仓入库天数平均值"] = itemData.abroad_inbound_delivery;
                row["海外仓打包天数初始"] = itemData.transfer_bale_config_delivery;
                row["海外仓打包天数平均值"] = itemData.transfer_bale_delivery;
                row["初始采购交期"] = itemData.supplier_delivery;
               row["最近一个单的预计到货时间"] = itemData.new_supplier_delivery;
                row["安全库存波峰天数(平均逾期天数)"] = itemData.average_overdue;
                row["moq"] = itemData.moq;
                row["安全库存数量"] = itemData.quantity_safe;
                row["实际到货平均值"] = itemData.average_arrival;
                row["实际库存"] = itemData.stock;
                row["日均加权销量"] = itemData.quantity_safe_inventory;
                row["未来7天日均"] = itemData.forecast_sevenday_sales;
                row["周转天数（供应链长度）"] = itemData.turnover_days;
                row["采购在途"] = itemData.realtime_quantity_purchase;
                row["调拨在途"] = itemData.realtime_quantity_transfer;
                row["缺货数量"] = itemData.quantity_out_stock;
                row["监控状态"] = itemData.monitor_status;
                table.Rows.Add(row);
            }

            var fileName = AppContext.BaseDirectory + @"Result\RealtimeStock\产品基础配置数据.csv";

            DataTableHelper.SaveCSV(table, fileName);

            var memory = new MemoryStream();
            using (var stream = new FileStream(fileName, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            return File(memory, "text/csv", "产品基础配置数据.csv");
        }

        /// <summary>
        /// 导出sku基础配置
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public FileResult ExportSkuNewSupplierDelivery()
        {

            var list = new SkuAutoTurnServices().SkuNewSupplierDeliveryList();

            DataTable table = new DataTable();
            string[] cols = new string[] { "仓库编码", "SKU", "最近一个单的预计交期" };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

            foreach (var itemData in list)
            {
                DataRow row = table.NewRow();

                row["仓库编码"] = itemData.warehouse_code;
                row["SKU"] = itemData.bailun_sku;
                row["最近一个单的预计交期"] = itemData.new_supplier_delivery;
                table.Rows.Add(row);
            }

            var fileName = AppContext.BaseDirectory + @"Result\RealtimeStock\最新预计交期.csv";

            DataTableHelper.SaveCSV(table, fileName);

            var memory = new MemoryStream();
            using (var stream = new FileStream(fileName, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            return File(memory, "text/csv", "最新预计交期.csv");
        }
    }
}