using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Bailun.DC.Models;
using Bailun.DC.Services;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Hosting;

namespace Bailun.DC.Web.Areas.Reports.Controllers
{
    [Area("Reports")]
    public class SkuController : Base.BaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public SkuController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Sku列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ListSku()
        {
            return View();
        }

        /// <summary>
        /// sku列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="sku"></param>
        /// <param name="skuname"></param>
        /// <returns></returns>
        public string ListSkuJson(BtTableParameter parameter,string sku,string skuname)
        {
            var total = 0;
            var services = new Services.SkuInfoServices();
            var obj = services.ListSku(parameter,sku,skuname,ref total);

            var countM = services.ListSkuCount(sku, skuname);

            countM.sku_title_cn = "总计：";
            countM.amount_onedaysale = Math.Round(countM.amount_onedaysale ?? 0, 2, MidpointRounding.AwayFromZero);
            countM.amount_stock = Math.Round(countM.amount_stock ?? 0, 2, MidpointRounding.AwayFromZero);
            countM.amount_transit = Math.Round(countM.amount_transit ?? 0, 2, MidpointRounding.AwayFromZero);
            countM.purchase_amount = Math.Round(countM.purchase_amount ?? 0, 2, MidpointRounding.AwayFromZero);

            var list = obj.Select(p => new {
                amount_onedaysale = p.amount_onedaysale??0,
                amount_stock = p.amount_stock??0,
                amount_transit = p.amount_transit??0,
                p.bailun_sku,
                p.category_name,
                fourteenday_total_sales = p.fourteenday_total_sales??0,
                noshippingcount = p.noshippingcount??0,
                nostockcount = p.nostockcount??0,
                oneday_total_sales = p.oneday_total_sales??0,
                purchase_amount = p.purchase_amount??0,
                quantity_purchase = p.quantity_purchase??0,
                quantity_transfer = p.quantity_transfer??0,
                sevenday_total_sales = p.sevenday_total_sales??0,
                p.sku_image,
                p.sku_title_cn,
                p.sku_title_en,
                thirtyday_total_sales = p.thirtyday_total_sales??0,
                usable_stock = p.usable_stock??0,
            });


            return JsonConvert.SerializeObject(new { total = total, rows = list, count_row=countM });
        }

        public ActionResult ListSkuDiffWeigh()
        {
            return View();
        }

        /// <summary>
        /// sku发货重量差异表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="sku">sku编码</param>
        /// <param name="shipstart">发货开始时间</param>
        /// <param name="shipend">发货结束时间</param>
        /// <param name="min">差异开始值</param>
        /// <param name="max">差异结束值</param>
        /// <returns></returns>
        public string ListSkuDiffWeighJson(BtTableParameter parameter, string sku, DateTime? shipstart, DateTime? shipend, int? min, int? max)
        {
            var total = 0;
            var obj = new Services.OrdersServices().ListWeighDiff(parameter, shipstart, shipend, min, max, sku, ref total).Select(a=>new {
                a.bailun_sku,
                a.bailun_sku_outbound_weight,
                day = a.day.ToString("yyyy-MM-dd"),
                a.diffweigh,
                a.pick_order_id,
                a.weight
            });

            return JsonConvert.SerializeObject(new { total = total, rows = obj });
        }

        /// <summary>
        /// 导出Sku发货重量差异明细
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="shipstart"></param>
        /// <param name="shipend"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public ActionResult ExportSkuDiffWeigh(string sku, DateTime? shipstart, DateTime? shipend, int? min, int? max)
        {
            var obj = new Services.OrdersServices().ListWeighDiff(shipstart, shipend, min, max, sku);

            var colNames = new List<string> {"日期","配货单号","sku","sku重量", "发货重量", "重量差异值"};

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.day.ToString("yyyy-MM-dd") + "|" + item.pick_order_id + "|" + item.bailun_sku + "|" + item.weight + "|" + item.bailun_sku_outbound_weight + "|" +
                    item.diffweigh
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "sku发货重量差异 " + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }


        /// <summary>
        /// sku库龄列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ListInventoryAging()
        {
            return View();
        }

        /// <summary>
        /// sku库龄列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="sku">sku编码</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="type">库龄，3：3个月以上，6：6个月以上，12：1年以上，24：2年以上，36：3年以上，4：3个月以上，6个月以下，7：6个月以上，12个月以下，13：12个月以上，24个月以下，25：24个月以上，36个月以下</param>
        /// <returns></returns>
        public string ListInventoryAgingJson(BtTableParameter parameter, string sku, string warehouse,string warehousetype, int type)
        {
            var total = 0;

            var start = DateTime.Parse("1990-01-01");
            var end = DateTime.Now;

            switch (type)
            {
                case 3:
                case 6:
                case 12:
                case 24:
                case 36:
                    end = end.AddMonths(-type);
                    break;
                case 4:
                    start = DateTime.Now.AddMonths(-6);
                    end = DateTime.Now.AddMonths(-3);
                    break;
                case 7:
                    start = DateTime.Now.AddMonths(-12);
                    end = DateTime.Now.AddMonths(-6);
                    break;
                case 13:
                    start = DateTime.Now.AddMonths(-24);
                    end = DateTime.Now.AddMonths(-12);
                    break;
                case 25:
                    start = DateTime.Now.AddMonths(-36);
                    end = DateTime.Now.AddMonths(-24);
                    break;
            }

            var _service = new Services.InventoryServices();
            var obj = _service.ListStockDate(parameter, sku,warehousetype,warehouse, start, end, ref total);
            var objCount = _service.ListStockDateCount(sku, warehousetype, warehouse, start, end);

            var list = obj.Select(a => new {
                a.bailun_sku,
                a.warehouse_code,
                a.warehouse_name,
                quantity_stock = a.quantity_stock.ToString("N0"),
                amount = a.amount.ToString("N2"),
                stock_time = (DateTime.Now-a.stock_time).Days+"d"
            });


            return JsonConvert.SerializeObject(new { total = total, rows = list,
                count_row = new {
                    warehouse_name = "总计",
                    quantity_stock = objCount.quantity_stock.ToString("N0"),
                    amount = objCount.amount.ToString("N2")
                }
            });
        }

        /// <summary>
        /// 导出库龄明细
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="type">库龄，3：3个月以上，6：6个月以上，12：1年以上，24：2年以上，36：3年以上，4：3个月以上，6个月以下，7：6个月以上，12个月以下，13：12个月以上，24个月以下，25：24个月以上，36个月以下</param>
        /// <returns></returns>
        public ActionResult ExportInventoryAging(string sku,string warehousetype, string warehouse, int type)
        {
            var typename = "";
            var total = 0;
            var start = DateTime.Parse("1990-01-01");
            var end = DateTime.Now;

            switch (type)
            {
                case 3:
                case 6:
                case 12:
                case 24:
                case 36:
                    typename = type + "个月以上的";
                    end = end.AddMonths(-type);
                    break;
                case 4:
                    typename = "3至6个月的";
                    start = DateTime.Now.AddMonths(-6);
                    end = DateTime.Now.AddMonths(-3);
                    break;
                case 7:
                    typename = "6至12个月的";
                    start = DateTime.Now.AddMonths(-12);
                    end = DateTime.Now.AddMonths(-6);
                    break;
                case 13:
                    typename = "12至24个月的";
                    start = DateTime.Now.AddMonths(-24);
                    end = DateTime.Now.AddMonths(-12);
                    break;
                case 25:
                    typename = "24至36个月的";
                    start = DateTime.Now.AddMonths(-36);
                    end = DateTime.Now.AddMonths(-24);
                    break;
            }

            var _service = new Services.InventoryServices();
            var obj = _service.ListStockDate(new BtTableParameter { limit=0}, sku, warehousetype, warehouse, start, end, ref total);

            var colNames = new List<string> {"sku","仓库编码","仓库名称", "库存数量", "库存金额","库龄(天)"};

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.bailun_sku + "|" + item.warehouse_code + "|" + item.warehouse_name + "|" + item.quantity_stock + "|" + item.amount+"|"+(DateTime.Now-item.stock_time).Days+"d");
            }

            var guid = Guid.NewGuid().ToString();
            var filename = typename + "库龄明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
            
        }


    }
}