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;
using Bailun.ServiceFabric.Core.Extension;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension.HttpContext;

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>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【库存】->【库存周转报表】->【sku】->【查询】页面", 0)]
        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.one_day_sale_amount = Math.Round(countM.one_day_sale_amount ?? 0, 2, MidpointRounding.AwayFromZero);
            countM.amount_stock = Math.Round(countM.amount_stock ?? 0, 2, MidpointRounding.AwayFromZero);
            countM.amount_onway_allot = Math.Round(countM.amount_onway_allot ?? 0, 2, MidpointRounding.AwayFromZero);
            countM.amount_onway_purchase = Math.Round(countM.amount_onway_purchase ?? 0, 2, MidpointRounding.AwayFromZero);

            var list = obj.Select(p => new {
                amount_onway_allot = p.amount_onway_allot??0,
                amount_onway_purchase = p.amount_onway_purchase??0,
                p.amount_stock,
                p.bailun_sku,
                p.category_name,
                p.count_onway_allot,
                p.count_onway_purchase,
                p.count_outstock,

                p.count_stock,
                p.count_unshipping,
                p.fourteen_day_sale_count,
                p.one_day_sale_amount,
                p.one_day_sale_count,
                p.seven_day_sale_count,
                p.sku_image,

                p.sku_title_cn,
                p.sku_title_en,
                p.thirty_day_sale_count,
            });


            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>
        [BailunAuthentication(LoginMode.Enforce)]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【数据分析】->【Sku发货重量差异】->【查询】页面", 0)]
        public string ListSkuDiffWeighJson(BtTableParameter parameter, string sku, string warehousetype,string warehousecode,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, warehousetype,warehousecode).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,
                a.warehouse_name
            });

            return JsonConvert.SerializeObject(new { total = total, rows = obj,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportSkuDiffWeigh", ServiceFabric.Core.Extension.HttpContext.HttpContextHelper.Current.User.GetUserName()),
            });
        }

        /// <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, string warehousetype, string warehousecode, DateTime? shipstart, DateTime? shipend, int? min, int? max)
        {
            var obj = new Services.OrdersServices().ListWeighDiff(shipstart, shipend, min, max, sku,warehousetype,warehousecode);

            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+"|"+item.warehouse_name
                    );
            }

            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>
        [BailunAuthentication(LoginMode.Enforce)]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【库存】->【库龄列表】->【查询】页面", 0)]
        public string ListInventoryAgingJson(BtTableParameter parameter, string sku, string warehouse,string warehousetype, int type,string buyername)
        {
            var total = 0;

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

            switch (type)
            {
                case 0:  //1个月以下的
                    start = DateTime.Now.AddMonths(-1);
                    break;
                case -3: //0-3个月的
                    start = DateTime.Now.AddMonths(-3);
                    break;
                case 1: //1个月以上
                    end = end.AddMonths(-type);
                    break;
                case 2:  //1-3个月
                    start = DateTime.Now.AddMonths(-3);
                    end = DateTime.Now.AddMonths(-1);
                    break;
                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,buyername, ref total);
            var objCount = _service.ListStockDateCount(sku, warehousetype, warehouse, start, end,buyername);

            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"),
                    
                },
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportInventoryAging", HttpContextHelper.Current.User.GetUserName()),
            });
        }

        
        /// <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,string buyername)
        {
            var typename = "";
            var total = 0;
            var start = DateTime.Parse("1990-01-01");
            var end = DateTime.Now;

            switch (type)
            {
                case 0:  //1个月以下的
                    start = DateTime.Now.AddMonths(-1);
                    break;
                case -3: //0-3个月的
                    start = DateTime.Now.AddMonths(-3);
                    break;
                case 1: //1个月以上
                    end = end.AddMonths(-type);
                    break;
                case 2:  //1-3个月
                    start = DateTime.Now.AddMonths(-3);
                    end = DateTime.Now.AddMonths(-1);
                    break;
                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(new BtTableParameter { limit=0}, sku, warehousetype, warehouse, start, end, buyername, 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");
            
        }

        /// <summary>
        /// 获取SKU的所有品牌
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSkuBrand()
        {
            try
            {
                var list = new Services.SkuInfoServices().ListBrand().Where(a=>!string.IsNullOrEmpty(a));

                return Json(new
                {
                    success = true,
                    msg = "",
                    list = list
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                });
            }
            
        }
    }
}