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.auto;
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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【安全库存配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【安全库存配置】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【销量上限】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【销量上限配置】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【调拨初始值配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【调拨初始值配置】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【备货天数配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【备货天数配置】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【自动周转列表】->【开启/停止监控】操作",3)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【备货天数配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【fba欧洲共享仓配置缺失】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【fba欧洲共享仓配置缺失】->【新增】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【自动周转列表】->【开启/停止侵权】操作", 3)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【销量配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【销量配置】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【动态备货范围】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【动态备货范围】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【动态备货规则组】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【动态备货规则组】->【新增】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【自动周转列表】->【保存动态配货配置】操作", 3)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【首单销量预测配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【首单销量预测配置】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【首单销量预测配置】->【导入】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【异常突增】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【异常突增】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【自动周转列表】->【停止(恢复)回货自动标记】操作", 3)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【销量预测配置】->【搜索】页面", 0)]
        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
            });
        }

        [NoLogin]
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【销量预测配置】->【新增规则】->【保存】操作", 1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【现金流】->【支付周期配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【现金流】->【支付周期配置】->【新增】->【保存】操作",1)]
        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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【现金流】->【物流商账期配置】->【搜索】页面", 0)]
        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]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【现金流】->【物流商账期配置】->【新增】->【保存】操作",1)]
        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

        #region 退货规则配置


        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【退货规则配置】->【搜索】页面", 0)]
        public JsonResult ReturnGoodsConfigPage([FromQuery]dc_auto_return_goods_config_search_dto search)
        {

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.ReturnGoodsConfigPage(search, search.offset??0, search.limit??0, ref total);

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

        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【退货规则配置】->【新增】->【保存】操作", 1)]
        public JsonResult SaveReturnGoodsConfig([FromBody]dc_auto_return_goods_config m)
        {
            var result = new Services.ConfigServices().SaveReturnGoodsConfig(m, AutoUtility.GetUser());
            return new JsonResult(result);
        }


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

            return new JsonResult(m);
        }

        #endregion


        #region 月度销量系数配置


        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【月度系数配置】->【搜索】页面", 0)]
        public JsonResult SalesTrendYearConfigPage([FromQuery]dc_auto_return_goods_config_search_dto search)
        {

            var total = 0;
            var service = new Services.ConfigServices();
            var list = service.SalesTrendYearConfigPage(search, search.offset??0, search.limit??0, ref total);

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

        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【月度系数配置】->【新增】->【保存】操作", 1)]
        public JsonResult SaveSalesTrendYearConfig([FromBody]dc_report_sales_trend_year_config m)
        {
            var result = new Services.ConfigServices().SaveSalesTrendYearConfig(m, AutoUtility.GetUser());
            return new JsonResult(result);
        }


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

            return new JsonResult(m);
        }

        #endregion


        [HttpPost]
        [UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【周转表】->【设置sku默认头程物流】->操作", 1)]
        public JsonResult BatchSetHeadTransport([FromBody]batch_set_head_transport_input_dto m)
        {
            try
            {
                new Services.ConfigServices().BatchSetHeadTransport(m, AutoUtility.GetUser());
                return new JsonResult("");
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.Message);
            }
           
        }


        [HttpPost]
        [UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【周转表】->【手工配置销量】操作", 1)]
        public JsonResult SaveSalesDayConfig([FromBody]sales_day_config_input_dto m)
        {
            var result = new Services.ConfigServices().SaveSalesDayConfig(m, AutoUtility.GetUser());
            return new JsonResult(result);
        }

        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【周转表】->【手工配置销量】操作", 1)]
        public JsonResult BatchSaveSalesDayConfig([FromBody]batch_sales_day_config_input_dto m)
        {
            var result = new Services.ConfigServices().BatchSaveSalesDayConfig(m, AutoUtility.GetUser());
            return new JsonResult(result);
        }


        [HttpGet]
        [UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【周转表】->【清除销量配置】删除", 1)]
        public JsonResult SaveSalesDayConfigDelete(int id)
        {
            var result = new Services.ConfigServices().SaveSalesDayConfigDelete(id);
            return new JsonResult(result);
        }

        [HttpGet]
        [UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【周转表】->【批量清除销量配置】删除", 1)]
        public JsonResult BatchSaveSalesDayConfigDelete(string bailun_sku,string warehouse_code)
        {
            var result = new Services.ConfigServices().BatchSaveSalesDayConfigDelete(bailun_sku, warehouse_code);
            return new JsonResult(result);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpPost]
        [UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【周转表】->【销量导入】->【导入】操作", 1)]
        public async Task<ActionResult<RequestResultDto>> SalesDayConfigImport(IFormFile file)
        {
            try
            {
                var user = AutoUtility.GetUser();
                var dataTable = new Services.ConfigServices().SalesDayConfigImport(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 };
            }

        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpPost]
        //[UseAction]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【周转表】->【默认头程方式】->【导入】操作", 1)]
        public async Task<ActionResult<RequestResultDto>> HeadConfigImport(IFormFile file)
        {
            try
            {
                var user = AutoUtility.GetUser();
                var dataTable = new Services.ConfigServices().HeadConfigImport(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 };
            }

        }
    }
}