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()
        {
            return View();
        }

        /// <summary>
        /// 逻辑仓库 库存列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <returns></returns>
        public string LogicWarehouseJson(BtTableParameter parameter,string warehousetype,string warehousecode)
        {
            var service = new Services.WareHouseServices();
            var total = 0;
            var obj = service.ListLogicWarehouseStock(parameter, warehousetype, warehousecode, ref total);

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

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

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

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

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

            var colNames = new List<string> {"仓储仓库","库存数量","库存金额", "采购在途数量", "采购在途金额",
                                             "调拨在途数量", "调拨在途金额","待发货数量","缺货数量","昨日总销量"
                                             ,"昨日总销售额","七天销量","十四天销量","三十天销量"
            };

            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.oneday_total_sales + "|" +
                    item.amount_onedaysale + "|" + item.sevenday_total_sales + "|" + item.fourteenday_total_sales + "|" + item.thirtyday_total_sales
                    );
            }

            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)
        {
            ViewBag.warehousecode = code;
            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>
        /// <returns></returns>
        public string ListWareHouseSkuJson(BtTableParameter parameter, string code, int? push_status, int? minordercount, int? maxordercount, int? stockmin, int? stockmax, decimal? stockamountmin, decimal? stockamountmax,string skucategoryids)
        {
            var total = 0;
            var obj = new Services.WareHouseServices().ListWareHouseSku(parameter, code, null, minordercount, maxordercount, stockmin, stockmax, stockamountmin, stockamountmax, skucategoryids, push_status, ref total);

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

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


        /// <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>
        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]
        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>
        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>
        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);

        }
    }

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

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

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