using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoTurnOver.Common;
using AutoTurnOver.Models;
using AutoTurnOver.Models.Report;
using AutoTurnOver.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace AutoTurnOver.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ConfigController : Controller
    {
        #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]
        public JsonResult InventoryList(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.ConfigServices();
            var list = service.InventoryList(m, offset, limit, ref total);

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

        /// <summary>
        /// 保存安全库存规则设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UseAction]
        public JsonResult SaveInventory([FromBody]dc_auto_config_safe_inventory m)
        {
            var result = new Services.ConfigServices().SaveInventory(m, "");
            return new JsonResult(result);
        }


        /// <summary>
        /// 获取安全库存规则设置详情
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetInventoryById(int id)
        {
            var m = new Services.ConfigServices().GetInventoryById(id);

            return new JsonResult(m);
        }

        #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]
        public JsonResult SalesUpperLimitList(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.ConfigServices();
            var list = service.SalesUpperLimitList(m, offset, limit, ref total);

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

        /// <summary>
        /// 保存安全库存规则设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UseAction]
        public JsonResult SaveSalesUpperLimit([FromBody]dc_auto_config_sales_upper_limit m)
        {
            var result = new Services.ConfigServices().SaveSalesUpperLimit(m, "");
            return new JsonResult(result);
        }


        /// <summary>
        /// 获取安全库存规则设置详情
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetSalesUpperLimitById(int id)
        {
            var m = new Services.ConfigServices().GetSalesUpperLimitById(id);

            return new JsonResult(m);
        }

        #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]
        public JsonResult ConfigDeliveryList(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.ConfigServices();
            var list = service.ConfigDeliveryList(m, offset, limit, ref total);

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

        /// <summary>
        /// 保存供应链长度规则设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveConfigDelivery([FromBody]dc_auto_config_delivery m)
        {
            var result = new Services.ConfigServices().SaveConfigDelivery(m, "");
            return new JsonResult(result);
        }


        /// <summary>
        /// 获取供应链长度规则设置详情
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetConfigDeliveryById(int id)
        {
            var m = new Services.ConfigServices().GetConfigDeliveryById(id);

            return new JsonResult(m);
        }

        #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]
        public JsonResult StockUpList(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.ConfigServices();
            var list = service.StockUpList(m, offset, limit, ref total);

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

        /// <summary>
        /// 保存备货天数设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UseAction]
        public JsonResult SaveStockUp([FromBody]dc_auto_config_stock_up_days m)
        {
            var result = new Services.ConfigServices().SaveStockUp(m, "");
            return new JsonResult(result);
        }


        /// <summary>
        /// 获取备货天数详情
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetStockUpById(int id)
        {
            var m = new Services.ConfigServices().GetStockUpById(id);

            return new JsonResult(m);
        }

        #endregion

        /// <summary>
        /// 监控状态修改
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult MonitorStatus(string bailun_sku, string warehouse_code, int monitor_status)
        {
            var user = AutoUtility.GetUser();
            if (user == null) return null;
            var result = new Services.ConfigServices().MonitorStatus(bailun_sku, warehouse_code, monitor_status, user);
            return new JsonResult(result);
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [UseAction]
        public JsonResult BatchMonitorStatus(string ids, int monitor_status)
        {
            var user = AutoUtility.GetUser();
            if (user == null) return null;
            var result = new Services.ConfigServices().BatchMonitorStatus(ids, monitor_status, user);
            return new JsonResult(result);
        }


        #region fba共享仓发货仓

        /// <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]
        public JsonResult StockFbaList(int limit, int offset, string order, string sort, string bailun_sku, string platform_sku, string warehousecode, string warehousetype, int? warehousearea)
        {
            var m = new Condition_ConfigPromotion
            {
                platform_sku = platform_sku,
                bailun_sku = bailun_sku,
                warehousecode = warehousecode,
                warehousetype = warehousetype,
                warehousearea = warehousearea
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.StockFbaList(m, offset, limit, ref total);

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

        [UseAction]
        public JsonResult StockFbaLoseList(int limit, int offset, string order, string sort, string platform_sku)
        {
            var m = new Condition_ConfigPromotion
            {
                platform_sku = platform_sku
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.StockFbaLoseList(m, offset, limit, ref total);

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

        /// <summary>
        /// 保存FBA发货仓设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UseAction]
        public JsonResult SaveStockFba([FromBody]dc_base_stock_config_fba m)
        {
            try
            {
                var result = new Services.ConfigServices().SaveStockFba(m, "");
                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.Message);
            }

        }


        /// <summary>
        /// 获取备货天数详情
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetStockFbaById(int id)
        {
            var m = new Services.ConfigServices().GetStockFbaById(id);

            return new JsonResult(m);

        }

        [HttpGet]
        public JsonResult BatchTortStatus(string ids, int tort_status)
        {
            var user = AutoUtility.GetUser();
            if (user == null) return null;
            var result = new Services.ConfigServices().BatchTortStatus(ids, tort_status, user);
            return new JsonResult(result);
        }

        #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]
        public JsonResult SalesConfigList(int limit, int offset, string order, string sort, string platform_type, string web_site, DateTime? start_date, DateTime? end_date)
        {
            var m = new dc_auto_sales_config_search_dto
            {
                platform_type = platform_type,
                web_site = web_site,
                start_date = start_date,
                end_date = end_date
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.SalesConfigList(m, offset, limit, ref total);

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

        /// <summary>
        /// 保存销量配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UseAction]
        public JsonResult SaveSalesConfig([FromBody]dc_auto_sales_config m)
        {
            var result = new Services.ConfigServices().SaveSalesConfig(m, "");
            return new JsonResult(result);
        }

        /// <summary>
        /// 获取销量配置
        /// </summary>
        /// <param name="id">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetSalesConfigById(int id)
        {
            var m = new Services.ConfigServices().GetSalesConfigById(id);
            return new JsonResult(m);
        }


        #endregion


        #region fba共享仓发货仓

        [HttpGet]
        [UseAction]
        public JsonResult StockUpRangeList(int limit, int offset, string order, string sort, string bailun_sku, string platform_sku, string warehousecode, string warehousetype, int? warehousearea)
        {
            var m = new Condition_ConfigPromotion
            {
                platform_sku = platform_sku,
                bailun_sku = bailun_sku,
                warehousecode = warehousecode,
                warehousetype = warehousetype,
                warehousearea = warehousearea
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.StockUpRangeList(m, offset, limit, ref total);

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

        [HttpPost]
        [UseAction]
        public JsonResult SaveStockUpRange([FromBody]dc_auto_stock_up_range m)
        {
            try
            {
                var result = new Services.ConfigServices().SaveStockUpRange(m, "");
                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.Message);
            }
        }


        [HttpGet]
        public JsonResult GetStockUpRangeById(int id)
        {
            var m = new Services.ConfigServices().GetStockUpRangeById(id);
            return new JsonResult(m);

        }

        #endregion

        #region 动态备货规则分组

        [HttpGet]
        [UseAction]
        public JsonResult JitTagGroupList(int limit, int offset, string order, string sort, string bailun_sku)
        {
            var m = new Condition_ConfigPromotion
            {
                bailun_sku = bailun_sku
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.JitTagGroupList(m, offset, limit, ref total);

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

        [HttpPost]
        [UseAction]
        public JsonResult SaveJitTagGroup([FromBody]dc_auto_jit_tag_group m)
        {
            try
            {
                var result = new Services.ConfigServices().SaveJitTagGroup(m, "");
                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.Message);
            }
        }

        [HttpGet]
        public JsonResult GetJitTagGroupById(int id)
        {
            var m = new Services.ConfigServices().GetJitTagGroupById(id);
            return new JsonResult(m);
        }

        [HttpGet]
        public JsonResult JitTagGroupAll()
        {
            var m = new Services.ConfigServices().JitTagGroupAll();
            return new JsonResult(m);
        }

        /// <summary>
        /// 批量配置规则组
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult BatchStockUp([FromBody]batch_stock_up_input_dto data)
        {
            try
            {
                new Services.ConfigServices().BatchStockUp(data);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }
        }

        #endregion

        #region 预测销量 人工

        [HttpGet]
        public JsonResult ForecastSalesConfigList(int limit, int offset, string order, string sort, string bailun_sku)
        {
            var m = new Condition_ConfigPromotion
            {
                bailun_sku = bailun_sku
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.ForecastSalesConfigList(m, offset, limit, ref total);

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

        [HttpPost]
        public JsonResult SaveForecastSalesConfig([FromBody]dc_config_forecast_sales m)
        {
            try
            {
                var result = new Services.ConfigServices().SaveForecastSalesConfig(m, AutoUtility.GetUser().UserName);
                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.Message);
            }
        }

        [HttpGet]
        public JsonResult GetForecastSalesConfigById(int id)
        {
            var m = new Services.ConfigServices().GetForecastSalesConfigById(id);
            return new JsonResult(m);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<RequestResultDto>> ForecastSalesImport(IFormFile file)
        {
            try
            {
                var user = AutoUtility.GetUser();
                var dataTable = new Services.ConfigServices().ForecastSalesConfigImport(file.OpenReadStream(), user);

                var fileName = AppContext.BaseDirectory + $@"Result\预测销量（手动）导入结果.csv";

                CsvFileHelper.SaveCSV(dataTable, fileName);

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

                var fileData = await QiNiuCloudHelper.UploadAsync(memory, $"{user.UserName}-{DateTime.Now.ToString("yyyyMMddHHmmss")}预测销量（手动）导入结果.csv");
                return new RequestResultDto { success = true, data = fileData };
            }
            catch (Exception ex)
            {
                return new RequestResultDto { success = false, message = ex.Message, err_data = ex.StackTrace };
            }

        }

        #endregion

        #region 暴增配置

        [HttpGet]
        public JsonResult UprushConfigList(int limit, int offset, string order, string sort, string warehousecode, string warehousetype, int? warehousearea)
        {
            var m = new dc_auto_uprush_config_search_dto
            {
                warehouse_code = warehousecode,
                warehousetype = warehousetype,
                warehousearea = warehousearea
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.UprushConfigList(m, offset, limit, ref total);

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

        [HttpPost]
        public JsonResult SaveUprushConfig([FromBody]dc_auto_uprush_config m)
        {
            try
            {
                var result = new Services.ConfigServices().SaveUprushConfig(m, "");
                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.Message);
            }
        }

        [HttpGet]
        public JsonResult GetUprushConfigById(int id)
        {
            var m = new Services.ConfigServices().GetUprushConfigById(id);
            return new JsonResult(m);
        }

        #endregion

        /// <summary>
        /// 批量修改缺货推送状态
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="monitor_status"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult BatchReturnGoodsStatus(string ids, int monitor_status)
        {
            var user = AutoUtility.GetUser();
            if (user == null) return null;
            var result = new Services.ConfigServices().BatchReturnGoodsStatus(ids, monitor_status, user);
            return new JsonResult(result);
        }

        #region 销量预测模型配置

        [HttpGet]
        public JsonResult SalesForecastConfigList(int limit, int offset, string order, string sort, string warehousecode, string warehousetype, int? warehousearea, string bailun_sku)
        {
            var m = new dc_auto_sales_forecast_config_search_dto
            {
                warehouse_code = warehousecode,
                warehousetype = warehousetype,
                warehousearea = warehousearea,
                bailun_sku = bailun_sku,
                page = (offset / limit) + 1,
                rows = limit
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.SalesForecastConfigList(m);

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

        [HttpPost]
        public JsonResult SaveSalesForecastConfig([FromBody]dc_auto_sales_forecast_config_dto m)
        {
            try
            {
                new Services.ConfigServices().SaveSalesForecastConfig(m, "");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [HttpGet]
        public JsonResult GetSalesForecastConfigById(int id)
        {
            var m = new Services.ConfigServices().GetSalesForecastConfigById(id);
            return new JsonResult(m);
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult DelSalesForecastConfig(int id)
        {
            try
            {
                new Services.ConfigServices().DelSalesForecastConfig(id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                new Services.ConfigServices().DelSalesForecastConfig(id);
                return Json(new { success = true, message = ex.Message });
            }

        }

        #endregion

        #region 现金流结算方式


        [HttpGet]
        public JsonResult CashFlowList(int limit, int offset, string order, string sort, string data_type)
        {
            var m = new dc_report_cash_flow_config_search_dto
            {
                data_type = data_type
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.CashFlowList(m, offset, limit, ref total);

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

        [HttpPost]
        public JsonResult SaveCashFlow([FromBody]dc_report_cash_flow_config m)
        {
            var result = new Services.ConfigServices().SaveCashFlow(m, "");
            return new JsonResult(result);
        }


        [HttpGet]
        public JsonResult GetCashFlowById(int id)
        {
            var m = new Services.ConfigServices().GetCashFlowById(id);

            return new JsonResult(m);
        }

        #endregion

        #region 物流商账期


        [HttpGet]
        public JsonResult LogisticsCompanyConfigPage(int limit, int offset, string order, string sort, string company_code)
        {
            var m = new dc_report_logistics_company_config_search_dto
            {
                company_code = company_code
            };

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.LogisticsCompanyConfigPage(m, offset, limit, ref total);

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

        [HttpPost]
        public JsonResult SaveLogisticsCompanyConfig([FromBody]dc_report_logistics_company_config m)
        {
            var result = new Services.ConfigServices().SaveLogisticsCompanyConfig(m);
            return new JsonResult(result);
        }


        [HttpGet]
        public JsonResult GetLogisticsCompanyConfigById(int id)
        {
            var m = new Services.ConfigServices().GetLogisticsCompanyConfigById(id);

            return new JsonResult(m);
        }

        #endregion
    }
}