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.Mvc;

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

        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)
        {
            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)
        {
            var result = new Services.SkuMonitorServices().ListGroupName(name,country,warehousetype,warehousecode);

            return Json(result);
        }

        /// <summary>
        /// 保存仓库冗余记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SkuWarehouseRedundancy1()
        {
            var filename = _hostingEnvironment.WebRootPath+"\\Files\\turnfile\\";

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

            return result;
        }

        /// <summary>
        /// 保存仓库sku销售额+销量数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SkuWarehouseSales1()
        {
            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)
        {
            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)
        {
            var total = 0;
            var obj = new Services.OrdersServices().ListOrderPlatformSku(page, pagesize, start, end,platform,companyid, ref total);
            
            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
            });

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

        }

        /// <summary>
        /// 保存sku发货重量差异值
        /// </summary>
        /// <param name="day">记录日期</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveSkuDeliverWeighDiff(DateTime? day)
        {
            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)
        {
            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)
        {
            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)
        {
            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)
        {
            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.paid_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)
        {
            try
            {
                var pagesize = 1000;
                var arrtype = new List<string>();

                if (m.type == 1)  //上架费
                {
                    arrtype = new List<string> { "BuyItNowFee",
                    "CreditAuctionEndEarly",
                    "CreditCardOnFile",
                    "CreditInsertion",
                    "ExtendedDurationFee",
                    "FeeAuctionEndEarly",
                    "FeeBold",
                    "FeeGalleryPlus",
                    "FeeInsertion",
                    "FeeLargePicture",
                    "FeePicturePack",
                    "FeeReserve",
                    "FeeReturnShipping",
                    "PaymentCC",
                    "PaypalOnFile",
                    "PrivateListing",
                    "SubscriptionSMBasic",
                    "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, string platform = "Aliexpress")
        {
            var pagesize = 1000;
            var total = 0;

            try
            {
                var obj = new Services.OrdersServices().ListInterceptOrderItemId(page, pagesize, start, end,ref total, platform);
                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)
        {
            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,
                });
            }
            
        }

    }
}