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;
using AutoTurnOver.DB;

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]
        [UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【自动周转列表】->【搜索】页面",0)]
        public JsonResult List([FromQuery] Condition_AutoTurnOver m, [FromQuery] int offset, [FromQuery] int limit, [FromQuery] string order, [FromQuery] string sort)
        {
            try 
            {
               
                var total = 0;
                var service = new Services.SkuAutoTurnServices();
                var list = service.List(m, offset, limit, ref total, order, sort);

                return new JsonResult(new
                {
                    rows = list,
                    total = total,
                    pagecount = (total / limit + (total % limit > 0 ? 1 : 0))  
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    message = ex.Message,
                    stack_trace = ex.StackTrace
                });
            }
           
        }


        /// <summary>
        /// 供应链调拨在途
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【自动下单管理】->【利润最大化分析】->【搜索】页面", 0)]
        public JsonResult ProfitAnalysis([FromQuery] Condition_AutoTurnOver m, [FromQuery] int offset, [FromQuery] int limit, [FromQuery] string order, [FromQuery] string sort)
        {

            try
            {
                var services = new SkuAutoTurnServices();
                var total = 0;
                var list = services.ProfitAnalysis(m, offset, limit, ref total, order, sort);

                return new JsonResult(new
                {
                    rows = list,
                    total = total,
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    message = ex.Message,
                    stack_trace = ex.StackTrace
                });
            }

        }

        [NoLogin]
        public JsonResult ProfitAnalysisSumFooter([FromQuery]Condition_AutoTurnOver m, [FromQuery] int offset, [FromQuery] int limit, [FromQuery] string order, [FromQuery] string sort)
        {

            var services = new SkuAutoTurnServices();
            var total = 0;
            m.isSum = true;
            var list = services.ProfitAnalysis(m, offset, limit, ref total, order, sort);

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

        public JsonResult ExportProfitAnalysis([FromQuery] ana_search_dto search_data)
        {
            try
            {
                var user = AutoUtility.GetUser();
                dc_task_download_dao.PushData<ana_search_dto>(new dc_task_download
                {
                    parameter = search_data.ToJson(),
                    task_name = "利润最大化分析"
                }, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }

        }


        [HttpGet]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动周转列表】->【空运海运利润计算】->【搜索】页面", 0)]
        public JsonResult TransferProfitList(string bailun_sku, string warehouse_code)
        {
            try 
            {
               
                var service = new Services.SkuAutoTurnServices();
                var list = service.TransferProfitList(bailun_sku, warehouse_code);

                return new JsonResult(new
                {
                    data = list
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    message = ex.Message,
                    stack_trace = ex.StackTrace
                });
            }
           
        }
        
        /// <summary>
        /// 查看平均数的数据来源
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public JsonResult GetOrderDataSource([FromQuery] dc_base_order_data_source_search_dto m, [FromQuery] int offset, [FromQuery] int limit)
        {
            try 
            {
               
                var total = 0;
                var service = new Services.SkuAutoTurnServices();
                var list = service.GetOrderDataSource(m, offset, limit, ref total);

                return new JsonResult(new
                {
                    rows = list,
                    total = total,
                    pagecount = (total / limit + (total % limit > 0 ? 1 : 0))  
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    message = ex.Message,
                    stack_trace = ex.StackTrace
                });
            }
           
        }

        public JsonResult GetLabelList()
        {
            return new JsonResult(new Services.SkuAutoTurnServices().GetLabelList());
        }

        public JsonResult ListSumFooter([FromQuery] Condition_AutoTurnOver m, [FromQuery] int offset, [FromQuery] int limit, [FromQuery] string order, [FromQuery] string sort)
        {
            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_list_dto() : list[0]);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        [UseAction]
        public ActionResult Export([FromQuery] Condition_AutoTurnOver m, [FromQuery] int offset, [FromQuery] int limit, [FromQuery] string order, [FromQuery] string sort)
        {
            try
            {
                var user = AutoUtility.GetUser();
                dc_task_download_dao.PushData<dc_base_stock_search_dto>(new dc_task_download
                {
                    parameter = m.ToJson(),
                    task_name = "周转表"
                }, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }

        }


        /// <summary>
        /// 导出销量模板
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportSalesTemplate([FromQuery] Condition_AutoTurnOver m, [FromQuery] int offset, [FromQuery] int limit, [FromQuery] string order, [FromQuery] string sort)
        {
            try
            {
                var user = AutoUtility.GetUser();
                dc_task_download_dao.PushData<dc_base_stock_search_dto>(new dc_task_download
                {
                    parameter = m.ToJson(),
                    task_name = "销量导入模板"
                }, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }

        }
        #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]
        [UseAction]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【特殊销售规则】->【搜索】页面",0)]
        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]
        [BrowseLog("Bailun_aims","触发【百伦自动周转系统】->【配置】->【特殊销售规则】->【新增规则】->【保存】操作",1)]
        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]
        [UseAction]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【市场因素配置】->【搜索】页面", 0)]
        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]
        [UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【市场因素配置】->【新增规则】->【保存】操作", 1)]
        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");
        }

        /// <summary>
        /// 获取历史节点趋势图
        /// </summary>
        /// <returns></returns>
        public JsonResult GetHistoryDataNodes(string sku, string warehousecode)
        {
            var result = new Services.SkuAutoTurnServices().GetHistoryDataNodes(sku, warehousecode);
            return new JsonResult(new { success = true, data = result });
        }


        [HttpGet]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【利润最大化分析】->【推送采购建议】操作", 3)]
        public JsonResult BatchPushPurchaseAdvise(string ids)
        {
            try
            {
                var user = AutoUtility.GetUser();
                if (user == null) return null;
                new Services.SkuAutoTurnServices().BatchPushPurchaseAdvise(ids, user);
                return new JsonResult("");
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.Message);
            }
         
        }

    }
}