using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Models.Orders;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Bailun.DC.Web.Controllers
{
    public class ApiController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IHostingEnvironment _hostingEnvironment;
        public ApiController(IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor)
        {
            _hostingEnvironment = hostingEnvironment;
            _httpContextAccessor = httpContextAccessor;
        }

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

        /// <summary>
        /// 获取sku分组信息
        /// </summary>
        /// <param name="page">请求页</param>
        /// <param name="sku">sku编码</param>
        /// <param name="country">区域（国家）</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="groupname">分组信息</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetListSkuGroup([FromBody]Models.SkuGroup.mSkuGroupCondition m)
        {
            Services.ApiServices.SaveApiLog("Api/GetListSkuGroup", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var total = 0;
            var pagesize = 1000;
            var result = new Services.SkuMonitorServices().ListSkuGroup(m.page, pagesize, m.sku, m.warehousecode, m.country, m.groupname, ref total);

            return Json(new {
                data = result,
                page = m.page,
                pagecount = (total/ pagesize + (pagesize % 1000>0?1:0)),
                total = total
            });
        }

        /// <summary>
        /// 获取SKU分组信息列表（支持模糊搜索）
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetListGroup(string name,string country,string warehousetype,string warehousecode)
        {
            Services.ApiServices.SaveApiLog("Api/GetListGroup", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var result = new Services.SkuMonitorServices().ListGroupName(name,country,warehousetype,warehousecode);

            return Json(result);
        }

        /// <summary>
        /// 保存仓库冗余记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SkuWarehouseRedundancy1()
        {
            Services.ApiServices.SaveApiLog("Api/SkuWarehouseRedundancy1", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var filename = _hostingEnvironment.WebRootPath+"\\Files\\turnfile\\";

            var result = new Services.InventoryServices().SaveSkuWarehouseRedundancy(filename);

            return result;
        }

        /// <summary>
        /// 保存仓库sku销售额+销量数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SkuWarehouseSales1()
        {
            Services.ApiServices.SaveApiLog("Api/SkuWarehouseSales1", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var filename = _hostingEnvironment.WebRootPath + "\\Files\\turnfile\\skusales.csv";

            var result = new Services.InventoryServices().SaveSkuWarehouseSales(filename);

            return result;
        }

        /// <summary>
        /// 获取淘汰sku列表
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">淘汰开始时间</param>
        /// <param name="end">淘汰结束时间</param>
        /// <returns></returns>
        public JsonResult ListWeekOutSku(int page, int pagesize, DateTime? start, DateTime? end)
        {
            Services.ApiServices.SaveApiLog("Api/ListWeekOutSku", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var total = 0;
            var list = new Services.SkuMonitorServices().ListWeedOut(page, pagesize, start, end,ref total);

            return Json(new {
                success = true,
                skucodes = list,
                total = total
            });

        }

        /// <summary>
        /// 平台sku销量明细
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListPlatformSkuSales(int page, int pagesize, DateTime? start, DateTime? end,string platform,int companyid)
        {
            Services.ApiServices.SaveApiLog("Api/ListPlatformSkuSales", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var total = 0;
            var obj = new Services.OrdersServices().ListOrderPlatformSku(page, pagesize, start, end,platform,companyid, ref total);

            var _skuService = new Services.SkuInfoServices();

            var listBailunSku = _skuService.GetBailunSkuByPlatformSku(obj.Select(a => a.platform_sku).ToList());
            
            var list = obj.Select(a => new {
                a.origin_order_id,                            //平台订单号
                a.platform_type,                             //平台类型
                a.website,                                       //站点
                a.order_currency,                           //订单币种
                a.seller_order_exchange_rate,          //转换成人民币汇率
                a.platform_sku_quantity_ordered,   //销售数量
                a.platform_sku_unit_price,              //单价
                a.item_id,                                       //itemid
                a.platform_sku,                               //平台sku
                bailunskus= listBailunSku.Where(b=>b.platform_sku==a.platform_sku && b.platform==a.platform_type && b.site==a.website)?.Select(c=>c.bailun_sku)?.Distinct().ToList(),
            });

            return Json(new
            {
                success = true,
                data  = list,
                pageindex = page,
                total = total,
                pagecount = (total/pagesize)+(total%pagesize>0?1:0)
            });

        }

        /// <summary>
        /// 获取时间段内平台sku的销量
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="platform">平台类型</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListPlatformSkuCount(int page, DateTime start, DateTime end, string platform)
        {
            try
            {
                var pagesize = 1000;
                Services.ApiServices.SaveApiLog("Api/ListPlatformSkuCount", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
                var obj = new Services.OrdersServices().ListPlatformSkuCount(page, pagesize, start, end, platform, 1);

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = obj.Select(a => new {
                        a.platform_sku,
                        a.platform_type,
                        a.website,
                        ordercount = a.platform_sku_quantity_ordered,
                        a.item_id,
                    })
                });
            }
            catch (Exception ex)
            {
                return Json(new {
                    success = false,
                    msg = ex.Message
                });
            }
        }

        /// <summary>
        /// 保存sku发货重量差异值
        /// </summary>
        /// <param name="day">记录日期</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveSkuDeliverWeighDiff(DateTime? day)
        {
            Services.ApiServices.SaveApiLog("Api/SaveSkuDeliverWeighDiff", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());


            var result = new Services.OrdersServices().SaveWeighDiff(day);

            return Json(new {
                success = string.IsNullOrEmpty(result),
                msg = result,
            });
        }

        /// <summary>
        /// 获取销售帐号的利润数据
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSalerProfit(DateTime? start, DateTime? end,int companyid)
        {
            Services.ApiServices.SaveApiLog("Api/ListSalerProfit", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var list = new Services.OrdersServices().ListSalerProfit(start, end,companyid);
            return Json(list);
        }

        /// <summary>
        /// 获取item_id时间段内的销量
        /// </summary>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="itemid">item_id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListItemIdOrderCount([FromBody]Models.Orders.mItemIdOrderCount_Input m)
        {
            Services.ApiServices.SaveApiLog("Api/ListItemIdOrderCount", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            if (m.itemid.Length > 1000 || m.itemid.Length==0)
            {
                return Json(new {
                    success = false,
                    msg = "itemid数组元素个数必须大于0个，小于1000个"
                });
            }

            if (string.IsNullOrWhiteSpace(m.platform))
            {
                return Json(new
                {
                    success = false,
                    msg = "平台不能为空"
                });
            }

            var list = new Services.OrdersServices().GetItemIdOrderCount(m.platform, m.start, m.end, m.itemid);

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

        /// <summary>
        /// 获取发货sku利润数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListOrderSkuProfit([FromBody]Models.Orders.mShipSkuProfitInput m)
        {
            Services.ApiServices.SaveApiLog("Api/ListOrderSkuProfit", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var pagesize = 1000;
            var obj = new Services.OrdersServices().ListOrderSkuProfit(m.page, pagesize, m.start, m.end,m.bailun_order_id);

            var list = obj.Select(a => new
            {
                a.platform_type,
                a.seller_account,
                a.website,
                a.bailun_order_id,
                a.origin_order_id,
                a.transaction_id,
                a.paid_time,
                a.gmt_modified,
                a.bailun_sku,
                a.amount_sales,
                a.profit_total,
                a.company_id,
                a.pick_order_id,
                a.bailun_account_id,
                a.shipping_time,
                a.has_delete,
                quantity_shipped = a.platform_sku_quantity_shipped,
                a.warehouse_code,
                a.id,
                a.productvalue,

            });

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

        /// <summary>
        /// 获取FBA sku利润数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListFBASkuProfit([FromBody]Models.Orders.mShipSkuProfitInput m)
        {
            Services.ApiServices.SaveApiLog("Api/ListFBASkuProfit", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var pagesize = 1000;
            var obj = new Services.OrdersServices().ListFBASkuProfit(m.page, pagesize, m.start, m.end, m.bailun_order_id);

            var list = obj.Select(a => new
            {
                a.platform_type,
                a.seller_account,
                a.website,
                a.bailun_order_id,
                a.origin_order_id,
                a.transaction_id,
                a.paid_time,
                a.gmt_modified,
                a.bailun_sku,
                a.amount_sales,
                a.profit_total,
                a.company_id,
                pick_order_id = a.bailun_order_id,
                a.bailun_account_id,
                shipping_time = a.create_time,
                a.has_delete,
                quantity_shipped = a.platform_sku_quantity_shipped,
                a.warehouse_code,
                a.id,
                a.productvalue,

            });

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

        /// <summary>
        /// 获取ebay费用
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="type">费用类型，1：上架费，2：广告费</param>
        /// <param name="page">当前页</param>
        /// <param name="companyid">所属公司</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListEbayFee([FromBody]mEbayFeeInput m)
        {
            Services.ApiServices.SaveApiLog("Api/ListEbayFee", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
            try
            {
                var pagesize = 1000;
                var arrtype = new List<string>();

                if (m.type == 1)  //上架费
                {
                    arrtype = new List<string> { "BuyItNowFee","CreditInsertion","FeeGalleryPlus","PrivateListing","SubscriptioneBayStores","SubscriptionSMBasic","SubscriptionSMBasicPro","SubtitleFee"
                    };
                }
                else if (m.type == 2)  //广告费
                {
                    arrtype = new List<string> {
                    "CustomCode"
                };
                }


                var obj = new Services.OrdersServices().ListEbayFee(m.page, pagesize, m.start, m.end, arrtype.ToArray());

                var list = obj.Select(a => new {
                    a.id,
                    a.account_entry_type,
                    a.description,
                    bj_date = a.bj_date.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    a.gross_amount,
                    a.item_id,
                    a.account_id,
                    a.currency,
                    a.exchange_rate,
                    a.company_id
                });

                return Json(new
                {
                    success = true,
                    data = list,
                    msg = ""
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息：" + ex.Message
                });
            }
            
            
        }

        /// <summary>
        /// 获取拦截的itemid
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="platform">平台类型</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListInterceptItemid(int page,DateTime? start, DateTime? end,int? accountid,string platform = "Aliexpress")
        {
            Services.ApiServices.SaveApiLog("Api/ListInterceptItemid", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
            var pagesize = 1000;
            var total = 0;

            try
            {
                var obj = new Services.OrdersServices().ListInterceptOrderItemId(page, pagesize, start, end,ref total, platform,accountid);
                total = obj.Count;

                return Json(new {
                    success = true,
                    msg = "",
                    total = total,
                    list = obj.Select(a=>new {
                        a.item_id,
                        a.count
                    })
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message,
                    total = 0
                });
            }
        }

        /// <summary>
        /// 获取时间段内的订单利润
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetProfit(DateTime start, DateTime end)
        {
            Services.ApiServices.SaveApiLog("Api/GetProfit", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            try
            {
                var obj = new Services.OrdersServices().GetProfitTotal(start, end);

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = new
                    {
                        count = obj.id,
                        amount_sales = obj.amount_sales.ToString("#0.00"),
                        profit_total = obj.profit_total.ToString("#0.00"),
                        profit_rate = (obj.profit_rate*100).ToString("#0.00")+"%",
                    }
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message,
                });
            }
            
        }

        /// <summary>
        /// 获取Ebay Sku的销售数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="skus">sku数组</param>
        /// <param name="platform">平台</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult EbaySkuSalesCount(int page,DateTime start, DateTime end, string skus, string platform = "Ebay")
        {
            Services.ApiServices.SaveApiLog("Api/EbaySkuSales", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            int pagesize = 1000;

            try
            {
                var arrsku = new string[] { };

                if (!string.IsNullOrWhiteSpace(skus))
                {
                    arrsku = skus.Split(',');
                }
                var obj = new Services.OrdersServices().ListEbaySkuSalesCount(page, pagesize, start, end, arrsku, platform);

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = obj.Select(a=>new {
                        a.platform_type,
                        a.website,
                        a.bailun_sku,
                        count = a.bailun_sku_quantity_ordered,
                        amount = a.amount_sales
                    })
                });
            }
            catch (Exception ex)
            {
                return Json(new {
                    success = false,
                    msg = "出现异常，异常信息："+ex.Message
                });
            }
            
        }

        /// <summary>
        /// 获取Sku的销售数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="skus">sku数组</param>
        /// <param name="platform">平台</param>
        /// <param name="isplatformtime">是否按平台下单时间统计，1：是，0：否</param>
        /// <param name="timetype">1:创建时间，2：付款时间</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SkuSalesCount(int page, DateTime start, DateTime end, string skus, int? isplatformtime,int timetype=1, string platform = "Ebay")
        {
            Services.ApiServices.SaveApiLog("Api/SkuSales", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
            int pagesize = 1000;

            try
            {
                var arrsku = new string[] { };

                if (!string.IsNullOrWhiteSpace(skus))
                {
                    arrsku = skus.Split(',');
                }

                var obj = new List<Models.Ebay.mEbaySkuSales>();

                if (isplatformtime.HasValue && isplatformtime.Value == 1)
                {
                    obj = new Services.OrdersServices().ListEbaySkuSalesCountByPlatformCreateTime(page, pagesize, start, end, arrsku, platform);
                }
                else
                {
                    new Services.OrdersServices().ListEbaySkuSalesCount(page, pagesize, start, end, arrsku, platform);
                }
                

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = obj.Select(a => new {
                        a.platform_type,
                        a.website,
                        a.bailun_sku,
                        count = a.bailun_sku_quantity_ordered,
                        amount = a.amount_sales
                    })
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息：" + ex.Message
                });
            }

        }

        /// <summary>
        /// 根据订单更新的时间获取下单的日期
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSaleCountChangeDate(DateTime start, DateTime end)
        {
            try
            {
                var result = new Services.OrdersServices().ListSaleCountChangeDate(start, end);

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = result.Select(a => a.ToString("yyyy-MM-dd"))
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message,
                    
                });
            }
            

        }

        /// <summary>
        /// 根据时间段获取采购单明细
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="suppliername">供应商名称</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListPuchaseDetail(int page, DateTime start, DateTime end, string suppliername)
        {
            Services.ApiServices.SaveApiLog("Api/ListPuchaseDetail", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
            var pagesize = 1000;

            try
            {
                var obj = new Services.PurchaseServices().ListPurchaseDetail(page, pagesize, start, end, suppliername);
                return Json(new {
                    success = true,
                    msg = "",
                    data = obj
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message,
                    
                });
            }
        }

        /// <summary>
        /// 获取每日汇率
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DailyExchangeRate(DateTime date)
        {
            Services.ApiServices.SaveApiLog("Api/DailyExchangeRate", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
            var obj = new Services.CommonServices().ListDateExchangeRate(date);

            return Json(new {
                success = true,
                data = obj.Select(a=>new {
                    record_time = a.record_time.ToString("yyyy-MM-dd"),
                    a.init_curreny,
                    a.final_curreny,
                    a.exchange_rate,
                })
            });
        }

        /// <summary>
        /// 获取平台itemid的销量
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="platform">平台类型</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListPlatformItemIdCount(int page,DateTime start,DateTime end,string platform)
        {
            Services.ApiServices.SaveApiLog("Api/ListPlatformItemIdCount", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var pagesize = 1000;

            try
            {
                var obj = new Services.OrdersServices().ListPlatformItemIdCount(page, pagesize, start, end, platform);

                return Json(new
                {
                    list = obj.Select(a => new {
                        platform = a.platform_type,
                        a.item_id,
                        salecount = a.platform_sku_quantity_ordered
                    }),
                    success = true,
                    msg = ""
                });
            }
            catch (Exception ex)
            {
                return Json(new {
                    success = false,
                    msg = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取sku的退款数量
        /// </summary>
        /// <param name="start">退款开始时间</param>
        /// <param name="end">退款结束时间</param>
        /// <param name="sku"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSkuRefundCount(DateTime start, DateTime end, string sku,string platform)
        {
            Services.ApiServices.SaveApiLog("Api/ListSkuRefundCount", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            try
            {
                var obj = new Services.OrdersServices().ListSkuRefund(sku, start, end,platform);

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = obj.Select(a=>new {
                        a.bailun_sku,
                        a.refundcount,
                        a.platform_type,
                        a.website,
                        a.bailun_account_id,
                        
                    })
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取SKU+仓库的库存和销量信息
        /// </summary>
        /// <param name="skus"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSkuStock(string skus)
        {
            Services.ApiServices.SaveApiLog("Api/ListSkuStock", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            var listsku = skus.Split(",").Where(a => !string.IsNullOrEmpty(a)).ToList();

            if (listsku.Count == 0)
            {
                return Json(new {
                    success = false,
                    msg = "必须最少要有一个sku",
                });
            }

            if (listsku.Count > 2000)
            {
                return Json(new
                {
                    success = false,
                    msg = "每次请求不能大于2000个sku",
                });
            }

            try
            {
                var obj = new Services.WareHouseServices().ListSkuStock(listsku.ToList());

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = obj.Select(a => new {
                        a.bailun_sku,
                        a.warehouse_code,
                        a.warehouse_name,
                        warehousetype = a.hq_type,
                        a.usable_stock,
                        a.amount,
                        //count_transfer = a.count_transfer??0,
                        purchase_transfer = a.purchase_transfer??0,
                        allot_plan_transfer = a.allot_plan_transfer??0,
                        allot_transfer = a.allot_transfer??0,
                        quantity_out_stock = a.quantity_out_stock??0,
                        oneday_total_sales = a.oneday_total_sales??0,
                        sevenday_average_sales = a.sevenday_average_sales??0,
                        thirtyday_average_sales = a.thirtyday_average_sales??0,
                    })
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                });
            }

        }

        /// <summary>
        /// 获取调拨单详情信息
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListAllotInfo(DateTime start, DateTime end,int page,int pagesize=1000)
        {
            try
            {
                var total = 0;
                var result = new Services.AllotServices().ListAllot(page, pagesize, start, end, ref total);

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


        /// <summary>
        /// 获取SKU的财务分类
        /// </summary>
        /// <param name="skus"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetSkuFinanceCategory(string skus)
        {
            var arrsku = skus.Split(',').Where(a=>!string.IsNullOrEmpty(a)).ToList();

            if (arrsku.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "SKU必须大于一个",
                });
            }

            var result = new Services.SkuInfoServices().GetSkuFinanceCategory(arrsku);
            
            return Json(new {
                success = true,
                msg = "",
                list = result,
            });
        }

        /// <summary>
        /// 获取仓库列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetWarehouseInfo()
        {
            var obj = new Services.WareHouseServices().List("", null);

            return Json(new { 
                success = true,
                msg = "",
                data = obj.Select(a=> new { 
                    a.warehouse_code,
                    a.warehouse_name,
                    warehouse_type = a.hq_type,
                    a.area_id,
                    a.area_name
                })
            });
        }

        /// <summary>
        /// 获取指定itemid的利润率
        /// </summary>
        /// <param name="itemids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetItemNoProfitRate(string itemids)
        {
            var arr = new List<string>();

            if (!string.IsNullOrEmpty(itemids))
            {
                arr = itemids.Split(",").Where(a => !string.IsNullOrEmpty(a)).ToList();
            }

            var obj = new Services.OrdersServices().ListItemNoProfitRateAPI(arr, DateTime.Now.AddDays(-1));
            return Json(new
            {
                success = true,
                msg = "",
                data = obj
            });
        }


        ///// <summary>
        ///// 首次入库时间
        ///// </summary>
        ///// <param name="start">开始时间</param>
        ///// <param name="end">结束时间</param>
        ///// <returns></returns>
        //[HttpPost]
        //public JsonResult FirstPutinTime(DateTime start, DateTime end)
        //{


        //}

    }
}