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

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

        public WarehouseController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

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

        /// <summary>
        /// 逻辑仓库 库存
        /// </summary>
        /// <returns></returns>
        public ActionResult LogicWarehouse()
        {
            ViewBag.EndDate = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartOneDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartSevenDate = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartFourteenDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartThirtyDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd") + " 00:00:00";


            return View();
        }

        /// <summary>
        /// 获取财务分类列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListFinanceCategory()
        {
            var list = new Services.SkuInfoServices().ListFinanceCategory();

            return Json(list);
        }

        /// <summary>
        /// 获取半成品产品大类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSemiSkuCategory()
        {
            var list = new Services.SkuInfoServices().ListSemiSkuCategory();

            return Json(list.Select(a=>new { 
                a.product_category_id,
                a.product_category_name
            }));
        }

        /// <summary>
        /// 逻辑仓库 库存列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="isfinish">成品或原料，1：成品，2：原料</param>
        /// <param name="category">产品类型</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【库存】->【库存周转报表】->【逻辑仓库】->【查询】页面", 0)]
        public string LogicWarehouseJson(BtTableParameter parameter, string warehousetype, string warehousecode,int? isfinish,string category)
        {
            var user = HttpContextHelper.Current?.User;

            var service = new Services.WareHouseServices();
            var total = 0;
            var obj = service.ListLogicWarehouseStock(parameter, warehousetype, warehousecode,isfinish,category, ref total);

            var countM = service.LogicWarehouseStockCount(warehousetype, warehousecode, isfinish, category);

            countM.warehouse_name = "总计";
            countM.amount_onedaysale = Math.Round(countM.amount_onedaysale ?? 0, 2, MidpointRounding.AwayFromZero);
            countM.amount_stock = Math.Round(countM.amount_stock, 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);

            //,sum(cash_in_30days) as cash_in_30days,sum(cash_out_30days) as cash_out_30days,sum(cash_net) as cash_net

            var list = obj.Select(p => new
            {
                amount_onedaysale = (p.amount_onedaysale ?? 0).ToString("N2"),
                amount_stock = p.amount_stock.ToString("N2"),
                amount_transit = (p.amount_transit ?? 0.00M).ToString("N2"),
                fourteenday_total_sales = (p.fourteenday_total_sales ?? 0).ToString("N0"),
                noshippingcount = (p.noshippingcount ?? 0).ToString("N0"),
                nostockcount = (p.nostockcount ?? 0).ToString("N0"),
                oneday_total_sales = (p.oneday_total_sales ?? 0).ToString("N0"),
                purchase_amount = (p.purchase_amount ?? 0).ToString("N2"),
                quantity_purchase = (p.quantity_purchase ?? 0).ToString("N0"),
                quantity_transfer = (p.quantity_transfer ?? 0).ToString("N0"),
                sevenday_total_sales = (p.sevenday_total_sales ?? 0).ToString("N0"),
                thirtyday_total_sales = (p.thirtyday_total_sales ?? 0).ToString("N0"),
                usable_stock = p.usable_stock.ToString("N0"),
                p.warehouse_code,
                p.warehouse_name,
                p.hq_type,
                quantity_tuneout_onway = (p.quantity_tuneout_onway ?? 0).ToString("N0"),
                quantity_tuneout_30days = (p.quantity_tuneout_30days ?? 0).ToString("N0"),
                quantity_tunein_30days = (p.quantity_tunein_30days ?? 0).ToString("N0"),
                cash_in_30days = (p.cash_in_30days ?? 0).ToString("N2"),
                cash_out_30days = (p.cash_out_30days ?? 0).ToString("N2"),
                cash_net = (p.cash_net ?? 0).ToString("N2"),
                pin_rate_stock = ((p.pin_rate_stock ?? 0) * 100).ToString("N2"),


                amount_tunein_30days = (p.amount_tunein_30days ?? 0).ToString("N2"),
                amount_tuneout_30days = (p.amount_tuneout_30days ?? 0).ToString("N2"),
                sevenday_total_sales_amount = (p.sevenday_total_sales_amount).ToString("N2"),
                fourteenday_total_sales_amount = (p.fourteenday_total_sales_amount ?? 0).ToString("N2"),
                thirtyday_total_sales_amount = (p.thirtyday_total_sales_amount ?? 0).ToString("N2"),

                stock_age_6months = (p.stock_age_6months??0),
                stock_age_6months_amount = (p.stock_age_6months_amount??0).ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    countM.warehouse_name,
                    amount_onedaysale = (countM.amount_onedaysale ?? 0).ToString("N2"),
                    amount_stock = countM.amount_stock.ToString("N2"),
                    amount_transit = (countM.amount_transit ?? 0).ToString("N2"),
                    noshippingcount = (countM.noshippingcount ?? 0).ToString("N0"),
                    nostockcount = (countM.nostockcount ?? 0).ToString("N0"),
                    oneday_total_sales = (countM.oneday_total_sales ?? 0).ToString("N0"),
                    purchase_amount = (countM.purchase_amount ?? 0).ToString("N2"),
                    quantity_purchase = (countM.quantity_purchase ?? 0).ToString("N0"),
                    quantity_transfer = (countM.quantity_transfer ?? 0).ToString("N0"),
                    sevenday_total_sales = (countM.sevenday_total_sales ?? 0).ToString("N0"),
                    thirtyday_total_sales = (countM.thirtyday_total_sales ?? 0).ToString("N0"),
                    usable_stock = countM.usable_stock.ToString("N0"),
                    fourteenday_total_sales = (countM.fourteenday_total_sales ?? 0).ToString("N0"),
                    quantity_tuneout_onway = (countM.quantity_tuneout_onway ?? 0).ToString("N0"),
                    quantity_tuneout_30days = (countM.quantity_tuneout_30days ?? 0).ToString("N0"),
                    quantity_tunein_30days = (countM.quantity_tunein_30days ?? 0).ToString("N0"),
                    cash_in_30days = (countM.cash_in_30days ?? 0).ToString("N2"),
                    cash_out_30days = (countM.cash_out_30days ?? 0).ToString("N2"),
                    cash_net = (countM.cash_net ?? 0).ToString("N2"),
                    pin_rate_stock = ((countM.pin_rate_stock ?? 0) * 100).ToString("N2"),


                    amount_tunein_30days = (countM.amount_tunein_30days ?? 0).ToString("N2"),
                    amount_tuneout_30days = (countM.amount_tuneout_30days ?? 0).ToString("N2"),
                    sevenday_total_sales_amount = (countM.sevenday_total_sales_amount).ToString("N2"),
                    fourteenday_total_sales_amount = (countM.fourteenday_total_sales_amount ?? 0).ToString("N2"),
                    thirtyday_total_sales_amount = (countM.thirtyday_total_sales_amount ?? 0).ToString("N2"),
                    stock_age_6months = (countM.stock_age_6months ?? 0),
                    stock_age_6months_amount = (countM.stock_age_6months_amount ?? 0).ToString("N2"),
                },
                isexport = (UserAuthorityServices.checkUserExportAuthority("ExportLogicWarehouse", user.GetUserName()) ? 1 : 0)

            });
        }

        /// <summary>
        /// 导出逻辑仓库
        /// </summary>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public ActionResult ExportLogicWarehouse(string warehousetype, string warehousecode,int? isfinish, string category)
        {
            var service = new Services.WareHouseServices();
            var obj = service.ListLogicWarehouseStock(warehousetype, warehousecode,isfinish,category);

            var list = obj.Select(p => new
            {
                amount_onedaysale = (p.amount_onedaysale ?? 0).ToString("N2"),
                amount_stock = p.amount_stock.ToString("N2"),
                amount_transit = (p.amount_transit ?? 0.00M).ToString("N2"),
                fourteenday_total_sales = (p.fourteenday_total_sales ?? 0).ToString("N0"),
                noshippingcount = (p.noshippingcount ?? 0).ToString("N0"),
                nostockcount = (p.nostockcount ?? 0).ToString("N0"),
                oneday_total_sales = (p.oneday_total_sales ?? 0).ToString("N0"),
                purchase_amount = (p.purchase_amount ?? 0).ToString("N2"),
                quantity_purchase = (p.quantity_purchase ?? 0).ToString("N0"),
                quantity_transfer = (p.quantity_transfer ?? 0).ToString("N0"),
                sevenday_total_sales = (p.sevenday_total_sales ?? 0).ToString("N0"),
                thirtyday_total_sales = (p.thirtyday_total_sales ?? 0).ToString("N0"),
                usable_stock = p.usable_stock.ToString("N0"),
                p.warehouse_code,
                p.warehouse_name,
                quantity_tuneout_onway = p.quantity_tuneout_onway ?? 0,
                quantity_tuneout_30days = p.quantity_tuneout_30days ?? 0,
                quantity_tunein_30days = p.quantity_tunein_30days ?? 0,

                stock_age_6months = (p.stock_age_6months??0).ToString("N0"),
                stock_age_6months_amount = (p.stock_age_6months_amount??0).ToString("N2"),
                skucategory = category,
            });

            var colNames = new List<string> {"仓储仓库","库存数量","库存金额", "采购在途数量", "采购在途金额",
                                             "调拨在途数量", "调拨在途金额","待发货数量","缺货数量","调出在途数",
                                             "30天内调出数","30天内调入数","昨日总销量","昨日总销售额","七天销量",
                                             "十四天销量","三十天销量","半年以上库龄","半年以上库龄金额","产品类型"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.warehouse_name + "|" + item.usable_stock + "|" + item.amount_stock + "|" + item.quantity_purchase + "|" + item.purchase_amount + "|" +
                    item.quantity_transfer + "|" + item.amount_transit + "|" + item.noshippingcount + "|" + item.nostockcount + "|" + item.quantity_tuneout_onway + "|" +
                    item.quantity_tuneout_30days + "|" + item.quantity_tunein_30days + "|" + item.oneday_total_sales + "|" + item.amount_onedaysale + "|" + item.sevenday_total_sales + "|" +
                    item.fourteenday_total_sales + "|" + item.thirtyday_total_sales + "|" + item.stock_age_6months + "|" + item.stock_age_6months_amount+"|"+item.skucategory
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "逻辑仓库" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(listVal, 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>
        /// <param name="code">仓库编码</param>
        /// <returns></returns>
        public ActionResult ListWareHouseSku(string code, string available_days, int? onedaysalescount,DateTime? day, int? isfinish, string category)
        {
            ViewBag.warehousecode = code;
            ViewBag.available_days = available_days;

            var _warehouseService = new Services.WareHouseServices();

            var listWareHouse = _warehouseService.List("", null).OrderBy(a => a.warehouse_name).ToList();
            var listSemiWarehouse = _warehouseService.ListSemiWareHouseNew();

            listWareHouse.AddRange(listSemiWarehouse.Select(b => new dc_base_warehouse { 
                warehouse_code = b.warehouse_code,
                warehouse_name = b.warehouse_name,
                hq_type = "半成品仓"
            }));

            ViewBag.listWarehouse = listWareHouse;

            ViewBag.EndDate = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartOneDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartSevenDate = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartFourteenDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd") + " 00:00:00";
            ViewBag.StartThirtyDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd") + " 00:00:00";

            ViewBag.onedaysalescount = onedaysalescount;

            ViewBag.day = day.HasValue ? day.Value.ToString("yyyy-MM-dd") : "";

            ViewBag.isfinish = isfinish.HasValue ? isfinish.Value + "" : "";
            ViewBag.category = category;

            return View();
        }

        /// <summary>
        /// Sku仓库
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="code">仓库编码</param>
        /// <param name="categoryid">sku分类id</param>
        /// <param name="minordercount">14日均销量 最小值</param>
        /// <param name="maxordercount">14日均销量 最大值</param>
        /// <param name="stockmin">库存 最小值</param>
        /// <param name="stockmax">库存 最大值</param>
        /// <param name="stockamountmin">库存金额 最小值</param>
        /// <param name="stockamountmax">库存金额 最大值</param>
        /// <param name="onedaysalescount">昨日销量，0：0销量，1：0-1销量，2：1-5销量，5：5-10销量，10：大于10的销量</param>
        /// <param name="day">统计日期</param>
        /// <returns></returns>
        public string ListWareHouseSkuJson(BtTableParameter parameter, string warehousecode, int? push_status, int? minordercount, int? maxordercount, int? stockmin, int? stockmax, decimal? stockamountmin, decimal? stockamountmax, string skucategoryids, string available_days, int? onedaysalescount,DateTime? day, int? isfinish, string category)
        {
            var total = 0;

            int? available_days_start = null;
            int? available_days_end = null;
            if (!string.IsNullOrEmpty(available_days))
            {
                var arr = available_days.Split('-');
                if (arr.Length > 1)
                {
                    var tempnum = 0;
                    int.TryParse(arr[0], out tempnum);
                    if (tempnum > 0)
                    {
                        available_days_start = tempnum;
                    }

                    int.TryParse(arr[1], out tempnum);
                    if (tempnum > 0)
                    {
                        available_days_end = tempnum;
                    }
                }
            }

            var _service = new Services.WareHouseServices();

            var obj = _service.ListWareHouseSku(parameter, warehousecode, null, minordercount, maxordercount, stockmin, stockmax, stockamountmin, stockamountmax, skucategoryids, push_status, available_days_start, available_days_end, ref total,category,day,onedaysalescount);

            var objCount = _service.ListWareHouseSkuCount(warehousecode, null, minordercount, maxordercount, stockmin, stockmax, stockamountmin, stockamountmax, skucategoryids, push_status, available_days_start, available_days_end,category,day, onedaysalescount);

            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,
                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,

                push_status = p.push_status == 1 ? "是" : "否",
                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,
                p.warehouse_code,
                p.warehouse_name,
                quantity_tuneout_onway = p.quantity_tuneout_onway ?? 0,
                quantity_tuneout_30days = p.quantity_tuneout_30days,
                quantity_tunein_30days = (p.quantity_tunein_30days ?? 0),
                fourteenday_total_sales = (p.fourteenday_total_sales ?? 0),

                cash_in_30days = (p.cash_in_30days ?? 0).ToString("N2"),
                cash_out_30days = (p.cash_out_30days ?? 0).ToString("N2"),
                cash_net = (p.cash_net ?? 0).ToString("N2"),
                pin_rate_stock = ((p.pin_rate_stock ?? 0) * 100).ToString("N2"),
                p.available_days,

                p.hq_type,

                amount_tunein_30days = (p.amount_tunein_30days ?? 0).ToString("N2"),
                amount_tuneout_30days = (p.amount_tuneout_30days ?? 0).ToString("N2"),
                sevenday_total_sales_amount = (p.sevenday_total_sales_amount).ToString("N2"),
                fourteenday_total_sales_amount = (p.fourteenday_total_sales_amount ?? 0).ToString("N2"),
                thirtyday_total_sales_amount = (p.thirtyday_total_sales_amount ?? 0).ToString("N2"),

                stock_age_6months = (p.stock_age_6months ?? 0),
                stock_age_6months_amount = (p.stock_age_6months_amount ?? 0).ToString("N2"),
                p.skucategory
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    sku_title_cn = "合计",
                    amount_onedaysale = objCount.amount_onedaysale ?? 0,
                    amount_stock = objCount.amount_stock ?? 0,
                    amount_transit = objCount.amount_transit ?? 0,
                    noshippingcount = objCount.noshippingcount ?? 0,
                    nostockcount = objCount.nostockcount ?? 0,
                    oneday_total_sales = objCount.oneday_total_sales ?? 0,
                    purchase_amount = objCount.purchase_amount ?? 0,
                    quantity_purchase = objCount.quantity_purchase ?? 0,
                    quantity_transfer = objCount.quantity_transfer ?? 0,
                    sevenday_total_sales = objCount.sevenday_total_sales ?? 0,

                    thirtyday_total_sales = objCount.thirtyday_total_sales ?? 0,
                    usable_stock = objCount.usable_stock ?? 0,
                    quantity_tuneout_onway = objCount.quantity_tuneout_onway ?? 0,
                    quantity_tuneout_30days = objCount.quantity_tuneout_30days,
                    quantity_tunein_30days = (objCount.quantity_tunein_30days ?? 0),
                    fourteenday_total_sales = (objCount.fourteenday_total_sales ?? 0),

                    cash_in_30days = (objCount.cash_in_30days ?? 0).ToString("N2"),
                    cash_out_30days = (objCount.cash_out_30days ?? 0).ToString("N2"),
                    cash_net = (objCount.cash_net ?? 0).ToString("N2"),
                    pin_rate_stock = ((objCount.pin_rate_stock ?? 0) * 100).ToString("N2"),

                    amount_tunein_30days = (objCount.amount_tunein_30days ?? 0).ToString("N2"),
                    amount_tuneout_30days = (objCount.amount_tuneout_30days ?? 0).ToString("N2"),
                    sevenday_total_sales_amount = (objCount.sevenday_total_sales_amount).ToString("N2"),
                    fourteenday_total_sales_amount = (objCount.fourteenday_total_sales_amount ?? 0).ToString("N2"),
                    thirtyday_total_sales_amount = (objCount.thirtyday_total_sales_amount ?? 0).ToString("N2"),

                    stock_age_6months = (objCount.stock_age_6months ?? 0),
                    stock_age_6months_amount = (objCount.stock_age_6months_amount ?? 0).ToString("N2"),
                }
            });
        }

        public ActionResult ExportWareHouseSku(string code, int? push_status, int? minordercount, int? maxordercount, int? stockmin, int? stockmax, decimal? stockamountmin, decimal? stockamountmax, string skucategoryids, string available_days, int? onedaysalescount,string category, DateTime? day)
        {
            var total = 0;
            int? available_days_start = null;
            int? available_days_end = null;
            if (!string.IsNullOrEmpty(available_days))
            {
                var arr = available_days.Split('-');
                if (arr.Length > 1)
                {
                    var tempnum = 0;
                    int.TryParse(arr[0], out tempnum);
                    if (tempnum > 0)
                    {
                        available_days_start = tempnum;
                    }

                    int.TryParse(arr[1], out tempnum);
                    if (tempnum > 0)
                    {
                        available_days_end = tempnum;
                    }
                }
            }
            var obj = new Services.WareHouseServices().ListWareHouseSku(new BtTableParameter { offset = 0, limit = 0 }, code, null, minordercount, maxordercount, stockmin, stockmax, stockamountmin, stockamountmax, skucategoryids, push_status, available_days_start, available_days_end, ref total, category, day, onedaysalescount);

            var colNames = new List<string>() { "仓库名称","Sku","推送产品库","分类名称","英文标题"
                ,"库存数量","库存金额","采购在途数量","采购在途金额","调拨在途数量"
                ,"调拨在途金额","待发货数量","缺货数量","调出在途数","30天调出数"
                ,"30天调入数","昨日总销量","昨日总销售额","七天销量","十四天销量"
                ,"三十天销量","可销售天数","半年以上库龄","半年以上库龄金额","sku产品分类"
            };

            var list = new List<string>();

            foreach (var item in obj)
            {
                var str = item.warehouse_name + "|" + item.bailun_sku + "|" + (item.push_status == 1 ? "是" : "否") + "|" + item.category_name + "|" + (item.sku_title_en) + "|" +
                    (item.usable_stock ?? 0) + "|" + (item.amount_stock ?? 0) + "|" + (item.quantity_purchase ?? 0) + "|" + (item.purchase_amount ?? 0) + "|" + (item.quantity_transfer ?? 0) + "|" +
                    (item.amount_transit ?? 0) + "|" + (item.noshippingcount ?? 0) + "|" + (item.nostockcount ?? 0) + "|" + (item.quantity_tuneout_onway ?? 0) + "|" + (item.quantity_tuneout_30days ?? 0) + "|" +
                    (item.quantity_tunein_30days ?? 0) + "|" + (item.oneday_total_sales ?? 0) + "|" + (item.amount_onedaysale ?? 0) + "|" + (item.sevenday_total_sales ?? 0) + "|" + (item.fourteenday_total_sales ?? 0) + "|" +
                    (item.thirtyday_total_sales ?? 0) + "|" + (item.available_days ?? 0) + "|" + (item.stock_age_6months ?? 0) + "|" + (item.stock_age_6months_amount ?? 0)+"|"+item.skucategory;

                list.Add(str);
            }

            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>
        /// 仓库冗余报告分析
        /// </summary>
        /// <returns></returns>
        public ActionResult WarehouseRedundancy()
        {


            return View();
        }

        /// <summary>
        /// 仓库冗余报告分析数据
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="code">仓库编码</param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【库存】->【库存周转报表】->【查询】页面", 0)]
        public string WarehouseRedundancyJson(BtTableParameter parameter, string warehousetype, string code, DateTime? day)
        {
            var total = 0;
            var services = new Services.WareHouseServices();
            var obj = services.ListWarehouseRedundancy(parameter, warehousetype, code, day, ref total);

            var count_obj = services.ListWarehouseRedundancyCount(warehousetype, code, day);

            var list = obj.Select(a => new
            {
                a.warehouse_code,
                a.warehouse_name,
                amount_total = (a.amount_total ?? 0).ToString("N2"),
                dailysale_amount = (a.dailysale_amount ?? 0).ToString("N2"),
                daily_productsale_count = (a.daily_productsale_count ?? 0),
                day = a.day.ToString("yyyy-MM-dd"),
                productcount = (a.productcount ?? 0).ToString("N0"),
                productsale_rate = ((a.productsale_rate ?? 0) * 100).ToString("N4"),
                redundancy_amount = (a.redundancy_amount ?? 0).ToString("N2"),
                redundancy_amount_rate = ((a.redundancy_amount_rate ?? 0) * 100).ToString("N4"),
                redundancy_product_count = (a.redundancy_product_count ?? 0).ToString("N0"),
                redundancy_product_rate = ((a.redundancy_product_rate ?? 0) * 100).ToString("N4"),
                redundancy_sku_count = (a.redundancy_sku_count ?? 0).ToString("N0"),
                redundancy_sku_rate = ((a.redundancy_sku_rate ?? 0) * 100).ToString("N4"),
                saleamount_rate = ((a.saleamount_rate ?? 0) * 100).ToString("N4"),
                skucount = (a.skucount ?? 0).ToString("N0"),
                skusales_count = (a.skusales_count ?? 0).ToString("N2"),
                skusales_rate = ((a.skusales_rate ?? 0) * 100).ToString("N4"),
                onway_count = a.onway_count.ToString("N0"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    warehouse_name = "合计",
                    amount_total = (count_obj.amount_total ?? 0).ToString("N2"),
                    dailysale_amount = (count_obj.dailysale_amount ?? 0).ToString("N2"),
                    daily_productsale_count = (count_obj.daily_productsale_count ?? 0).ToString("N2"),
                    //day = a.day.ToString("yyyy-MM-dd"),
                    productcount = (count_obj.productcount ?? 0).ToString("N0"),
                    productsale_rate = ((count_obj.productsale_rate ?? 0) * 100).ToString("N4"),
                    redundancy_amount = (count_obj.redundancy_amount ?? 0).ToString("N2"),
                    redundancy_amount_rate = ((count_obj.redundancy_amount_rate ?? 0) * 100).ToString("N4"),
                    redundancy_product_count = (count_obj.redundancy_product_count ?? 0).ToString("N0"),
                    redundancy_product_rate = ((count_obj.redundancy_product_rate ?? 0) * 100).ToString("N4"),
                    redundancy_sku_count = (count_obj.redundancy_sku_count ?? 0).ToString("N0"),
                    redundancy_sku_rate = ((count_obj.redundancy_sku_rate ?? 0) * 100).ToString("N4"),
                    saleamount_rate = ((count_obj.saleamount_rate ?? 0) * 100).ToString("N4"),
                    skucount = (count_obj.skucount ?? 0).ToString("N0"),
                    skusales_count = (count_obj.skusales_count ?? 0).ToString("N2"),
                    skusales_rate = ((count_obj.skusales_rate ?? 0) * 100).ToString("N4"),
                    onway_count = count_obj.onway_count.ToString("N0"),
                }
            });
        }


        /// <summary>
        /// 仓库sku库存冗余分析
        /// </summary>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public ActionResult SkuRedundancy(string warehousecode, DateTime? day, string warehousename)
        {
            ViewBag.warehousecode = warehousecode;
            ViewBag.day = day.HasValue ? day.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.warehousename = warehousename;
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SkuRedundancyJson(string warehousecode, DateTime day, int? t)
        {
            var services = new Services.WareHouseServices();
            if (t.HasValue)
            {
                var obj = services.GetSkuRedundancyByType(warehousecode, day, t);

                foreach (var item in obj)
                {
                    item.productsale_rate = item.productsale_rate * 100;
                    item.saleamount_rate = item.saleamount_rate * 100;
                    item.redundancy_product_rate = item.redundancy_product_rate * 100;
                    item.redundancy_amount_rate = item.redundancy_amount_rate * 100;

                    item.day_turnover_rate = item.day_turnover_rate * 100;
                    item.week_turnover_rate = item.week_turnover_rate * 100;
                    item.month_turnover_rate = item.month_turnover_rate * 100;

                }

                return Json(obj);
            }
            else
            {
                var obj = services.GetSkuRedundancy(warehousecode, day);
                return Json(obj);
            }
        }

        /// <summary>
        /// 导出sku冗余报表
        /// </summary>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="day">统计日期</param>
        /// <param name="t">类型</param>
        /// <returns></returns>
        public ActionResult ExportSkuRedundancy(string warehousecode, DateTime day, int? t)
        {
            var services = new Services.WareHouseServices();
            if (t.HasValue)
            {
                var obj = services.GetSkuRedundancyByType(warehousecode, day, t);

                foreach (var item in obj)
                {
                    item.productsale_rate = item.productsale_rate * 100;
                    item.saleamount_rate = item.saleamount_rate * 100;
                    item.redundancy_product_rate = item.redundancy_product_rate * 100;
                    item.redundancy_amount_rate = item.redundancy_amount_rate * 100;

                    item.day_turnover_rate = item.day_turnover_rate * 100;
                    item.week_turnover_rate = item.week_turnover_rate * 100;
                    item.month_turnover_rate = item.month_turnover_rate * 100;

                }

                var listCol = new List<string> { "sku", "产品编码", "sku标题", "产品个数", "在途数", "库存总金额", "日销产品个数", "动销产品比例", "日销金额", "动销金额比例", "冗余产品个数", "冗余个数比例", "冗余金额", "冗余金额比例", "监控状态", "是否侵权" };

                if (t.Value > 1)
                {
                    listCol = new List<string> { "sku", "产品编码", "sku标题", "产品个数", "在途数", "库存总金额", "昨日销量", "昨日销售金额", "过去3天日均", "过去7天日均", "过去14天日均", "过去30天日均", "日周转率", "周周转率", "月周转率", "缺货数", "监控状态", "是否侵权" };
                }

                var list = new List<string>();

                if (t.Value <= 1)
                {
                    var s = "";
                    foreach (var item in obj)
                    {
                        s = item.bailun_sku + "|" + item.sku_product_code + "|" + item.bailun_sku_name + "|" + item.productcount + "|" + item.onway_count + "|" + item.amount_total + "|" + item.daily_productsale_count + "|" + item.productsale_rate + "|" + item.dailysale_amount + "|" + item.saleamount_rate + "|" + item.redundancy_product_count + "|" + item.redundancy_product_rate + "|" + item.redundancy_amount + "|" + item.redundancy_amount_rate + "|" + (item.monitorstatus == 0 ? "正在监控" : "停止监控") + "|" + (item.tortstatus == 1 ? "已侵权" : "未侵权");
                        list.Add(s);
                    }
                }
                else if (t.Value > 1)
                {
                    var s = "";
                    foreach (var item in obj)
                    {
                        s = item.bailun_sku + "|" + item.sku_product_code + "|" + item.bailun_sku_name + "|" + item.productcount + "|" + item.onway_count + "|" + item.amount_total + "|" + item.yesterdaysale_count + "|" + item.yesterdaysale_amount + "|" + item.sale_3d_avg + "|" + item.sale_7d_avg + "|" + item.sale_14d_avg + "|" + item.sale_30d_avg + "|" + item.day_turnover_rate + "|" + item.week_turnover_rate + "|" + item.month_turnover_rate + "|" + item.stockout + "|" + (item.monitorstatus == 0 ? "正在监控" : "停止监控") + "|" + (item.tortstatus == 1 ? "已侵权" : "未侵权");
                        list.Add(s);
                    }
                }

                var title = "";

                switch (t.Value)
                {
                    case 0:
                        title = "前100冗余金额sku分析";
                        break;
                    case 1:
                        title = "前100冗余个数sku分析";
                        break;
                    case 2:
                        title = "前100个数动销最快sku分析";
                        break;
                    case 3:
                        title = "前100金额动销最快sku分析";
                        break;
                }

                var guid = Guid.NewGuid().ToString();
                var filename = title + " " + DateTime.Now.ToString("yyyyMMddHHmmss");
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(list, listCol, 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");
            }

            return View("");
        }

        /// <summary>
        /// 仓库历史冗余图表展示
        /// </summary>
        /// <returns></returns>
        public ActionResult WHRedundancyChart(string warehousecode, DateTime day, string col, string colname, string warehousename)
        {

            ViewBag.warehousecode = warehousecode;
            ViewBag.day = day.ToString("yyyy-MM-dd");
            ViewBag.col = col;
            ViewBag.colname = colname;
            ViewBag.warehousename = warehousename;
            return View();
        }

        /// <summary>
        /// 获取过去两个月的历史数据
        /// </summary>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="day">结束日期</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult WHRedundancyChartJson(string warehousecode, DateTime day, string col)
        {
            var startDay = day.AddDays(-60);

            var obj = new Services.WareHouseServices().ListOver60DaysWarehouseRedundancy(warehousecode, startDay, day);

            var colname = new List<string>();
            var colval = new List<decimal>();

            for (var i = 0; i < 61; i++)
            {
                var item = obj.Where(a => a.day == startDay.AddDays(i)).FirstOrDefault();
                colname.Add(startDay.AddDays(i).ToString("MM-dd"));

                if (item == null)
                {
                    colval.Add(0);
                }
                else
                {
                    var propertys = item.GetType().GetProperties();
                    foreach (var a in propertys)
                    {
                        if (a.Name == col)
                        {
                            var value = a.GetValue(item, null);
                            try
                            {
                                var b = decimal.Parse(value.ToString());

                                if (a.Name.IndexOf("比例") > 0)
                                {
                                    b *= 100;
                                }

                                colval.Add(b);
                            }
                            catch
                            {
                                colval.Add(0);
                            }

                            break;
                        }
                    }
                }
            }

            return Json(new
            {
                col = colname,
                val = colval
            });
        }

        /// <summary>
        /// SKU 的每日采购和发货情况报表
        /// </summary>
        /// <returns></returns>
        public ActionResult ListDailyPurchaseSales(string categoryname, string colname, int dateWay, int t)
        {
            var start = DateTime.Now.AddDays(-1);
            var end = DateTime.Now.AddDays(-1);

            //获取百伦分类id
            var categoryid = "0";
            if (categoryname != "普货")
            {
                if (categoryname == "原料")
                {
                    categoryid = (-100).ToString();
                }
                else
                {
                    var objCategory = new Services.SkuInfoServices().GetSimpleCategory(categoryname);
                    if (objCategory != null)
                    {
                        categoryid = objCategory.skums_id.ToString();
                    }
                }
            }
            else
            {
                categoryid = "5|6|7|8|9|10|11|12|13|14|15";
            }


            //获取列名上的日期
            if (dateWay == 2) //按周
            {
                var s = colname.Substring(0, 9);
                start = DateTime.Parse(DateTime.Now.Year + "-" + s.Substring(0, 2) + "-" + s.Substring(2, 2));
                end = DateTime.Parse(DateTime.Now.Year + "-" + s.Substring(5, 2) + "-" + s.Substring(7, 2));
            }
            else if (dateWay == 3)  //按月
            {
                var s = colname.Substring(0, 2);
                start = DateTime.Parse(DateTime.Now.Year + "-" + s + "-01");
                end = start.AddMonths(1).AddDays(1);
            }

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            ViewBag.t = t;
            ViewBag.categoryid = categoryid;

            return View();
        }

        /// <summary>
        /// SKU 的每日采购和发货情况报表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListDailyPurchaseSalesJson(BtTableParameter parameter, string warehousetype, string warehouse_code, DateTime start, DateTime end, int t, string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();

            var _service = new Services.WareHouseServices();
            var total = 0;
            var obj = _service.ListDailyPurchaseSale(parameter, warehousetype, warehouse_code, start, end, skucategoryids, 1, ref total);
            var countM = _service.ListDailyPurchaseSaleCount(warehousetype, warehouse_code, start, end, skucategoryids, 1);

            var list = obj.Select(a => new
            {
                day = a.day.ToString("yyyy-MM-dd"),
                //amount_purchase = a.amount_purchase.ToString("N2"),
                //amount_putin = a.amount_putin.ToString("N2"),
                amount_sales = (t == 1 ? a.amount_sales : a.amount_shipping).ToString("N2"),
                a.bailun_sku,

                //a.count_purchase,
                //a.count_putin,
                count_sales = (t == 1 ? a.count_sales : a.count_shipping),

                stockamount_end = a.stockamount_end.ToString("N2"),
                stockamount_start = a.stockamount_start.ToString("N2"),
                a.stock_end,
                a.stock_start,

                a.warehouse_code,
                a.warehouse_name,

                count_purchase = t == 1 ? a.count_purchase : a.count_putin,
                amount_purchase = (t == 1 ? a.amount_purchase : a.amount_putin).ToString("N2"),
                diff_count = t == 1 ? a.difference_count : a.diff_putin_count,
                diff_amount = (t == 1 ? a.difference_amount : a.diff_putin_amount).ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    bailun_sku = "总计",
                    amount_sales = countM.amount_sales.ToString("N2"),
                    countM.count_sales,
                    stockamount_end = countM.stockamount_end.ToString("N2"),
                    stockamount_start = countM.stockamount_start.ToString("N2"),
                    countM.stock_end,
                    countM.stock_start,
                    count_purchase = t == 1 ? countM.count_purchase : countM.count_putin,
                    amount_purchase = (t == 1 ? countM.amount_purchase : countM.amount_putin).ToString("N2"),
                    diff_count = t == 1 ? countM.difference_count : countM.diff_putin_count,
                    diff_amount = (t == 1 ? countM.difference_amount : countM.diff_putin_amount).ToString("N2"),
                },
                companyid
            });

        }

        /// <summary>
        /// 每日采购和发货情况汇总报表
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyPurchaseSalesCount()
        {
            return View();
        }

        public ActionResult ListDailySemiPurchaseSales(string colname, int dateWay, int t)
        {
            var start = DateTime.Now.AddDays(-1);
            var end = DateTime.Now.AddDays(-1);

            //获取列名上的日期
            if (dateWay == 2) //按周
            {
                var s = colname.Substring(0, 9);
                start = DateTime.Parse(DateTime.Now.Year + "-" + s.Substring(0, 2) + "-" + s.Substring(2, 2));
                end = DateTime.Parse(DateTime.Now.Year + "-" + s.Substring(5, 2) + "-" + s.Substring(7, 2));
            }
            else if (dateWay == 3)  //按月
            {
                var s = colname.Substring(0, 2);
                start = DateTime.Parse(DateTime.Now.Year + "-" + s + "-01");
                end = start.AddMonths(1).AddDays(1);
            }

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            ViewBag.t = t;


            return View();
        }

        [BailunAuthentication(LoginMode.Enforce)]
        public string ListDailySemiPurchaseSalesJson(BtTableParameter parameter, DateTime start, DateTime end, int t)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();

            var _service = new Services.WareHouseServices();
            var total = 0;
            var obj = _service.ListDailyPurchaseSale(parameter, "", "", start, end, "", 0, ref total);
            var countM = _service.ListDailyPurchaseSaleCount("", "", start, end, "", 0);

            var list = obj.Select(a => new
            {
                day = a.day.ToString("yyyy-MM-dd"),
                //amount_purchase = a.amount_purchase.ToString("N2"),
                //amount_putin = a.amount_putin.ToString("N2"),
                amount_sales = a.amount_sales.ToString("N2"),
                a.bailun_sku,

                //a.count_purchase,
                //a.count_putin,
                a.count_sales,

                stockamount_end = a.stockamount_end.ToString("N2"),
                stockamount_start = a.stockamount_start.ToString("N2"),
                a.stock_end,
                a.stock_start,

                a.warehouse_code,
                a.warehouse_name,

                count_purchase = t == 1 ? a.count_purchase : a.count_putin,
                amount_purchase = (t == 1 ? a.amount_purchase : a.amount_putin).ToString("N2"),
                diff_count = t == 1 ? a.difference_count : a.diff_putin_count,
                diff_amount = (t == 1 ? a.difference_amount : a.diff_putin_amount).ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    bailun_sku = "总计",
                    amount_sales = countM.amount_sales.ToString("N2"),
                    countM.count_sales,
                    stockamount_end = countM.stockamount_end.ToString("N2"),
                    stockamount_start = countM.stockamount_start.ToString("N2"),
                    countM.stock_end,
                    countM.stock_start,
                    count_purchase = t == 1 ? countM.count_purchase : countM.count_putin,
                    amount_purchase = (t == 1 ? countM.amount_purchase : countM.amount_putin).ToString("N2"),
                    diff_count = t == 1 ? countM.difference_count : countM.diff_putin_count,
                    diff_amount = (t == 1 ? countM.difference_amount : countM.diff_putin_amount).ToString("N2"),
                },
                companyid
            });
        }


        /// <summary>
        /// 按sku分类汇总每日销进差异报表
        /// </summary>
        /// <param name="type">1、按日，2、按周，3、按月</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="t">1：按采购下单，2：按入库</param>
        /// <returns></returns>
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【每日销进差异汇总】->【查询】页面", 0)]
        public JsonResult DailyPurchaseSalesCountJson(int dateWay, DateTime start, DateTime end, string warehousetype, string warehousecode, int t)
        {
            var list = new List<mDailyPurchaseSales>();
            var _service = new Services.WareHouseServices();
            var obj = _service.DailyPurchaseSaleBySkuCategory(warehousetype, warehousecode, start, end).OrderBy(a => a.day).ToList();

            foreach (var item in obj)
            {
                if (item.category_simple_name.Contains("普货"))
                {
                    item.category_simple_name = "普货";
                }
            }

            //Add by Allan at 201908261750 for 增加原料的统计
            var objSemi = _service.DailyPurchaseSaleBySkuCategory_Semi(warehousetype, warehousecode, start, end).OrderBy(a => a.day).ToList();
            obj.AddRange(objSemi);
            //End Add

            //Add by Allan at 201911041434 for 把原料再分类
            var objSemiCategory = _service.DailyPurchaseSaleByWH_Semi(start, end);
            //End Add

            if (obj.Count == 0)
            {
                return Json(new
                {
                    success = true,
                    list = list,
                    msg = ""
                });
            }

            #region 采购和发货情况 Add by Allan at 20191104


            var listSubCount1 = new List<Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>>();
            var listSubCount2 = new List<Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>>();
            var semi_E_Oil = objSemiCategory.Where(a => a.category_simple_name == "精油灌装车间" || a.category_simple_name == "精油生产车间").ToList(); //精油原料
            var semi_Hairdressing = objSemiCategory.Where(a => a.category_simple_name == "美容组装车间" || a.category_simple_name == "美容生产车间").ToList();//美容原料
            var semi_Manicure = objSemiCategory.Where(a => a.category_simple_name == "阳山美甲灌装车间" || a.category_simple_name == "嘉禾美甲灌装车间" || a.category_simple_name == "哈倪蔓美甲灌装车间").ToList();//美甲原料
            var semi_HNM = objSemiCategory.Where(a => a.category_simple_name == "甲油胶生产车间").ToList();//哈倪曼基料

            var finish_Gen = obj.Where(a => a.category_simple_name.Contains("普货")).ToList();  //普货
            var finish_Manicure = obj.Where(a => a.category_simple_name == "美甲").ToList(); //美甲生产
            var finish_E_Oil = obj.Where(a => a.category_simple_name == "精油").ToList();    //精油生产
            var finish_Hairdressing = obj.Where(a => a.category_simple_name == "美容").ToList();  //美容生产


            if (semi_E_Oil.Count > 0)
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("精油原料", semi_E_Oil.Sum(a => a.amount_purchase), semi_E_Oil.Sum(a => a.count_purchase), semi_E_Oil.Sum(a => a.amount_shipping), semi_E_Oil.Sum(a => a.count_shipping), (semi_E_Oil.Sum(a => a.amount_shipping) - semi_E_Oil.Sum(a => a.amount_purchase)), (semi_E_Oil.Sum(a => a.count_shipping) - semi_E_Oil.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("精油原料", 0, 0, 0, 0, 0, 0));
            }

            if (semi_Hairdressing.Count > 0)
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美容原料", semi_Hairdressing.Sum(a => a.amount_purchase), semi_Hairdressing.Sum(a => a.count_purchase), semi_Hairdressing.Sum(a => a.amount_shipping), semi_Hairdressing.Sum(a => a.count_shipping), (semi_Hairdressing.Sum(a => a.amount_shipping) - semi_Hairdressing.Sum(a => a.amount_purchase)), (semi_Hairdressing.Sum(a => a.count_shipping) - semi_Hairdressing.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美容原料", 0, 0, 0, 0, 0, 0));
            }

            if (semi_Manicure.Count > 0)
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美甲原料", semi_Manicure.Sum(a => a.amount_purchase), semi_Manicure.Sum(a => a.count_purchase), semi_Manicure.Sum(a => a.amount_shipping), semi_Manicure.Sum(a => a.count_shipping), (semi_Manicure.Sum(a => a.amount_shipping) - semi_Manicure.Sum(a => a.amount_purchase)), (semi_Manicure.Sum(a => a.count_shipping) - semi_Manicure.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美甲原料", 0, 0, 0, 0, 0, 0));
            }

            if (semi_HNM.Count > 0)
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("哈倪蔓基料", semi_HNM.Sum(a => a.amount_purchase), semi_HNM.Sum(a => a.count_purchase), semi_HNM.Sum(a => a.amount_shipping), semi_HNM.Sum(a => a.count_shipping), (semi_HNM.Sum(a => a.amount_shipping) - semi_HNM.Sum(a => a.amount_purchase)), (semi_HNM.Sum(a => a.count_shipping) - semi_HNM.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("哈倪蔓基料", 0, 0, 0, 0, 0, 0));
            }


            if (finish_Gen.Count > 0)
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("普货", finish_Gen.Sum(a => a.amount_purchase), finish_Gen.Sum(a => a.count_purchase), finish_Gen.Sum(a => a.amount_shipping), finish_Gen.Sum(a => a.count_shipping), (finish_Gen.Sum(a => a.amount_shipping) - finish_Gen.Sum(a => a.amount_purchase)), (finish_Gen.Sum(a => a.count_shipping) - finish_Gen.Sum(a => a.count_purchase))));

            }
            else
            {
                listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("普货", 0, 0, 0, 0, 0, 0));

            }

            if (finish_Manicure.Count > 0)
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美甲生产", finish_Manicure.Sum(a => a.amount_purchase), finish_Manicure.Sum(a => a.count_purchase), finish_Manicure.Sum(a => a.amount_shipping), finish_Manicure.Sum(a => a.count_shipping), (finish_Manicure.Sum(a => a.amount_shipping) - finish_Manicure.Sum(a => a.amount_purchase)), (finish_Manicure.Sum(a => a.count_shipping) - finish_Manicure.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美甲生产", 0, 0, 0, 0, 0, 0));
            }

            if (finish_E_Oil.Count > 0)
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("精油生产", finish_E_Oil.Sum(a => a.amount_purchase), finish_E_Oil.Sum(a => a.count_purchase), finish_E_Oil.Sum(a => a.amount_shipping), finish_E_Oil.Sum(a => a.count_shipping), (finish_E_Oil.Sum(a => a.amount_shipping) - finish_E_Oil.Sum(a => a.amount_purchase)), (finish_E_Oil.Sum(a => a.count_shipping) - finish_E_Oil.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("精油生产", 0, 0, 0, 0, 0, 0));
            }

            if (finish_Hairdressing.Count > 0)
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美容生产", finish_Hairdressing.Sum(a => a.amount_purchase), finish_Hairdressing.Sum(a => a.count_purchase), finish_Hairdressing.Sum(a => a.amount_shipping), finish_Hairdressing.Sum(a => a.count_shipping), (finish_Hairdressing.Sum(a => a.amount_shipping) - finish_Hairdressing.Sum(a => a.amount_purchase)), (finish_Hairdressing.Sum(a => a.count_shipping) - finish_Hairdressing.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("美容生产", 0, 0, 0, 0, 0, 0));
            }

            if (finish_Gen.Count > 0)
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("普货", finish_Gen.Sum(a => a.amount_purchase), finish_Gen.Sum(a => a.count_purchase), finish_Gen.Sum(a => a.amount_shipping), finish_Gen.Sum(a => a.count_shipping), (finish_Gen.Sum(a => a.amount_shipping) - finish_Gen.Sum(a => a.amount_purchase)), (finish_Gen.Sum(a => a.count_shipping) - finish_Gen.Sum(a => a.count_purchase))));
            }
            else
            {
                listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("普货", 0, 0, 0, 0, 0, 0));
            }

            #endregion

            if (dateWay == 2)   //按周
            {
                var first = obj.FirstOrDefault();
                var DayOfWeek = first.day.DayOfWeek;

                var startDay = first.day;
                var endDay = first.day.AddDays((7 - (int)DayOfWeek));
                var weekIndex = 0;

                foreach (var item in obj)
                {
                    if (item.day > endDay)
                    {
                        weekIndex++;
                        startDay = endDay.AddDays(1);
                        endDay = endDay.AddDays(7);
                    }

                    var m = list.Where(a => a.dayStart >= item.day && item.day <= a.dayEnd && a.category_simple_name == item.category_simple_name).FirstOrDefault();
                    if (m == null)
                    {
                        m = new mDailyPurchaseSales
                        {
                            dayStart = startDay,
                            dayEnd = endDay,
                            category_simple_name = item.category_simple_name,


                            amount_purchase = item.amount_purchase,
                            amount_putin = item.amount_putin,
                            amount_sales = item.amount_sales,
                            amount_shipping = item.amount_shipping,

                            count_purchase = item.count_purchase,
                            count_putin = item.count_putin,
                            count_sales = item.count_sales,
                            count_shipping = item.count_shipping,
                        };

                        list.Add(m);
                    }
                    else
                    {
                        m.amount_purchase += item.amount_purchase;
                        m.amount_putin += item.amount_putin;
                        m.amount_sales += item.amount_sales;
                        m.amount_shipping += item.amount_shipping;

                        m.count_purchase += item.count_purchase;
                        m.count_putin += item.count_putin;
                        m.count_sales += item.count_sales;
                        m.count_shipping += item.count_shipping;
                    }
                }

                foreach (var item in list)
                {
                    item.day = item.dayStart.ToString("MMdd") + "-" + (item.dayEnd > end ? end : item.dayEnd).ToString("MMdd");
                    item.difference_amount = item.amount_purchase - item.amount_sales;
                    item.difference_count = item.count_purchase - item.count_sales;

                    item.diff_putin_amount = item.amount_putin - item.amount_shipping;
                    item.diff_putin_count = item.count_putin - item.count_shipping;
                }
            }
            else if (dateWay == 3)  //按月
            {
                foreach (var item in obj)
                {
                    var m = list.Where(a => a.day == item.day.ToString("MM") && a.category_simple_name == item.category_simple_name).FirstOrDefault();
                    if (m == null)
                    {
                        m = new mDailyPurchaseSales
                        {
                            day = item.day.ToString("MM"),
                            category_simple_name = item.category_simple_name,


                            amount_purchase = item.amount_purchase,
                            amount_putin = item.amount_putin,
                            amount_sales = item.amount_sales,
                            amount_shipping = item.amount_shipping,

                            count_purchase = item.count_purchase,
                            count_putin = item.count_putin,
                            count_sales = item.count_sales,
                            count_shipping = item.count_shipping,
                        };

                        list.Add(m);
                    }
                    else
                    {
                        m.amount_purchase += item.amount_purchase;
                        m.amount_putin += item.amount_putin;
                        m.amount_sales += item.amount_sales;
                        m.amount_shipping += item.amount_shipping;

                        m.count_purchase += item.count_purchase;
                        m.count_putin += item.count_putin;
                        m.count_sales += item.count_sales;
                        m.count_shipping += item.count_shipping;
                    }
                }

                foreach (var item in list)
                {
                    item.difference_amount = item.amount_purchase - item.amount_sales;
                    item.difference_count = item.count_purchase - item.count_sales;

                    item.diff_putin_amount = item.amount_putin - item.amount_shipping;
                    item.diff_putin_count = item.count_putin - item.count_shipping;
                }
            }
            else   //每日
            {
                list = obj.Select(a => new mDailyPurchaseSales
                {
                    day = a.day.ToString("MM-dd"),
                    amount_purchase = a.amount_purchase,
                    amount_putin = a.amount_putin,
                    amount_sales = a.amount_sales,
                    amount_shipping = a.amount_shipping,

                    count_purchase = a.count_purchase,
                    count_putin = a.count_putin,
                    count_sales = a.count_sales,
                    count_shipping = a.count_shipping,

                    difference_amount = a.amount_purchase - a.amount_sales,
                    difference_count = a.count_purchase - a.count_sales,
                    diff_putin_amount = a.amount_putin - a.amount_shipping,
                    diff_putin_count = a.count_putin - a.count_shipping,


                    category_simple_name = a.category_simple_name,
                }).ToList();
            }

            //格式化
            var head = new List<string>() { "Sku分类" };
            var data = new List<SkuCategory_Col>();

            foreach (var item in list)
            {
                var objSC = data.Where(a => a.category_simple_name == item.category_simple_name).FirstOrDefault();
                if (objSC == null)
                {
                    objSC = new SkuCategory_Col
                    {
                        category_simple_name = item.category_simple_name,
                        list = new List<string> { },
                        days = new List<string> { }
                    };

                    //objSC.list.Add(item.day);
                    objSC.days.Add(item.day);
                    objSC.list.Add((t == 1 ? item.amount_purchase : item.amount_putin).ToString());
                    objSC.list.Add((t == 1 ? item.count_purchase : item.count_putin).ToString());
                    objSC.list.Add((t == 1 ? item.amount_sales : item.amount_shipping).ToString());
                    objSC.list.Add((t == 1 ? item.count_sales : item.count_shipping).ToString());
                    objSC.list.Add((t == 1 ? (item.amount_purchase - item.amount_sales) : (item.amount_putin - item.amount_shipping)).ToString());
                    objSC.list.Add((t == 1 ? (item.count_purchase - item.count_sales) : (item.count_putin - item.count_shipping)).ToString());

                    data.Add(objSC);
                    if (head.Where(a => a.Contains(item.day)).Count() <= 0)
                    {
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "采购下单金额" : "入库金额"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "采购下单数" : "入库数"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "销售金额" : "发货金额"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "销售数量" : "发货数量"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + "差异金额");
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + "差异数量");
                    }
                }
                else
                {
                    //objSC.list.Add(item.day);
                    //objSC.list.Add((t == 1 ? item.amount_purchase : item.amount_putin).ToString());
                    //objSC.list.Add((t == 1 ? item.count_purchase : item.count_putin).ToString());
                    //objSC.list.Add((t == 1 ? item.amount_sales : item.amount_shipping).ToString());
                    //objSC.list.Add((t == 1 ? item.count_sales : item.count_shipping).ToString());

                    if (!objSC.days.Contains(item.day))
                    {
                        objSC.days.Add(item.day);
                        objSC.list.Add((t == 1 ? item.amount_purchase : item.amount_putin).ToString());
                        objSC.list.Add((t == 1 ? item.count_purchase : item.count_putin).ToString());
                        objSC.list.Add((t == 1 ? item.amount_sales : item.amount_shipping).ToString());
                        objSC.list.Add((t == 1 ? item.count_sales : item.count_shipping).ToString());
                        objSC.list.Add((t == 1 ? (item.amount_purchase - item.amount_sales) : (item.amount_putin - item.amount_shipping)).ToString());
                        objSC.list.Add((t == 1 ? (item.count_purchase - item.count_sales) : (item.count_putin - item.count_shipping)).ToString());
                    }
                    else
                    {
                        objSC.list[objSC.list.Count - 6] = (decimal.Parse(objSC.list[objSC.list.Count - 6]) + ((t == 1 ? item.amount_purchase : item.amount_putin))).ToString("G0");
                        objSC.list[objSC.list.Count - 5] = (decimal.Parse(objSC.list[objSC.list.Count - 5]) + (t == 1 ? item.count_purchase : item.count_putin)).ToString("G0");
                        objSC.list[objSC.list.Count - 4] = (decimal.Parse(objSC.list[objSC.list.Count - 4]) + (t == 1 ? item.amount_sales : item.amount_shipping)).ToString("G0");
                        objSC.list[objSC.list.Count - 3] = (decimal.Parse(objSC.list[objSC.list.Count - 3]) + (t == 1 ? item.count_sales : item.count_shipping)).ToString("G0");
                        objSC.list[objSC.list.Count - 2] = (decimal.Parse(objSC.list[objSC.list.Count - 2]) + (t == 1 ? (item.amount_purchase - item.amount_sales) : (item.amount_putin - item.amount_shipping))).ToString("G0");
                        objSC.list[objSC.list.Count - 1] = (decimal.Parse(objSC.list[objSC.list.Count - 1]) + (t == 1 ? (item.count_purchase - item.count_sales) : (item.count_putin - item.count_shipping))).ToString("G0");
                    }


                    if (head.Where(a => a.Contains(item.day)).Count() <= 0)
                    {
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "采购下单金额" : "入库金额"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "采购下单数" : "入库数"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "销售金额" : "发货金额"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + (t == 1 ? "销售数量" : "发货数量"));
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + "差异金额");
                        head.Add(item.day + (dateWay == 3 ? "月" : "") + "差异数量");
                    }

                }
            }

            if (data.Count > 0)
            {
                var m = new SkuCategory_Col
                {
                    category_simple_name = "总计",
                    list = new List<string>()
                };

                var mdefault = new SkuCategory_Col
                {
                    category_simple_name = "普货",
                    list = new List<string>(),
                };

                var newData = data.Where(a => !a.category_simple_name.Contains("普货")).ToList();

                foreach (var item in data)
                {
                    for (var i = 0; i < item.list.Count; i++)
                    {
                        if (m.list.Count > i)
                        {
                            m.list[i] = (decimal.Parse(m.list[i]) + decimal.Parse(item.list[i])).ToString();
                        }
                        else
                        {
                            m.list.Add(item.list[i]);
                        }
                    }

                    if (item.category_simple_name.Contains("普货"))
                    {
                        for (var i = 0; i < item.list.Count; i++)
                        {
                            if (mdefault.list.Count > i)
                            {
                                mdefault.list[i] = (decimal.Parse(mdefault.list[i]) + decimal.Parse(item.list[i])).ToString();
                            }
                            else
                            {
                                mdefault.list.Add(item.list[i]);
                            }
                        }
                    }
                }

                newData.Add(mdefault);
                newData.Add(m);


                data = newData;
            }

            var countHead = new List<string>() { "Sku分类" };
            countHead.Add((t == 1 ? "总采购下单金额" : "总入库金额"));
            countHead.Add((t == 1 ? "总采购下单数" : "总入库数"));
            countHead.Add((t == 1 ? "总销售金额" : "总发货金额"));
            countHead.Add((t == 1 ? "总销售数量" : "总发货数量"));
            countHead.Add("总差异金额");
            countHead.Add("总差异数量");

            var countData = new List<SkuCategory_Col>();
            var c_val1 = 0M;
            var c_val2 = 0;
            var c_val3 = 0M;
            var c_val4 = 0;
            var c_val5 = 0M;
            var c_val6 = 0;

            foreach (var item in data)
            {
                var objCount = obj.Where(a => a.category_simple_name == item.category_simple_name);

                if (item.category_simple_name == "普货")
                {
                    objCount = obj.Where(a => a.category_simple_name.Contains(item.category_simple_name));
                }

                var val_1 = (t == 1 ? objCount.Sum(a => a.amount_purchase) : objCount.Sum(a => a.amount_putin));
                var val_2 = (t == 1 ? objCount.Sum(a => a.count_purchase) : objCount.Sum(a => a.count_putin));
                var val_3 = (t == 1 ? objCount.Sum(a => a.amount_sales) : objCount.Sum(a => a.amount_shipping));
                var val_4 = (t == 1 ? objCount.Sum(a => a.count_sales) : objCount.Sum(a => a.count_shipping));

                var val_5 = (t == 1 ? objCount.Sum(a => a.amount_purchase - a.amount_sales) : objCount.Sum(a => a.amount_putin - a.amount_shipping));
                var val_6 = (t == 1 ? objCount.Sum(a => a.count_purchase - a.count_sales) : objCount.Sum(a => a.count_putin - a.count_shipping));

                if (item.category_simple_name != "总计")
                {
                    c_val1 += val_1;
                    c_val2 += val_2;
                    c_val3 += val_3;
                    c_val4 += val_4;
                    c_val5 += val_5;
                    c_val6 += val_6;
                }
                else
                {
                    val_1 = c_val1;
                    val_2 = c_val2;
                    val_3 = c_val3;
                    val_4 = c_val4;
                    val_5 = c_val5;
                    val_6 = c_val6;
                }

                countData.Add(new SkuCategory_Col
                {
                    category_simple_name = item.category_simple_name,
                    list = new List<string> { val_1.ToString(), val_2.ToString(), val_3.ToString(), val_4.ToString(), val_5.ToString(), val_6.ToString() }
                });
            }

            listSubCount1.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("合计", listSubCount1.Sum(a => a.Item2), listSubCount1.Sum(a => a.Item3), listSubCount1.Sum(a => a.Item4), listSubCount1.Sum(a => a.Item5), listSubCount1.Sum(a => a.Item6), listSubCount1.Sum(a => a.Item7)));
            listSubCount2.Add(new Tuple<string, decimal, decimal, decimal, decimal, decimal, decimal>("合计", listSubCount2.Sum(a => a.Item2), listSubCount2.Sum(a => a.Item3), listSubCount2.Sum(a => a.Item4), listSubCount2.Sum(a => a.Item5), listSubCount2.Sum(a => a.Item6), listSubCount2.Sum(a => a.Item7)));

            return Json(new
            {
                success = true,
                list = list,
                msg = "",
                head = head,
                data = data,
                counthead = countHead,
                countdata = countData,
                subcount = listSubCount1.Select(a => new
                {
                    a.Item1,
                    a.Item2,
                    a.Item3,
                    a.Item4,
                    a.Item5,
                    a.Item6,
                    a.Item7
                }),
                subcount1 = listSubCount2
            });
        }

        #region 利润

        /// <summary>
        /// 仓库利润报表
        /// </summary>
        /// <returns></returns>
        public ActionResult ListWarehouseProfit()
        {

            return View();
        }

        /// <summary>
        /// 仓库利润报表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="warehousecode"></param>
        /// <param name="skucategoryids"></param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【利润统计】->【仓库利润统计】->【查询】页面", 0)]
        public string ListWarehouseProfitJson(BtTableParameter parameter, string warehousecode, string skucategoryids)
        {
            var total = 0;
            var obj = new Services.WareHouseServices().ListWarehouseProfit(parameter, skucategoryids, warehousecode, ref total);
            var countObj = new Services.WareHouseServices().ListWarehouseProfitCount(skucategoryids, warehousecode);

            var list = obj.Select(a => new
            {
                a.warehouse_code,
                a.warehouse_name,
                pre30_grossprofit = a.pre30_grossprofit.ToString("N2"),
                pre30_grossprofit_rate = (a.pre30_grossprofit_rate * 100).ToString("N2"),
                pre30_return_rate = a.pre30_return_rate,
                pre30_sales_amount = a.pre30_sales_amount.ToString("N2"),
                pre30_sales_count = a.pre30_sales_count.ToString("N0"),
                pre30_stockamount = a.pre30_stockamount.ToString("N2"),
                pre30_stockamount_add = a.pre30_stockamount_add.ToString("N2"),
                pre30_stockamount_turn_rate = (a.pre30_stockamount_turn_rate * 100).ToString("N2"),
                pre30_stockamount_vendibility_day = a.pre30_stockamount_vendibility_day.ToString("N2"),
                pre30_stockamount__rate = (a.pre30_stockamount__rate * 100).ToString("N2"),
                pre30_stocknum_rate = (a.pre30_stocknum_rate * 100).ToString("N2"),
                pre30_stocknum_turn_rate = (a.pre30_stocknum_turn_rate * 100).ToString("N2"),
                pre30_stocknum_vendibility_day = (a.pre30_stocknum_vendibility_day).ToString("N2"),
                pre30_stock_add_count = a.pre30_stock_add_count.ToString("N0"),


                quantity_purchase = a.quantity_purchase.ToString("N0"),
                quantity_purchase_amount = a.quantity_purchase_amount.ToString("N2"),
                quantity_transfer = a.quantity_transfer.ToString("N0"),
                quantity_transfer_amount = (a.quantity_transfer_amount * 100).ToString("N2"),
                usable_stock = a.usable_stock.ToString("N0"),
                usable_stock_amount = (a.usable_stock_amount).ToString("N2"),
                yd_grossprofit = (a.yd_grossprofit).ToString("N2"),
                yd_grossprofit_rate = (a.yd_grossprofit_rate * 100).ToString("N2"),
                yd_sales_amount = a.yd_sales_amount.ToString("N2"),
                yd_sales_count = a.yd_sales_count.ToString("N0"),
                yd_sales_stockamount = a.yd_sales_stockamount.ToString("N2"),

            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    warehouse_name = "合计",
                    pre30_grossprofit = countObj.pre30_grossprofit.ToString("N2"),
                    pre30_grossprofit_rate = (countObj.pre30_grossprofit_rate * 100).ToString("N2"),
                    pre30_return_rate = countObj.pre30_return_rate,
                    pre30_sales_amount = countObj.pre30_sales_amount.ToString("N2"),
                    pre30_sales_count = countObj.pre30_sales_count.ToString("N0"),
                    pre30_stockamount = countObj.pre30_stockamount.ToString("N2"),
                    pre30_stockamount_add = countObj.pre30_stockamount_add.ToString("N2"),
                    pre30_stockamount_turn_rate = (countObj.pre30_stockamount_turn_rate * 100).ToString("N2"),
                    pre30_stockamount_vendibility_day = countObj.pre30_stockamount_vendibility_day.ToString("N2"),
                    pre30_stockamount__rate = (countObj.pre30_stockamount__rate * 100).ToString("N2"),
                    pre30_stocknum_rate = (countObj.pre30_stocknum_rate * 100).ToString("N2"),
                    pre30_stocknum_turn_rate = (countObj.pre30_stocknum_turn_rate * 100).ToString("N2"),
                    pre30_stocknum_vendibility_day = (countObj.pre30_stocknum_vendibility_day).ToString("N2"),
                    pre30_stock_add_count = countObj.pre30_stock_add_count.ToString("N0"),


                    quantity_purchase = countObj.quantity_purchase.ToString("N0"),
                    quantity_purchase_amount = countObj.quantity_purchase_amount.ToString("N2"),
                    quantity_transfer = countObj.quantity_transfer.ToString("N0"),
                    quantity_transfer_amount = (countObj.quantity_transfer_amount * 100).ToString("N2"),
                    usable_stock = countObj.usable_stock.ToString("N0"),
                    usable_stock_amount = (countObj.usable_stock_amount).ToString("N2"),
                    yd_grossprofit = (countObj.yd_grossprofit).ToString("N2"),
                    yd_grossprofit_rate = (countObj.yd_grossprofit_rate * 100).ToString("N2"),
                    yd_sales_amount = countObj.yd_sales_amount.ToString("N2"),
                    yd_sales_count = countObj.yd_sales_count.ToString("N0"),
                    yd_sales_stockamount = countObj.yd_sales_stockamount.ToString("N2"),
                }
            });
        }


        /// <summary>
        /// sku利润报表
        /// </summary>
        /// <returns></returns>
        public ActionResult ListSkuProfit()
        {
            return View();
        }

        /// <summary>
        /// sku利润报表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="warehousecode"></param>
        /// <param name="skucategoryids"></param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【利润统计】->【sku利润统计】->【查询】页面", 0)]
        public string ListSkuProfitJson(BtTableParameter parameter, string warehousecode, string skucategoryids)
        {
            var total = 0;
            var obj = new Services.WareHouseServices().ListSkuProfit(parameter, skucategoryids, warehousecode, ref total);
            var countObj = new Services.WareHouseServices().ListWarehouseProfitCount(skucategoryids, warehousecode);

            var list = obj.Select(a => new
            {
                a.warehouse_code,
                a.warehouse_name,
                a.bailun_sku,
                a.category_name,
                pre30_grossprofit = a.pre30_grossprofit.ToString("N2"),
                pre30_grossprofit_rate = (a.pre30_grossprofit_rate * 100).ToString("N2"),
                pre30_return_rate = a.pre30_return_rate,
                pre30_sales_amount = a.pre30_sales_amount.ToString("N2"),
                pre30_sales_count = a.pre30_sales_count.ToString("N0"),
                pre30_stockamount = a.pre30_stockamount.ToString("N2"),
                pre30_stockamount_add = a.pre30_stockamount_add.ToString("N2"),
                pre30_stockamount_turn_rate = (a.pre30_stockamount_turn_rate * 100).ToString("N2"),
                pre30_stockamount_vendibility_day = a.pre30_stockamount_vendibility_day.ToString("N2"),
                pre30_stockamount__rate = (a.pre30_stockamount__rate * 100).ToString("N2"),
                pre30_stocknum_rate = (a.pre30_stocknum_rate * 100).ToString("N2"),
                pre30_stocknum_turn_rate = (a.pre30_stocknum_turn_rate * 100).ToString("N2"),
                pre30_stocknum_vendibility_day = (a.pre30_stocknum_vendibility_day).ToString("N2"),
                pre30_stock_add_count = a.pre30_stock_add_count.ToString("N0"),


                quantity_purchase = a.quantity_purchase.ToString("N0"),
                quantity_purchase_amount = a.quantity_purchase_amount.ToString("N2"),
                quantity_transfer = a.quantity_transfer.ToString("N0"),
                quantity_transfer_amount = (a.quantity_transfer_amount).ToString("N2"),
                usable_stock = a.usable_stock.ToString("N0"),
                usable_stock_amount = (a.usable_stock_amount).ToString("N2"),
                yd_grossprofit = (a.yd_grossprofit).ToString("N2"),
                yd_grossprofit_rate = (a.yd_grossprofit_rate * 100).ToString("N2"),
                yd_sales_amount = a.yd_sales_amount.ToString("N2"),
                yd_sales_count = a.yd_sales_count.ToString("N0"),
                yd_sales_stockamount = a.yd_sales_stockamount.ToString("N2"),

            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    warehouse_name = "合计",
                    pre30_grossprofit = countObj.pre30_grossprofit.ToString("N2"),
                    pre30_grossprofit_rate = (countObj.pre30_grossprofit_rate * 100).ToString("N2"),
                    pre30_return_rate = countObj.pre30_return_rate,
                    pre30_sales_amount = countObj.pre30_sales_amount.ToString("N2"),
                    pre30_sales_count = countObj.pre30_sales_count.ToString("N0"),
                    pre30_stockamount = countObj.pre30_stockamount.ToString("N2"),
                    pre30_stockamount_add = countObj.pre30_stockamount_add.ToString("N2"),
                    pre30_stockamount_turn_rate = (countObj.pre30_stockamount_turn_rate * 100).ToString("N2"),
                    pre30_stockamount_vendibility_day = countObj.pre30_stockamount_vendibility_day.ToString("N2"),
                    pre30_stockamount__rate = (countObj.pre30_stockamount__rate * 100).ToString("N2"),
                    pre30_stocknum_rate = (countObj.pre30_stocknum_rate * 100).ToString("N2"),
                    pre30_stocknum_turn_rate = (countObj.pre30_stocknum_turn_rate * 100).ToString("N2"),
                    pre30_stocknum_vendibility_day = (countObj.pre30_stocknum_vendibility_day).ToString("N2"),
                    pre30_stock_add_count = countObj.pre30_stock_add_count.ToString("N0"),


                    quantity_purchase = countObj.quantity_purchase.ToString("N0"),
                    quantity_purchase_amount = countObj.quantity_purchase_amount.ToString("N2"),
                    quantity_transfer = countObj.quantity_transfer.ToString("N0"),
                    quantity_transfer_amount = (countObj.quantity_transfer_amount).ToString("N2"),
                    usable_stock = countObj.usable_stock.ToString("N0"),
                    usable_stock_amount = (countObj.usable_stock_amount).ToString("N2"),
                    yd_grossprofit = (countObj.yd_grossprofit).ToString("N2"),
                    yd_grossprofit_rate = (countObj.yd_grossprofit_rate * 100).ToString("N2"),
                    yd_sales_amount = countObj.yd_sales_amount.ToString("N2"),
                    yd_sales_count = countObj.yd_sales_count.ToString("N0"),
                    yd_sales_stockamount = countObj.yd_sales_stockamount.ToString("N2"),
                }
            });
        }

        #endregion

        /// <summary>
        /// 半成品仓库列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SemiWarehouse()
        {
            var obj = new Services.WareHouseServices().ListSemiWareHouse();

            var list = obj.Select(a => new
            {
                warehouse_code = a.Item1,
                warehouse_name = a.Item2
            });

            return Json(list);

        }

        /// <summary>
        /// 动态库存分析
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        public ActionResult DynamicStockAnalyse(string warehouse_code, string warehouse_name)
        {
            ViewBag.warehouse_code = warehouse_code;
            ViewBag.warehouse_name = warehouse_name;
            return View();
        }

        /// <summary>
        /// 动态库存分析Json
        /// </summary>
        /// <param name="warehouse_code">仓库编码</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DynamicStockAnalyseJson(string warehouse_code)
        {
            //区分半成品仓和成品仓

            int code = 0;
            int.TryParse(warehouse_code, out code);

            var obj = new Models.Warehouse.mDynamicStockAnalyse();
            var _service = new Services.WareHouseServices();

            if (code > 0) //半成品仓
            {
                obj = _service.ListDynamicStockAnalyse(warehouse_code, 0).FirstOrDefault();
            }
            else
            {
                //成品仓
                obj = _service.ListDynamicStockAnalyse(warehouse_code, 1).FirstOrDefault();
            }

            //组装数据并输出

            var list = new List<Tuple<string, string, string, string, string>>();

            if (obj != null)
            {
                list.Add(new Tuple<string, string, string, string, string>("可销售天数少于15天", obj.less15days_skucount.ToString("N0"), obj.less15days.ToString("N0"), obj.less15days_amount.ToString("N2"), "-15"));
                list.Add(new Tuple<string, string, string, string, string>("可销售天数15-30天", obj.fifteen_30_days_skucount.ToString("N0"), obj.fifteen_30_days.ToString("N0"), obj.fifteen_30_days_amount.ToString("N2"), "15-30"));
                list.Add(new Tuple<string, string, string, string, string>("可销售天数30-45天", obj.thirty_45_days_skucount.ToString("N0"), obj.thirty_45_days.ToString("N0"), obj.thirty_45_days_amount.ToString("N2"), "30-45"));
                list.Add(new Tuple<string, string, string, string, string>("可销售天数45-60天", obj.fortyfive_60_days_skucount.ToString("N0"), obj.fortyfive_60_days.ToString("N0"), obj.fortyfive_60_days_amount.ToString("N2"), "45-60"));
                list.Add(new Tuple<string, string, string, string, string>("可销售天数60-90天", obj.sixty_90_days_skucount.ToString("N0"), obj.sixty_90_days.ToString("N0"), obj.sixty_90_days_amount.ToString("N2"), "60-90"));
                list.Add(new Tuple<string, string, string, string, string>("可销售天数90-120天", obj.ninty_120_days_skucount.ToString("N0"), obj.ninty_120_days.ToString("N0"), obj.ninty_120_days_amount.ToString("N2"), "90-120"));
                list.Add(new Tuple<string, string, string, string, string>("可销售天数120-180天", obj.onetwozero_180_days_skucount.ToString("N0"), obj.onetwozero_180_days.ToString("N0"), obj.onetwozero_180_days_amount.ToString("N2"), "120-180"));
                list.Add(new Tuple<string, string, string, string, string>("可销售天数180天以上", obj.morethen_180_days_skucount.ToString("N0"), obj.morethen_180_days.ToString("N0"), obj.morethen_180_days_amount.ToString("N2"), "180-"));
            }

            return Json(new
            {
                success = true,
                msg = "",
                data = list
            });

        }

        /// <summary>
        /// 逻辑仓仓库的字段趋势图
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public ActionResult WarehouseTrendChart(string warehouse_code, string key, string titlename,string category)
        {
            ViewBag.warehouse_code = warehouse_code;
            ViewBag.key = key;
            ViewBag.titlename = titlename;

            ViewBag.start = DateTime.Now.AddDays(-31).ToString("yyyy-MM-dd");
            ViewBag.end = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");

            ViewBag.category = category;

            return View();
        }

        /// <summary>
        /// 逻辑仓仓库的字段趋势图
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult WarehouseTrendChartJson(string warehouse_code, string key, DateTime start, DateTime end,string category)
        {
            var obj = new List<string>();

            if (string.IsNullOrEmpty(warehouse_code))
            {
                obj = new Services.WareHouseServices().GetMidLogicWarehouseStatisticCount(key, start, end,category);
            }
            else
            {
                obj = new Services.WareHouseServices().GetMidLogicWarehouseStatistic(warehouse_code, key, start, end,category);
            }



            var listval = new List<string>();
            var listdate = new List<string>();

            obj = obj.Where(a => !string.IsNullOrEmpty(a)).ToList();

            if (obj.Count > 0)
            {
                foreach (var item in obj)
                {
                    var arr = item.Split(',');
                    if (arr.Length > 1)
                    {
                        if (key.Trim() == "pin_rate_stock")
                        {
                            listval.Add(decimal.Parse(arr[0]).ToString("N2"));
                        }
                        else
                        {
                            listval.Add(arr[0]);
                        }
                        listdate.Add(DateTime.Parse(arr[1]).ToString("yyyy-MM-dd"));
                    }
                }
            }

            return Json(new
            {
                success = true,
                msg = "",
                val = listval,
                dates = listdate,
            });
        }

        #region 库存汇总分析

        /// <summary>
        /// 库存汇总分析
        /// </summary>
        /// <returns></returns>
        public ActionResult InventorySummary()
        {
            return View();
        }

        /// <summary>
        /// 库存汇总分析
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        [ServiceFabric.Authorize.BailunAuthentication(LoginMode.Enforce)]
        public string InventorySummaryJson(BtTableParameter parameter, string warehousetype, string warehousecode,DateTime day)
        {
            var total = 0;
            var _service = new Services.WareHouseServices();

            var obj = _service.ListInventorySummary(parameter, warehousetype, warehousecode, day, ref total);

            var objCount = _service.ListInventorySummaryCount(warehousetype, warehousecode, day);

            var list = obj.Select(a => new
            {
                a.warehousecode,
                a.warehousename,
                a.warehousetype,

                usable_stock = a.usable_stock.ToString("N0"),
                amount_stock = a.amount_stock.ToString("N2"),
                purchase_amount = a.purchase_amount.ToString("N2"),
                quantity_purchase = a.quantity_purchase.ToString("N0"),
                quantity_purchase_product = a.quantity_purchase_product.ToString("N0"),
                transfer_amount = a.transfer_amount.ToString("N2"),
                quantity_transfer = a.quantity_transfer.ToString("N0"),
                quantity_transfer_product = a.quantity_transfer_product.ToString("N0"),

                sale0_amount = a.sale0_amount.ToString("N2"),
                sale0_count_rate = (a.sale0_count_rate * 100).ToString("N2"),
                sale10_amount = a.sale10_amount.ToString("N2"),
                sale10_amount_rate = (a.sale10_amount_rate * 100).ToString("N2"),
                sale10_count = a.sale10_count.ToString("N0"),
                sale10_rate = (a.sale10_rate * 100).ToString("N2"),

                sale1_5_amount = a.sale1_5_amount.ToString("N2"),
                sale1_5_amount_rate = (a.sale1_5_amount_rate * 100).ToString("N2"),
                sale1_amount = a.sale1_amount.ToString("N2"),
                sale1_amount_rate = (a.sale1_amount_rate * 100).ToString("N2"),

                sale5_10_amount = a.sale5_10_amount.ToString("N2"),
                sale5_10_amount_rate = (a.sale5_10_amount_rate * 100).ToString("N2"),
                sale5_10_count = a.sale5_10_count.ToString("N0"),
                sale5_10_rate = (a.sale5_10_rate * 100).ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                rows = list,
                total = total,
                count_row = new
                {
                    warehousename = "总计",

                    usable_stock = objCount.usable_stock.ToString("N0"),
                    amount_stock = objCount.amount_stock.ToString("N2"),
                    purchase_amount = objCount.purchase_amount.ToString("N2"),
                    quantity_purchase = objCount.quantity_purchase.ToString("N0"),
                    quantity_purchase_product = objCount.quantity_purchase_product.ToString("N0"),
                    transfer_amount = objCount.transfer_amount.ToString("N2"),
                    quantity_transfer = objCount.quantity_transfer.ToString("N0"),
                    quantity_transfer_product = objCount.quantity_transfer_product.ToString("N0"),

                    sale0_amount = objCount.sale0_amount.ToString("N2"),
                    sale0_count_rate = (objCount.sale0_count_rate * 100).ToString("N2"),
                    sale10_amount = objCount.sale10_amount.ToString("N2"),
                    sale10_amount_rate = (objCount.sale10_amount_rate * 100).ToString("N2"),
                    sale10_count = objCount.sale10_count.ToString("N0"),
                    sale10_rate = (objCount.sale10_rate * 100).ToString("N2"),

                    sale1_5_amount = objCount.sale1_5_amount.ToString("N2"),
                    sale1_5_amount_rate = (objCount.sale1_5_amount_rate * 100).ToString("N2"),
                    sale1_amount = objCount.sale1_amount.ToString("N2"),
                    sale1_amount_rate = (objCount.sale1_amount_rate * 100).ToString("N2"),

                    sale5_10_amount = objCount.sale5_10_amount.ToString("N2"),
                    sale5_10_amount_rate = (objCount.sale5_10_amount_rate * 100).ToString("N2"),
                    sale5_10_count = objCount.sale5_10_count.ToString("N0"),
                    sale5_10_rate = (objCount.sale5_10_rate * 100).ToString("N2")
                }
            });
        }

        public ActionResult ExportInventorySummary(string warehousetype, string warehousecode,DateTime day) {

            var total = 0;
            var _service = new Services.WareHouseServices();

            var obj = _service.ListInventorySummary(new BtTableParameter { limit=0,offset=0}, warehousetype, warehousecode, day, ref total);

            var list = obj.Select(a => new
            {
                a.warehousecode,
                a.warehousename,
                a.warehousetype,

                usable_stock = a.usable_stock.ToString("N0"),
                amount_stock = a.amount_stock.ToString("N2"),
                purchase_amount = a.purchase_amount.ToString("N2"),
                quantity_purchase = a.quantity_purchase.ToString("N0"),
                quantity_purchase_product = a.quantity_purchase_product.ToString("N0"),
                transfer_amount = a.transfer_amount.ToString("N2"),
                quantity_transfer = a.quantity_transfer.ToString("N0"),
                quantity_transfer_product = a.quantity_transfer_product.ToString("N0"),

                sale0_amount = a.sale0_amount.ToString("N2"),
                sale0_count_rate = (a.sale0_count_rate * 100).ToString("N2"),
                sale10_amount = a.sale10_amount.ToString("N2"),
                sale10_amount_rate = (a.sale10_amount_rate * 100).ToString("N2"),
                sale10_count = a.sale10_count.ToString("N0"),
                sale10_rate = (a.sale10_rate * 100).ToString("N2"),

                sale1_5_amount = a.sale1_5_amount.ToString("N2"),
                sale1_5_amount_rate = (a.sale1_5_amount_rate * 100).ToString("N2"),
                sale1_amount = a.sale1_amount.ToString("N2"),
                sale1_amount_rate = (a.sale1_amount_rate * 100).ToString("N2"),

                sale5_10_amount = a.sale5_10_amount.ToString("N2"),
                sale5_10_amount_rate = (a.sale5_10_amount_rate * 100).ToString("N2"),
                sale5_10_count = a.sale5_10_count.ToString("N0"),
                sale5_10_rate = (a.sale5_10_rate * 100).ToString("N2"),
            });


            var colNames = new List<string>() { "仓库类型","仓库名称","sku数","sku金额","采购在途sku数"
                ,"采购在途产品数","采购在途金额","调拨在途sku数","调拨在途产品数","调拨在途金额"
                ,"日销大于10sku占比%","日销大于10sku数","日销大于10库存金额占比%","日销大于10库存金额","日销5-10sku数占比%"
                ,"日销5-10sku数","日销5-10库存金额占比%","日销5-10库存金额","日销1-5库存金额占比%","日销1-5库存金额"
                ,"日销0-1库存金额占比%","日销0-1库存金额","日销为0sku数占比%","日销为0sku库存金额"
            };

            var result = new List<string>();

            foreach (var item in list)
            {
                var str = item.warehousetype + "|" + item.warehousename + "|" + item.usable_stock + "|" + item.amount_stock + "|" + item.quantity_purchase + "|" +
                    item.quantity_purchase_product + "|" + item.purchase_amount + "|" + item.quantity_transfer + "|" + item.quantity_transfer_product + "|" + item.transfer_amount + "|" +
                    item.sale10_rate + "|" + item.sale10_count + "|" + item.sale10_amount_rate + "|" + item.sale10_amount + "|" + item.sale5_10_rate + "|" +
                    item.sale5_10_count + "|" + item.sale5_10_amount_rate + "|" + item.sale5_10_amount + "|" + item.sale1_5_amount_rate + "|" + item.sale1_5_amount + "|" +
                    item.sale1_amount_rate + "|" + item.sale1_amount + "|" + item.sale0_count_rate + "|" + item.sale0_amount;

                result.Add(str);
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "库存汇总分析 " + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(result, 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>
        /// 库存汇总分析趋势图
        /// </summary>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="warehousename">仓库名称</param>
        /// <param name="key">显示的字段</param>
        /// <returns></returns>
        public ActionResult InventorySummaryChart(string warehousecode,string warehousename,string key,string title,DateTime? day)
        {
            ViewBag.warehousecode = warehousecode;
            ViewBag.warehousename = warehousename;
            ViewBag.key = key;
            ViewBag.title = title;
            ViewBag.end = day.HasValue ? day.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.start = day.HasValue ? day.Value.AddDays(-30).ToString("yyyy-MM-dd") : "";

            return View();
        }

        /// <summary>
        /// 库存汇总分析趋势图
        /// </summary>
        /// <returns></returns>
        [ServiceFabric.Authorize.BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult InventorySummaryChartJson(string warehousecode,string key,DateTime start,DateTime end)
        {
            var _services = new Services.WareHouseServices();

            var obj = _services.InventorySummaryChart(warehousecode, start, end, key);

            var listval = new List<string>();
            var listdate = new List<string>();

            obj = obj.Where(a => !string.IsNullOrEmpty(a)).ToList();

            if (obj.Count > 0)
            {
                foreach (var item in obj)
                {
                    var arr = item.Split(',');
                    if (arr.Length > 1)
                    {
                        listval.Add(arr[0]);
                        listdate.Add(DateTime.Parse(arr[1]).ToString("yyyy-MM-dd"));
                    }
                }
            }

            return Json(new
            {
                success = true,
                msg = "",
                val = listval,
                dates = listdate,
            });

        }

        #endregion
    }

    class SkuCategory_Col
    {
        public string category_simple_name { get; set; }

        public List<string> days { get; set; }

        public List<string> list { get; set; }
    }
}