using AutoTurnOver.Common;
using AutoTurnOver.Models;
using AutoTurnOver.Models.ApiDto.WeeklyStatistics;
using AutoTurnOver.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Data;
using System.IO;

namespace AutoTurnOver.Controllers
{
    /// <summary>
    /// 普货周数据统计
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WeeklyStatisticsController : Controller
    {
        private readonly WeeklyStatisticsServices _weeklyStatisticsServices;

        public WeeklyStatisticsController()
        {
            _weeklyStatisticsServices = new WeeklyStatisticsServices();
        }

        /// <summary>
        /// Aims周负利润订单分页数据
        /// </summary>
        /// <param name="m"></param>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【周负利润订单】->【周负利润订单】->【搜索】页面", 0)]
        public JsonResult GetWeekNegativeProfitDetailsPageList([FromQuery] week_negative_profit_details_page_input_dto m, [FromQuery] int limit, [FromQuery] int offset)
        {
            var total = 0;
            var list = _weeklyStatisticsServices.GetWeekNegativeProfitDetailsPageList(m, offset, limit, ref total);

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

        /// <summary>
        /// 导出周负利润订单数据
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [NoLogin]
        public FileResult WeekNegativeProfitDetailsExport([FromQuery] week_negative_profit_details_page_input_dto m)
        {
            var services = new ReportServices();
            var total = 0;
            var list = _weeklyStatisticsServices.GetWeekNegativeProfitDetailsPageList(m, 0, 0, ref total);

            DataTable table = new DataTable();
            string[] cols = new string[] {
                "商品编码", "SKU","名称","平台", "简易分类","采购员", "周销量", "周gmv","周成本", "周退款数", "周退款金额", "利润率", "利润额","退款率","起始日期","结束日期","创建时间"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

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

                row["商品编码"] = itemData.bailun_sku;
                row["SKU"] = itemData.bailun_sku;
                row["名称"] = itemData.sku_title_cn;
                row["平台"] = itemData.platform;
                row["简易分类"] = itemData.simple_category;
                row["采购员"] = itemData.buyer_name;
                row["周销量"] = itemData.weekly_sales;
                row["周gmv"] = itemData.weekly_gmv;
                row["周成本"] = itemData.weekly_cost;
                row["周退款数"] = itemData.weekly_refunds_num;
                row["周退款金额"] = itemData.weekly_refund_amount;
                row["利润率"] = itemData.profit_margin;
                row["利润额"] = itemData.amount_of_profit;
                row["退款率"] = itemData.refund_rate;
                row["起始日期"] = itemData.start_date;
                row["结束日期"] = itemData.end_date;
                row["创建时间"] = itemData.create_date_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");
        }

        /// <summary>
        /// 分页查询aims-本周新增冗余明细
        /// </summary>
        /// <param name="m"></param>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【本周新增冗余】->【搜索】页面", 0)]
        public JsonResult GetWeekRedundancyDetailsPageList([FromQuery] week_redundancy_details_page_input_dto m, [FromQuery] int limit, [FromQuery] int offset)
        {
            var total = 0;
            var list = _weeklyStatisticsServices.GetWeekRedundancyDetailsPageList(m, offset, limit, ref total);

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

        /// <summary>
        /// 导出本周新增冗余明细
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        [NoLogin]
        public FileResult WeekRedundancyDetailsExport([FromQuery] week_redundancy_details_page_input_dto m)
        {
            var services = new ReportServices();
            var total = 0;
            var list = _weeklyStatisticsServices.GetWeekRedundancyDetailsPageList(m, 0, 0, ref total);

            DataTable table = new DataTable();
            string[] cols = new string[] {
                "商品编码", "SKU", "仓库编码", "仓库名称","平台", "简易分类","采购员", "入库时间", "过去7天日均", "总库存数", "总库存金额","冗余数","冗余金额","冗余发生日期","起始日期","结束日期","创建时间"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

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

                row["商品编码"] = itemData.product_code;
                row["SKU"] = itemData.bailun_sku;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["平台"] = itemData.platform;
                row["简易分类"] = itemData.simple_category;
                row["采购员"] = itemData.buyer_name;
                row["入库时间"] = itemData.warehousing_time;
                row["过去7天日均"] = itemData.seven_days_average;
                row["总库存数"] = itemData.total_inventory;
                row["总库存金额"] = itemData.total_inventory_amount;
                row["冗余数"] = itemData.redundant_number;
                row["冗余金额"] = itemData.redundancy_amount;
                row["冗余发生日期"] = itemData.redundancy_occurrence_date;
                row["起始日期"] = itemData.start_date;
                row["结束日期"] = itemData.end_date;
                row["创建时间"] = itemData.create_date_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");
        }

        /// <summary>
        /// 分页aims普货周缺货数据明细
        /// </summary>
        /// <param name="m"></param>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->->【aims普货周缺货】->【搜索】页面", 0)]
        public JsonResult GetWeekShortagePageList([FromQuery] week_shortage_details_page_input_dto m, [FromQuery] int limit, [FromQuery] int offset)
        {
            var total = 0;
            var list = _weeklyStatisticsServices.GetWeekShortagePageList(m, offset, limit, ref total);

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

        /// <summary>
        /// 导出aims普货周缺货数据明细
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        [NoLogin]
        public FileResult WeekShortageExport([FromQuery] week_shortage_details_page_input_dto m)
        {
            var total = 0;
            var list = _weeklyStatisticsServices.GetWeekShortagePageList(m, 0, 0, ref total);

            DataTable table = new DataTable();
            string[] cols = new string[] {
                "商品编码", "SKU", "仓库编码", "仓库名称","平台", "简易分类","采购员", "入库时间", "历史采购数量", "历史销售数量", "过去7天日均","缺货时间","pds开发竞品item",
                "ana市场模糊7日均","第一销售平台7日均","第二销售平台7日均","安全库存","创建时间"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

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

                row["商品编码"] = itemData.bailun_sku;
                row["SKU"] = itemData.bailun_sku;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_code;
                row["平台"] = itemData.platform;
                row["简易分类"] = itemData.simple_category;
                row["采购员"] = itemData.buyer_name;
                row["入库时间"] = itemData.warehousing_time;
                row["历史采购数量"] = itemData.historical_purchase_quantity;
                row["历史销售数量"] = itemData.historical_sales_quantity;
                row["过去7天日均"] = itemData.seven_days_average;
                row["缺货时间"] = itemData.stockout_time;
                row["pds开发竞品item"] = itemData.pds_item_id;
                row["ana市场模糊7日均"] = itemData.ana_seven_days_average;
                row["第一销售平台7日均"] = itemData.first_sales_platform_average;
                row["第二销售平台7日均"] = itemData.second_sales_platform_average;
                row["安全库存"] = itemData.safety_stock;
                //row["起始日期"] = itemData.start_date;
                //row["结束日期"] = itemData.end_date;
                row["创建时间"] = itemData.create_date_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");
        }
    }
}