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

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


        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【ip+de投资回报分析】->【搜索】页面", 0)]
        public JsonResult AnaList(int limit, int offset, string order, string sort)
        {
            var total = 0;
            var service = new Services.ReportInvestReturnService();
            var list = service.AnaList(new Condition_ConfigPromotion { }, offset, limit, order, sort, ref total);

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

        public FileResult AnaExport()
        {
            int total = 0;
            var service = new Services.ReportInvestReturnService();
            var list = service.AnaList(new Condition_ConfigPromotion { }, 0, int.MaxValue, null, null, ref total);

            DataTable table = new DataTable();
            string[] cols = new string[] {
                "sku",  "所属项目", "标题",  "采购单价 ￥", "仓库编码", "仓库名称", "仓库类型", "总库存（在库+在途）", "总金额 （在库+在途）", "日均销量", "过去30天销量", "过去7天销量",  "出单天数 (总)", "出单天数 (过去30天)", "首次出单日期", "最后出单日期",
                "30天利润 CNY",   "可售天数",   "采购在途数量",  "采购在途金额",   "头程在途",    "头程在途金额",  "在库库存",   "在库金额 CNY",   "预估运费 CNY",  "单位头程费", "预测30天销量", "预测30天销售额 CNY",
                "最近30天的平均销售单价  CNY",  "广告费率",  "最近30天广告费 USD", "最近30天的销售额 USD",  "最近30天的平台费 USD", "平台费率", "最近30天的退款金额 USD", "退款金额占比",  "最后更新时间", "库存管理得分",
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

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

                row["sku"] = itemData.sku;
                row["所属项目"] = itemData.project;
                row["最近30天广告费 USD"] = itemData.adfee_day_30;
                row["标题"] = itemData.sku_name;
                row["采购单价 ￥"] = itemData.price;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["仓库类型"] = itemData.warehouse_type;
                row["总库存（在库+在途）"] = itemData.stock;
                row["总金额 （在库+在途）"] = itemData.stock_amount;
                row["日均销量"] = itemData.sales_day_average;
                row["过去30天销量"] = itemData.sales_day_30;
                row["过去7天销量"] = itemData.sales_day_7;
                row["出单天数 (总)"] = itemData.order_days;
                row["出单天数 (过去30天)"] = itemData.consume_days_30;
                row["首次出单日期"] = itemData.first_order_date == null ? "" : itemData.first_order_date.Value.ToString("`yyyy-MM-dd");
                row["最后出单日期"] = itemData.last_order_date == null ? "" : itemData.last_order_date.Value.ToString("`yyyy-MM-dd");
                row["30天利润 CNY"] = itemData.profit_30_forecast;
                row["可售天数"] = itemData.vendibility_days;
                row["采购在途数量"] = itemData.quantity_purchase;
                row["采购在途金额"] = itemData.quantity_purchase_amount;
                row["头程在途"] = itemData.quantity_transfer;
                row["头程在途金额"] = itemData.quantity_transfer_amount;
                row["在库库存"] = itemData.library_stock;
                row["在库金额 CNY"] = itemData.library_stock_amount;
                row["预估运费 CNY"] = itemData.estimated_freight;
                row["单位头程费"] = itemData.freight_unit_price;
                row["预测30天销量"] = itemData.sales_day_30_forecast;
                row["预测30天销售额 CNY"] = itemData.gmv_day_30_forecast_cny;
                row["最近30天的平均销售单价  CNY"] = itemData.gmv_day30_avg_unit_price_cny;
                row["广告费率"] = itemData.adfee_rate.ToString("P");
                row["平台费率"] = itemData.platform_fee_rate.ToString("P");
                row["退款金额占比"] = itemData.refund_rate.ToString("P");
                row["最近30天的销售额 USD"] = itemData.amount_total_day_30;
                row["最近30天的平台费 USD"] = itemData.platform_fee_day_30;
                row["最近30天的退款金额 USD"] = itemData.refund_amount_day_30;
                row["最后更新时间"] = itemData.gmt_update_time.ToString("yyyy-MM-dd HH:mm:ss");
                row["库存管理得分"] = itemData.stock_score;

                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");
        }
    }
}