using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Bailun.DC.Models;
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;
using System.Data;

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

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

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

        #region 平台费用流水

        public ActionResult ListPlatformCost(string p)
        {
            ViewBag.platform = p;
            return View();
        }

        /// <summary>
        /// 平台费用流水
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListPlatformCostJson(BtTableParameter parameter, string platform, DateTime? start, DateTime? end,string website,string account,string warehousetype,string warehousecode,string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User.GetCompanyId().ToInt32();

            var total = 0;
            var obj = new Services.OrdersServices().ListPlatformCost(parameter, platform, start, end,website,account,warehousetype,warehousecode, companyid, ref total,skucategoryids);

            var countM = new Services.OrdersServices().ListPlatformCostCount(platform, start, end,website,account, warehousetype, warehousecode, companyid, skucategoryids);
            
            var list = obj.Select(p => new {
                p.origin_order_id,
                p.bailun_order_id,
                p.platform_type,
                p.website,
                p.seller_account,
                amount_sales = (p.amount_sales*p.seller_order_exchange_rate).ToString("N2"),
                amount_refund = (p.amount_refund*p.seller_order_exchange_rate).ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                cost_promotion = (p.cost_promotion*p.seller_order_exchange_rate).ToString("N2"),
                amount_shipping = (p.amount_shipping*p.seller_order_exchange_rate).ToString("N2"),

                cost_platform_fee = (p.platform_type=="Ebay"?p.cost_platform_fee*p.seller_other_exchange_rate:p.cost_platform_fee*p.seller_order_exchange_rate).ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_fba_fee = (p.cost_fba_fee*p.seller_order_exchange_rate).ToString("N2"),
                cost_paypal_fee = (p.cost_paypal_fee*p.seller_order_exchange_rate).ToString("N2"),
                cost_refund_commisson = (p.cost_refund_commisson*p.seller_order_exchange_rate).ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                cost_logistics = p.cost_logistics.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (p.profit_rate*100).ToString("N2"),
                paid_time = p.paid_time.ToString("yyyy-MM-dd HH:mm:ss"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                companyid = companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportPlatformCost", HttpContextHelper.Current.User.GetUid()),
                count_row = new {
                    bailun_order_id = "总计",
                    amount_sales = countM.amount_sales.ToString("N2"),
                    amount_refund = (countM.amount_refund).ToString("N2"),
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),
                    cost_promotion = (countM.cost_promotion).ToString("N2"),
                    amount_shipping = (countM.amount_shipping).ToString("N2"),

                    cost_platform_fee = (countM.cost_platform_fee).ToString("N2"),
                    cost_product = countM.cost_product.ToString("N2"),
                    cost_package = countM.cost_package.ToString("N2"),
                    cost_fba_fee = (countM.cost_fba_fee).ToString("N2"),
                    cost_paypal_fee = (countM.cost_paypal_fee).ToString("N2"),
                    cost_refund_commisson = (countM.cost_refund_commisson).ToString("N2"),
                    cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                    cost_handle_platform = countM.cost_handle_platform.ToString("N2"),
                    cost_first = countM.cost_first.ToString("N2"),
                    cost_logistics = countM.cost_logistics.ToString("N2"),
                    profit_total = countM.profit_total.ToString("N2"),
                    profit_rate = countM.amount_sales>0?((countM.profit_total/ countM.amount_sales) * 100).ToString("N2"):"0",
                }
            });
        }

        /// <summary>
        /// 导出平台费用流水
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="website"></param>
        /// <param name="account"></param>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <param name="skucategoryids"></param>
        /// <returns></returns>
        public ActionResult ExportPlatformCost(string platform, DateTime? start, DateTime? end, string website, string account, string warehousetype, string warehousecode, string skucategoryids,int companyid)
        {
            var obj = new Services.OrdersServices().ListPlatformCost(platform, start, end, website, account, warehousetype, warehousecode, companyid,skucategoryids);

            var o = obj.Select(p => new {
                p.origin_order_id,
                p.bailun_order_id,
                p.platform_type,
                p.website,
                p.seller_account,
                amount_sales = (p.amount_sales * p.seller_order_exchange_rate).ToString("N2"),
                amount_refund = (p.amount_refund * p.seller_order_exchange_rate).ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                cost_promotion = (p.cost_promotion * p.seller_order_exchange_rate).ToString("N2"),
                amount_shipping = (p.amount_shipping * p.seller_order_exchange_rate).ToString("N2"),

                cost_platform_fee = (p.platform_type == "Ebay" ? p.cost_platform_fee * p.seller_other_exchange_rate : p.cost_platform_fee * p.seller_order_exchange_rate).ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_fba_fee = (p.cost_fba_fee * p.seller_order_exchange_rate).ToString("N2"),
                cost_paypal_fee = (p.cost_paypal_fee * p.seller_order_exchange_rate).ToString("N2"),
                cost_refund_commisson = (p.cost_refund_commisson * p.seller_order_exchange_rate).ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (p.profit_rate * 100).ToString("N2"),
                paid_time = p.paid_time.ToString("yyyy-MM-dd HH:mm:ss"),
            });

            var colNames = new List<string> {"平台订单号","平台名称","平台站点", "卖家帐号", "销售额",
                                             "平台费", "促销费","尾程费","百伦处理费","产品成本",
                                             "头程费","预收金额","利润","利润率","退款金额",
                                             "运费收入","FBA费","Paypal费","付款时间"};

            var list = new List<string>();
            foreach (var item in o)
            {
                list.Add(item.origin_order_id+"|"+item.platform_type+"|"+item.website+"|"+item.seller_account+"|"+item.amount_sales+"|"+
                    item.cost_platform_fee+"|"+item.cost_promotion+"|"+item.cost_tail+"|"+item.cost_handle_bailun+"|"+item.cost_product+"|"+
                    item.cost_first+"|"+item.amount_prepaid+"|"+item.profit_total+"|"+item.profit_rate+"|"+item.amount_refund+"|"+
                    item.amount_shipping+"|"+item.cost_fba_fee+"|"+item.cost_paypal_fee+"|"+item.paid_time
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = platform+"平台费用流水" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        #endregion

        #region 亚马逊 FBA+非FBA
        /// <summary>
        /// 亚马逊销售统计
        /// </summary>
        /// <returns></returns>
        public ActionResult AmazonSaleStatistics()
        {
            return View();
        }

        /// <summary>
        /// 亚马逊销售统计
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="sellaccount">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="currency">币种</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListAmazonSaleStatisticsJson(BtTableParameter parameter, string sellaccount, string website, DateTime start, DateTime end,string warehousetype, string warehousecode,string skucategoryids,string currency)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();

            var total = 0;
            var service = new Services.OrdersServices();

            var objwithdraw = new Services.PlatformSiteServices().GetPlatformLossWithdraw().Where(a => a.english_name == "Amazon").FirstOrDefault();
            

            var list = service.ListAmazonStatistics(parameter, sellaccount, website, start, end, warehousetype,warehousecode,companyid, ref total,skucategoryids);

            var countM = service.ListAmazonStatisticsCount(sellaccount, website, start, end,warehousetype,warehousecode,companyid,skucategoryids);
            countM.website = "总计：";
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.loss_withdrawal = countM.amount_product * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0);
            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_logistics = Math.Round(countM.cost_logistics, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_platform = Math.Round(countM.cost_handle_platform, 2, MidpointRounding.AwayFromZero);

            countM.profit_rate = countM.amount_product>0?Math.Round((countM.profit_total / countM.amount_product), 2, MidpointRounding.AwayFromZero):0;
            
            var obj = list.Select(p => new
            {
                p.platform_type,
                p.seller_account,
                p.website,
                amount_sales = p.amount_sales.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                order_count = p.order_count.ToString("N0"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                loss_withdrawal = (p.amount_product * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0))>0? (p.amount_product * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0)).ToString("N2"):"0",
                cost_total = p.cost_total.ToString("N2"),
                cost_logistics = p.cost_logistics.ToString("N2"),
                amount_refund = p.amount_refund > 0 ? p.amount_refund.ToString("N2") : "0",
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                noshippingcount = p.noshippingcount.ToString("N0"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (100 * p.profit_rate).ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = obj,count_row=new {
                countM.website,
                amount_sales = countM.amount_sales.ToString("N2"),
                cost_product = countM.cost_product.ToString("N2"),
                cost_platform_fee = countM.cost_platform_fee.ToString("N2"),
                cost_first = countM.cost_first.ToString("N2"),
                countM.order_count,
                loss_withdrawal = countM.loss_withdrawal>0? countM.loss_withdrawal.ToString("N2"):"0",
                cost_total = countM.cost_total.ToString("N2"),
                cost_logistics = countM.cost_logistics.ToString("N2"),

                profit_total = countM.profit_total.ToString("N2"),
                profit_rate = (100 * countM.profit_rate).ToString("N2"),
                countM.order_currency,
                amount_prepaid = countM.amount_prepaid.ToString("N2"),
                amount_refund = countM.amount_refund > 0 ? countM.amount_refund.ToString("N2") : "0",
                noshippingcount = countM.noshippingcount.ToString("N0"),

                cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = countM.cost_handle_platform.ToString("N2")
            }
            });
        }

        /// <summary>
        /// FBA销售统计
        /// </summary>
        /// <returns></returns>
        public ActionResult FBASaleStatistics()
        {
            return View();
        }

        /// <summary>
        /// FBA销售统计数据
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="sellaccount">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListFBASaleStatisticsJson(BtTableParameter parameter, string sellaccount, string website, DateTime start, DateTime end,string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();

            var objwithdraw = new Services.PlatformSiteServices().GetPlatformLossWithdraw().Where(a => a.english_name == "Amazon").FirstOrDefault();
            var list = service.ListFBAStatistics(parameter, sellaccount, website, start, end,companyid, ref total,skucategoryids);

            var countM = service.ListFBAStatisticsCount(sellaccount, website, start, end,companyid, skucategoryids);
            countM.website = "总计：";
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_count = Math.Round(countM.cost_count, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.fba_fee = Math.Round(countM.fba_fee, 2, MidpointRounding.AwayFromZero);
            countM.fba_profit = Math.Round(countM.fba_profit, 2, MidpointRounding.AwayFromZero);
            countM.forecast_profit_count = Math.Round(countM.forecast_profit_count, 2, MidpointRounding.AwayFromZero);
            countM.head_fee = Math.Round(countM.head_fee, 2, MidpointRounding.AwayFromZero);
            countM.nofba_forecast_logisticsfee = Math.Round(countM.nofba_forecast_logisticsfee, 2, MidpointRounding.AwayFromZero);
            countM.nofba_forecast_profit = Math.Round(countM.nofba_forecast_profit, 2, MidpointRounding.AwayFromZero);
            countM.nofba_logisticsfee = Math.Round(countM.nofba_logisticsfee, 2, MidpointRounding.AwayFromZero);
            countM.nofba_profit = Math.Round(countM.nofba_profit, 2, MidpointRounding.AwayFromZero);
            countM.platform_fee = Math.Round(countM.platform_fee, 2, MidpointRounding.AwayFromZero);

            countM.profit_count = Math.Round(countM.profit_count, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.loss_withdrawal = countM.amount_product * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0);
            countM.cost_fba_fee = Math.Round(countM.cost_fba_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.profit_rate = countM.amount_product>0?Math.Round((countM.profit_count / countM.amount_product), 2, MidpointRounding.AwayFromZero):0;


            var obj = list.Select(p => new
            {
                p.platform_type,
                p.seller_account,
                p.website,
                amount_product = p.amount_product.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                platform_fee = p.platform_fee.ToString("N2"),
                head_fee = p.head_fee.ToString("N2"),
                p.order_count,
                loss_withdrawal = (p.amount_product * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0)) > 0 ? (p.amount_product * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0)).ToString("N2") : "0",
                cost_count = p.cost_count.ToString("N2"),
                forecast_profit_count = p.forecast_profit_count.ToString("N2"),
                nofba_logisticsfee = p.nofba_logisticsfee > 0 ? p.nofba_logisticsfee.ToString("N2") : "0",
                nofba_forecast_logisticsfee = p.nofba_forecast_logisticsfee.ToString("N2"),
                forecast_profit_rate = (100 * p.forecast_profit_rate).ToString("N2"),
                profit_count = p.profit_count.ToString("N2"),
                profit_rate = (100 * p.profit_rate).ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                amount_refund = p.amount_refund > 0 ? p.amount_refund.ToString("N2") : "0",
                cost_fba_fee = p.cost_fba_fee>0?p.cost_fba_fee.ToString("N2"):"0",
                cost_paypal_fee = p.cost_paypal_fee>0?p.cost_paypal_fee.ToString("N2"):"0",
                cost_package = p.cost_package>0?p.cost_package.ToString("N2"):"0",
                noshippingcount = p.noshippingcount.ToString("N0"),
            });

            return JsonConvert.SerializeObject(new { total = total, rows = obj,
                count_row = new
                {
                    countM.website,
                    amount_product = countM.amount_product.ToString("N2"),
                    cost_product = countM.cost_product.ToString("N2"),
                    platform_fee = countM.platform_fee.ToString("N2"),
                    head_fee = countM.head_fee.ToString("N2"),
                    countM.order_count,
                    loss_withdrawal = countM.loss_withdrawal > 0 ? countM.loss_withdrawal.ToString("N2") : "0",
                    cost_count = countM.cost_count.ToString("N2"),
                    forecast_profit_count = countM.forecast_profit_count.ToString("N2"),
                    nofba_logisticsfee = countM.nofba_logisticsfee.ToString("N2"),
                    nofba_forecast_logisticsfee = countM.nofba_forecast_logisticsfee.ToString("N2"),
                    forecast_profit_rate = (100 * countM.forecast_profit_rate).ToString("N2"),
                    profit_count = countM.profit_count.ToString("N2"),
                    profit_rate = (100 * countM.profit_rate).ToString("N2"),
                    countM.order_currency,
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),
                    amount_refund = countM.amount_refund > 0 ? countM.amount_refund.ToString("N2") : "0",
                    cost_fba_fee = countM.cost_fba_fee > 0 ? countM.cost_fba_fee.ToString("N2") : "0",
                    cost_paypal_fee = countM.cost_paypal_fee > 0 ? countM.cost_paypal_fee.ToString("N2") : "0",
                    cost_package = countM.cost_package > 0 ? countM.cost_package.ToString("N2") : "0",
                    noshippingcount = countM.noshippingcount.ToString("N0"),
                }
            });
        }

        /// <summary>
        /// 订单流水
        /// </summary>
        /// <returns></returns>
        public ActionResult ListOrder(string platform)
        {

            ViewBag.platform = platform;
            return View();
        }

        /// <summary>
        /// 订单流水数据
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="platform">平台</param>
        /// <param name="account">帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">平台订单号</param>
        /// <param name="sku">sku编码</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListOrderJson(BtTableParameter parameter, string platform, string account, string website, DateTime? start, DateTime? end,string orderno,string sku,string skucategoryids,decimal? rate_start,decimal? rate_end)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var obj = service.ListOrders(parameter, platform, website, account, start, end, orderno, sku,companyid, ref total,skucategoryids,rate_start,rate_end);

            var countM = service.ListOrdersCount(platform, website, account, start, end, orderno, sku,companyid,skucategoryids, rate_start, rate_end);
            countM.amount_adjustment = Math.Round(countM.amount_adjustment, 2, MidpointRounding.AwayFromZero);
            countM.amount_gift_wrap = Math.Round(countM.amount_gift_wrap, 2, MidpointRounding.AwayFromZero);
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.amount_shipping = Math.Round(countM.amount_shipping, 2, MidpointRounding.AwayFromZero);
            countM.amount_tax = Math.Round(countM.amount_tax, 2, MidpointRounding.AwayFromZero);
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);

            countM.cost_estimate_logistics = Math.Round(countM.cost_estimate_logistics, 2, MidpointRounding.AwayFromZero);
            countM.cost_fba_fee = Math.Round(countM.cost_fba_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_promotion = Math.Round(countM.cost_promotion, 2, MidpointRounding.AwayFromZero);
            countM.cost_refund_commisson = Math.Round(countM.cost_refund_commisson, 2, MidpointRounding.AwayFromZero);
            countM.cost_shipping = Math.Round(countM.cost_shipping, 2, MidpointRounding.AwayFromZero);
            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_platform = Math.Round(countM.cost_handle_platform, 2, MidpointRounding.AwayFromZero);
            countM.cost_logistics = Math.Round(countM.cost_logistics, 2, MidpointRounding.AwayFromZero);

            countM.website = "总计：";

            //,t1.cost_handle_bailun,t1.cost_handle_platform,t1.cost_logistics
            var list = obj.Select(p => new {
                p.bailun_order_id,
                p.origin_order_id,
                p.platform_type,
                p.website,
                p.seller_account,
                p.platform_order_type,
                p.bailun_order_status,
                p.bailun_payment_status,
                p.bailun_shipping_status,
                p.order_currency,
                amount_sales = p.amount_sales.ToString("N2"),
                amount_shipping = p.amount_shipping.ToString("N2"),
                amount_product = p.amount_product.ToString("N2"),
                amount_adjustment = p.amount_adjustment.ToString("N2"),
                cost_promotion = p.cost_promotion.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_fba_fee = p.cost_fba_fee.ToString("N2"),
                cost_total = p.cost_total.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                create_time = p.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                order_update_time = p.order_update_time.ToString("yyyy-MM-dd HH:mm:ss"),
                p.salecount,
                profit_rate = (p.profit_rate*100).ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2"),
                cost_logistics = p.cost_logistics.ToString("N2")

            });

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


        /// <summary>
        /// 财务费用
        /// </summary>
        /// <param name="platform"></param>
        /// <returns></returns>
        public ActionResult FinanceFee(string platform)
        {
            ViewBag.platform = platform;
            return View();
        }

        /// <summary>
        /// 财务费用
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="platform"></param>
        /// <param name="feetype"></param>
        /// <param name="feecharacter"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string FinanceFeeJson(BtTableParameter parameter, string platform, int feetype, int feecharacter, string account, DateTime? start, DateTime? end, string orderno)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();

            var objwithdraw = new Services.PlatformSiteServices().GetPlatformLossWithdraw().Where(a => a.english_name == platform).FirstOrDefault();
            var obj = service.ListFinanceFee(parameter, platform, feetype, feecharacter, account, start, end, orderno,companyid, ref total);

            var countM = service.ListFinanceFeeCount(platform, feetype, feecharacter, account, start, end, orderno,companyid);
            countM.amount_sales = Math.Round(countM.amount_sales, 2);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2);
            countM.amount_shipping = Math.Round(countM.amount_shipping, 2);
            countM.cost_promotion = Math.Round(countM.cost_promotion, 2);
            countM.cost_first = Math.Round(countM.cost_first, 2);
            countM.cost_logistics = Math.Round(countM.cost_logistics, 2);
            countM.cost_fba_fee = Math.Round(countM.cost_fba_fee, 2);
            countM.platform_fee_rate = countM.amount_sales>0?Math.Round((countM.cost_platform_fee / countM.amount_sales * 100), 2):0;
            countM.losswithdrawal = Math.Round((countM.amount_sales * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0) > 0 ? (countM.amount_sales * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0)) : 0), 2);
            countM.amount_total = Math.Round(countM.amount_total, 2);
            countM.cost_total = Math.Round(countM.cost_total, 2);

            countM.bailun_sku = "总计：";

            var list = obj.Select(p => new {
                p.origin_order_id,
                p.platform_type,
                p.website,
                p.seller_account,
                p.bailun_sku,
                amount_sales = p.amount_sales.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                amount_shipping = p.amount_shipping.ToString("N2"),
                cost_promotion = p.cost_promotion.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                cost_logistics = p.cost_logistics.ToString("N2"),
                cost_fba_fee = p.cost_fba_fee.ToString("N2"),
                platform_fee_rate = p.amount_sales>0?(p.cost_platform_fee/ p.amount_sales * 100).ToString("N2"):"0",
                losswithdrawal = (p.amount_sales * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0)) > 0 ? (p.amount_sales * (objwithdraw == null ? 0 : objwithdraw.Loss_withdrawal_percent ?? 0)).ToString("N2") : "0",
                amount_total = p.amount_total.ToString("N2"),
                cost_total = p.cost_total.ToString("N2"),
                paid_time = p.paid_time.ToString("yyyy-MM-dd HH:mm:ss")
            });


            return JsonConvert.SerializeObject(new { total = total, rows = list,count_row=new {
                bailun_sku = "总计",
                amount_sales = countM.amount_sales.ToString("N2"),
                cost_platform_fee = countM.cost_platform_fee.ToString("N2"),
                amount_shipping = countM.amount_shipping.ToString("N2"),
                cost_promotion = countM.cost_promotion.ToString("N2"),
                cost_first = countM.cost_first.ToString("N2"),
                cost_logistics = countM.cost_logistics.ToString("N2"),
                cost_fba_fee = countM.cost_fba_fee.ToString("N2"),
                platform_fee_rate = countM.platform_fee_rate.ToString("N2"),
                losswithdrawal = countM.losswithdrawal.ToString("N2"),
                amount_total = countM.amount_total.ToString("N2"),
                cost_total = countM.cost_total.ToString("N2"),
            }
            });
        }

        /// <summary>
        /// FBA费用异常订单
        /// </summary>
        /// <returns></returns>
        public ActionResult FBAAbnormalOrder()
        {
            return View();
        }


        /// <summary>
        /// FBA费用异常订单
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="account">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="orderno">订单号</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string FBAabnormalOrderJson(BtTableParameter parameter, string account, string website, string orderno, DateTime? start, DateTime? end,string skucategoryids)
        {

            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var obj = new Services.OrdersServices().ListFbaAbnormalOrder(parameter, account, website, start, end, orderno,companyid, ref total,skucategoryids);

            var list = obj.Select(p => new {
                average_fba_fee = p.average_fba_fee>0?p.average_fba_fee.ToString("N2") :"0",
                p.bailun_sku,
                cost_fba_fee = p.cost_fba_fee>0? p.cost_fba_fee.ToString("N2") :"0",
                create_time = p.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                fba_fee_rmb = p.fba_fee_rmb>0? p.fba_fee_rmb.ToString("N2") :"0",
                max_fba_fee = p.max_fba_fee>0? p.max_fba_fee.ToString("N2") :"0",
                min_fba_fee = p.min_fba_fee>0? p.min_fba_fee.ToString("N2") :"0",
                p.order_currency,
                p.origin_order_id,
                p.platform_type,
                p.product_code,
                p.seller_account,
                seller_order_exchange_rate = p.seller_order_exchange_rate>0?p.seller_order_exchange_rate.ToString("N2") :"0",
                p.website,
            });

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


        /// <summary>
        /// 平台费异常订单
        /// </summary>
        /// <returns></returns>
        public ActionResult PlatformFeeAbnormal(string platform)
        {
            ViewBag.platform = platform;
            return View();
        }

        /// <summary>
        /// 平台费异常订单
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="account"></param>
        /// <param name="website"></param>
        /// <param name="orderno"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string PlatformFeeAbnormalJson(BtTableParameter parameter,string platform,string account,string website,string orderno,DateTime? start,DateTime? end,string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var obj = service.ListPlatformFeeAbnormal(parameter, platform, account, website, orderno, start, end,companyid, ref total, skucategoryids);

            var countM = service.ListPlatformFeeAbnormalCount(platform, account, website, orderno, start, end,companyid, skucategoryids);
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.seller_account = "总计：";

            var list = obj.Select(p => new {
                p.origin_order_id,
                p.bailun_order_id,
                p.seller_account,
                amount_product = p.amount_product>0? p.amount_product.ToString("N2") :"0",
                cost_platform_fee = p.cost_platform_fee>0? p.cost_platform_fee.ToString("N2") :"0",
                platform_fee_rate = p.platform_fee_rate>0? (p.platform_fee_rate*100).ToString("N0") :"0",
                p.platform_type,
                p.website,
                create_time = p.create_time.ToString("yyyy-MM-dd HH:mm:ss")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list,count_row = countM });
        }
        
        
        /// <summary>
        /// 非FBA销售订单
        /// </summary>
        /// <param name="fba">是否fba订单，1：是，0：否</param>
        /// <returns></returns>
        public ActionResult SkuOrderList(int fba)
        {
            ViewBag.isfba = fba;
            return View();
        }

        /// <summary>
        /// FBA销售订单
        /// </summary>
        /// <returns></returns>
        public ActionResult FBASkuOrderList()
        {
            return View();
        }

        /// <summary>
        /// 销售订单 sku维度
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="orderstatus">订单状态</param>
        /// <param name="shippingstatus">发货状态</param>
        /// <param name="orderno">订单号</param>
        /// <param name="sku">sku编码</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string SkuOrderListJson(BtTableParameter parameter, string warehousetype, string warehousecode,string seller,DateTime? start,DateTime? end, string orderstatus, string shippingstatus, string orderno, string sku,int isfba)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var obj = service.ListSkuOrder(parameter, warehousetype, warehousecode, seller, start, end, orderno, sku, orderstatus, shippingstatus, ref total, isfba,companyid);
            var countM = service.ListSkuOrderCount(warehousetype, warehousecode, seller, start, end, orderno, sku, orderstatus, shippingstatus, isfba,companyid);

            countM.sku_image = "总计：";

            return JsonConvert.SerializeObject(new { total = total, rows = obj,count_row = countM });
        }

        /// <summary>
        /// 订单汇总
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderSaleCount()
        {
            return View();
        }

        /// <summary>
        /// 订单汇总数据
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string OrderSaleCountJson(BtTableParameter parameter,string platform,string account,string website,string warehousecode, DateTime? start,DateTime? end,string sku)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();

            var obj = service.ListSkuSaleCount(parameter, platform, account, website, warehousecode, start, end, sku,companyid, ref total);
            var countM = service.ListSkuSaleCounts(platform, account, website, warehousecode, start, end, sku,companyid);
            countM.warehouse_name = "总计：";

            return JsonConvert.SerializeObject(new { total = total, rows = obj,count_row = countM });
        }

        #endregion

        #region Ebay

        /// <summary>
        /// Ebay销售统计
        /// </summary>
        /// <returns></returns>
        public ActionResult EbaySaleStatistics()
        {
            return View();
        }

        /// <summary>
        /// Ebay销售统计 Json
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="selleraccount"></param>
        /// <param name="website"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string EbaySaleStatisticsJson(BtTableParameter parameter, string selleraccount, string website, DateTime start, DateTime end, string warehousetype, string warehousecode,string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();

            var total = 0;
            var services = new Services.OrdersServices();
            var objwithdraw = new Services.PlatformSiteServices().GetPlatformLossWithdraw().Where(a => a.english_name == "Ebay").FirstOrDefault();
            var withdrawpercent = 0.0000M;
            if (objwithdraw != null && objwithdraw.Loss_withdrawal_percent.HasValue)
            {
                withdrawpercent = objwithdraw.Loss_withdrawal_percent.Value;
            }

            withdrawpercent = 0.025m;

            var list = services.ListEbayStatistics(parameter, website, selleraccount, start, end, warehousetype, warehousecode,companyid, ref total,skucategoryids);

            var countM = services.ListEbayStatisticsCount("Ebay",website, selleraccount, start, end, warehousetype, warehousecode,companyid, skucategoryids);
            
            countM.seller_account = "总计：";
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.loss_withdrawal = countM.amount_sales * (withdrawpercent);
            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_shipping = Math.Round(countM.cost_shipping, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.profit_rate = countM.amount_product>0?Math.Round((countM.profit_total / countM.amount_product), 2, MidpointRounding.AwayFromZero):0;
            countM.cost_tail = Math.Round(countM.cost_tail, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);
            countM.cost_logistics = Math.Round(countM.cost_logistics, 2, MidpointRounding.AwayFromZero);

            var obj = list.Select(p => new
            {
                p.platform_type,
                p.seller_account,
                p.website,
                amount_sales = p.amount_sales.ToString("N2"),
                amount_product = p.amount_product.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                p.order_count,
                loss_withdrawal = (p.amount_sales * withdrawpercent).ToString("N2"),

                cost_total = p.cost_total.ToString("N2"),
                cost_shipping = p.cost_shipping.ToString("N2"),
                amount_refund = p.amount_refund.ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (100 * p.profit_rate).ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                noshippingcount = p.noshippingcount.ToString("N0"),
                cost_logistics = p.cost_logistics.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    countM.platform_type,
                    countM.seller_account,
                    countM.website,
                    amount_sales = countM.amount_sales.ToString("N2"),
                    amount_product = countM.amount_product.ToString("N2"),
                    cost_product = countM.cost_product.ToString("N2"),
                    cost_platform_fee = countM.cost_platform_fee.ToString("N2"),
                    cost_package = countM.cost_package.ToString("N2"),
                    cost_paypal_fee = countM.cost_paypal_fee.ToString("N2"),
                    cost_first = countM.cost_first.ToString("N2"),
                    countM.order_count,
                    loss_withdrawal = countM.loss_withdrawal.ToString("N2"),
                    cost_total = countM.cost_total.ToString("N2"),
                    cost_shipping = countM.cost_shipping.ToString("N2"),
                    amount_refund = countM.amount_refund.ToString("N2"),
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),
                    profit_total = countM.profit_total.ToString("N2"),
                    profit_rate = (100 * countM.profit_rate).ToString("N2"),
                    cost_tail = countM.cost_tail.ToString("N2"),
                    cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                    noshippingcount = countM.noshippingcount.ToString("N0"),
                    cost_logistics = countM.cost_logistics.ToString("N2"),
                }
            });
        }

        /// <summary>
        /// 按站点显示Ebay统计报表
        /// </summary>
        /// <returns></returns>
        public ActionResult EbayStatisticsByWebsite()
        {
            return View();
        }

        /// <summary>
        /// 按站点显示Ebay统计报表
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="website">站点</param>
        /// <param name="selleraccount">销售帐号</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string EbayStatisticsByWebsiteJson(BtTableParameter request,string platform,string website, string selleraccount, DateTime start, DateTime end, string warehousetype, string warehousecode,string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var _services = new Services.OrdersServices();
            var objwithdraw = new Services.PlatformSiteServices().GetPlatformLossWithdraw().Where(a => a.english_name == platform).FirstOrDefault();
            var withdrawpercent = 0.0000M;
            if (objwithdraw != null && objwithdraw.Loss_withdrawal_percent.HasValue)
            {
                withdrawpercent = objwithdraw.Loss_withdrawal_percent.Value;
            }

            var obj = _services.ListEbayStatisticsByWebsite(request, platform, website,selleraccount,start,end,warehousetype,warehousecode,companyid,ref total,skucategoryids);

            var countM = _services.ListEbayStatisticsCount(platform,website, selleraccount, start, end, warehousetype, warehousecode,companyid, skucategoryids);

            countM.website = "总计：";
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.loss_withdrawal = countM.amount_sales * (withdrawpercent);
            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_shipping = Math.Round(countM.cost_shipping, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.profit_rate = countM.amount_product > 0 ? Math.Round((countM.profit_total / countM.amount_product), 2, MidpointRounding.AwayFromZero) : 0;
            countM.cost_tail = Math.Round(countM.cost_tail, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);

            var list = obj.Select(p => new
            {
                p.platform_type,
                p.seller_account,
                p.website,
                amount_sales = p.amount_sales.ToString("N2"),
                amount_product = p.amount_product.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                p.order_count,
                loss_withdrawal = (p.amount_sales * withdrawpercent).ToString("N2"),

                cost_total = p.cost_total.ToString("N2"),
                cost_shipping = p.cost_shipping.ToString("N2"),
                amount_refund = p.amount_refund.ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (100 * p.profit_rate).ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                noshippingcount = p.noshippingcount.ToString("N0")
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    countM.platform_type,
                    countM.seller_account,
                    countM.website,
                    amount_sales = countM.amount_sales.ToString("N2"),
                    amount_product = countM.amount_product.ToString("N2"),
                    cost_product = countM.cost_product.ToString("N2"),
                    cost_platform_fee = countM.cost_platform_fee.ToString("N2"),
                    cost_package = countM.cost_package.ToString("N2"),
                    cost_paypal_fee = countM.cost_paypal_fee.ToString("N2"),
                    cost_first = countM.cost_first.ToString("N2"),
                    countM.order_count,
                    loss_withdrawal = countM.loss_withdrawal.ToString("N2"),
                    cost_total = countM.cost_total.ToString("N2"),
                    cost_shipping = countM.cost_shipping.ToString("N2"),
                    amount_refund = countM.amount_refund.ToString("N2"),
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),
                    profit_total = countM.profit_total.ToString("N2"),
                    profit_rate = (100 * countM.profit_rate).ToString("N2"),
                    cost_tail = countM.cost_tail.ToString("N2"),
                    cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                    noshippingcount = countM.noshippingcount.ToString("N0"),
                }
            });
        }

        /// <summary>
        /// Ebay订单流水，按itemid进行搜索
        /// </summary>
        /// <returns></returns>
        public ActionResult ListEbayOrder()
        {
            return View();
        }

        /// <summary>
        /// Ebay订单流水数据
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="account">帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">平台订单号</param>
        /// <param name="sku">sku编码</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListEbayOrderJson(BtTableParameter parameter, string account, string website, DateTime? start, DateTime? end, string orderno, string sku,string itemid,string skucategoryid, decimal? rate_start, decimal? rate_end)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var obj = service.ListOrders(parameter, "Ebay", website, account, start, end, orderno, sku, companyid, ref total, skucategoryid,rate_start,rate_end, itemid);

            var objItemid = service.GetOrderItemId(obj.Select(a => a.bailun_order_id).ToList());

            var countM = service.ListOrdersCount("Ebay", website, account, start, end, orderno, sku, companyid, skucategoryid,rate_start,rate_end, itemid);
            countM.amount_adjustment = Math.Round(countM.amount_adjustment, 2, MidpointRounding.AwayFromZero);
            countM.amount_gift_wrap = Math.Round(countM.amount_gift_wrap, 2, MidpointRounding.AwayFromZero);
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.amount_shipping = Math.Round(countM.amount_shipping, 2, MidpointRounding.AwayFromZero);
            countM.amount_tax = Math.Round(countM.amount_tax, 2, MidpointRounding.AwayFromZero);
            countM.amount_total = Math.Round(countM.amount_total, 2, MidpointRounding.AwayFromZero);

            countM.cost_estimate_logistics = Math.Round(countM.cost_estimate_logistics, 2, MidpointRounding.AwayFromZero);
            countM.cost_fba_fee = Math.Round(countM.cost_fba_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_promotion = Math.Round(countM.cost_promotion, 2, MidpointRounding.AwayFromZero);
            countM.cost_refund_commisson = Math.Round(countM.cost_refund_commisson, 2, MidpointRounding.AwayFromZero);
            countM.cost_shipping = Math.Round(countM.cost_shipping, 2, MidpointRounding.AwayFromZero);
            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.profit_oms = Math.Round((countM.profit_oms-countM.cost_handle_platform-countM.cost_handle_bailun), 2, MidpointRounding.AwayFromZero);
            countM.website = "总计：";


            var list = obj.Select(p => new {
                p.origin_order_id,
                p.platform_type,
                p.website,
                p.seller_account,
                p.platform_order_type,
                p.bailun_order_status,
                p.bailun_payment_status,
                p.bailun_shipping_status,
                p.order_currency,
                amount_total = p.amount_total > 0 ? p.amount_total.ToString("N2") : "0",
                amount_shipping = p.amount_shipping > 0 ? p.amount_shipping.ToString("N2") : "0",
                amount_product = p.amount_product > 0 ? p.amount_product.ToString("N2") : "0",
                amount_adjustment = p.amount_adjustment > 0 ? p.amount_adjustment.ToString("N2") : "0",
                cost_promotion = p.cost_promotion > 0 ? p.cost_promotion.ToString("N2") : "0",
                cost_platform_fee = p.cost_platform_fee > 0 ? p.cost_platform_fee.ToString("N2") : "0",
                cost_product = p.cost_product > 0 ? p.cost_product.ToString("N2") : "0",
                cost_first = p.cost_first > 0 ? p.cost_first.ToString("N2") : "0",
                cost_package = p.cost_package > 0 ? p.cost_package.ToString("N2") : "0",
                cost_fba_fee = p.cost_fba_fee > 0 ? p.cost_fba_fee.ToString("N2") : "0",
                cost_total = p.cost_total > 0 ? p.cost_total.ToString("N2") : "0",
                profit_total = p.profit_total > 0 ? p.profit_total.ToString("N2") : "0",
                create_time = p.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                order_update_time = p.order_update_time.ToString("yyyy-MM-dd HH:mm:ss"),
                p.salecount,
                profit_rate = (p.amount_total>0?((p.profit_oms/p.amount_total) * 100).ToString("N2"):"0"),
                item_id = objItemid.Where(a=>a.bailun_order_id==p.bailun_order_id).FirstOrDefault()?.item_id,
                profit_oms = (p.profit_oms-p.cost_handle_bailun-p.cost_handle_platform).ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2"),
                cost_logistics = p.cost_logistics.ToString("N2"),
            });

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

        /// <summary>
        /// 导出Ebay所有订单流水
        /// </summary>
        /// <param name="account"></param>
        /// <param name="website"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="orderno"></param>
        /// <param name="sku"></param>
        /// <param name="itemid"></param>
        /// <returns></returns>
        public ActionResult ExportEbayOrders(string account, string website, DateTime? start, DateTime? end, string orderno, string sku, string itemid,string skucategoryid, decimal? rate_start, decimal? rate_end)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var obj = service.ListOrders(new BtTableParameter() { limit=100000,offset=0}, "Ebay", website, account, start, end, orderno, sku, companyid, ref total, skucategoryid,rate_start,rate_end,itemid);

            var objItemid = service.GetOrderItemId(obj.Select(a => a.bailun_order_id).ToList());

            var colNames = new List<string> {"平台订单号","itemid","平台站点", "卖家帐号", "订单状态",
                                             "付款状态", "发货状态","币种","订单总金额","运费",
                                             "商品金额","调整金额","促销费","平台费","产品成本",
                                             "头程费","包装费","百伦处理费","尾程费","平台操作费",
                                             "总支出","销售额","利润","创建时间","更新时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.origin_order_id + "|" + (objItemid.Where(a => a.bailun_order_id == item.bailun_order_id).FirstOrDefault()?.item_id) + "|" + item.website + "|" + item.seller_account + "|" + item.bailun_order_status + "|" +
                    item.bailun_payment_status + "|" + item.bailun_shipping_status + "|" + item.order_currency + "|" + item.amount_total + "|" + item.amount_shipping + "|" +
                    item.amount_product + "|" + item.amount_adjustment + "|" + item.cost_promotion + "|" + item.cost_platform_fee + "|" + item.cost_product + "|" +
                    item.cost_first + "|" + item.cost_package + "|" + item.cost_handle_bailun + "|" + item.cost_logistics + "|" + item.cost_handle_platform + "|" +
                    item.cost_total + "|" + item.amount_sales + "|" + (item.profit_oms - item.cost_handle_bailun - item.cost_handle_platform) + "|" + (item.create_time.ToString("yyyy-MM-dd HH:mm:ss")) + "|" + item.order_update_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "Ebay所有订单流水" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// Ebay上架费
        /// </summary>
        /// <returns></returns>
        public ActionResult EbayPutAwayFee()
        {
            return View();
        }

        [BailunAuthentication(LoginMode.Enforce)]
        public string EbayPutAwayFeeJson(BtTableParameter parameter,DateTime? start,DateTime? end,string orderno,string sku,string skucategoryid,string account)
        {
            var _service = new Services.OrdersServices();
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;

            var feeType = new string[] {
                "BuyItNowFee",
                "CreditGalleryPlus",
                "CreditInsertion",
                "CreditSMBasicPro",
                "ExtendedDurationFee",
                "ExtendedDurationFeeCredit",
                "FeeAuctionEndEarly",
                "FeeBold",
                "FeeFinalValueShipping",
                "FeeGalleryPlus",
                "FeeLargePicture",
                "FeeSchedule",
                "PrivateListing",
                "SubscriptionSMBasic",
                "SubscriptionSMBasicPro",
                "SubscriptioneBayStores",
                "SubtitleFee",
                "SubtitleFeeCredit",
                "CrediteBayStores"

            };

            var obj = _service.ListEbayFee(parameter, companyid, start, end, ref total, feeType,orderno,account,"");

            var countObj = _service.EbayFeeCount(companyid, start, end, feeType, orderno,account,false,"");

            var list = obj.Select(a => new {
                a.id,
                a.account_entry_type,
                a.description,
                gmt_date = a.gmt_date.HasValue?a.gmt_date.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
                gross_amount = a.gross_amount.ToString("N2"),
                a.item_id,
                net_amount = a.net_amount.ToString("N2"),
                a.vat_percent,
                a.order_line_id,
                a.currency,
                a.exchange_rate,
                gross_amount_rmb = a.gross_amount_rmb.ToString("N2"),
                a.account_name
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    order_line_id = "总计",
                    gross_amount = countObj.gross_amount.ToString("N2"),
                    gross_amount_rmb = countObj.gross_amount_rmb.ToString("N2")
                }
            });

        }

        /// <summary>
        /// Ebay广告费
        /// </summary>
        /// <returns></returns>
        public ActionResult EbayADFee()
        {
            return View();
        }

        /// <summary>
        /// Ebay广告费
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="orderno"></param>
        /// <param name="sku"></param>
        /// <param name="skucategoryid"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string EbayADFeeJson(BtTableParameter parameter, DateTime? start, DateTime? end, string orderno, string sku, string skucategoryid, string account,string itemid)
        {
            var _service = new Services.OrdersServices();
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;

            var feeType = new string[] {
                "FeeAd"
            };

            var obj = _service.ListEbayFee(parameter, companyid, start, end, ref total, feeType, orderno, account,itemid);

            var countObj = _service.EbayFeeCount(companyid, start, end, feeType, orderno, account,false,itemid);

            var list = obj.Select(a => new {
                a.id,
                a.account_entry_type,
                a.description,
                gmt_date = a.gmt_date.HasValue ? a.gmt_date.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                gross_amount = a.gross_amount.ToString("N2"),
                a.item_id,
                net_amount = a.net_amount.ToString("N2"),
                a.vat_percent,
                a.order_line_id,
                a.currency,
                a.exchange_rate,
                gross_amount_rmb = a.gross_amount_rmb.ToString("N2"),
                a.account_name
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    order_line_id = "总计",
                    gross_amount = countObj.gross_amount.ToString("N2"),
                    gross_amount_rmb = countObj.gross_amount_rmb.ToString("N2")
                },
                companyid=companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportEbayAdFee", HttpContextHelper.Current.User.GetUid()),
            });

        }

        /// <summary>
        /// 导出Ebay广告费
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="orderno">订单号</param>
        /// <param name="sku">sku编码</param>
        /// <param name="skucategoryid">sku分类id</param>
        /// <param name="account">帐号</param>
        /// <param name="itemid">itemid</param>
        /// <returns></returns>
        public ActionResult ExportEbayAdFee(DateTime? start, DateTime? end, string orderno, string sku, string skucategoryid, string account, string itemid,int companyid)
        {
            var _service = new Services.OrdersServices();
            var total = 0;

            var feeType = new string[] {
                "FeeAd"
            };

            var obj = _service.ListEbayFee(new BtTableParameter { offset=0,limit=0}, companyid, start, end, ref total, feeType, orderno, account,itemid);

            var colNames = new List<string> {"销售帐号","费用类型","费用名称","总费用","币种","汇率","RMB金额","item_id","记录时间"};

            var listVal = new List<string>();
            foreach (var item in obj)
            {
                listVal.Add(
                    item.account_name + "|" + item.account_entry_type + "|" + item.description + "|" + item.gross_amount + "|" + item.currency + "|" +
                    item.exchange_rate + "|" + item.gross_amount_rmb + "|" + item.item_id + "|" + item.gmt_date.Value.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = " Ebay广告费" + 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>
        /// Ebay汇损费
        /// </summary>
        /// <returns></returns>
        public ActionResult ExchangeLossFee()
        {
            return View();
        }

        /// <summary>
        /// Ebay汇损费
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ExchangeLossFeeJson(BtTableParameter parameter, DateTime? start, DateTime? end, string selleraccount)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var _service = new Services.OrdersServices();
            var total = 1;

            var obj = _service.ListExchangeLoss(parameter, selleraccount, start,end,ref total, companyid);

            var countObj = _service.ListExchangeLossCount(selleraccount, start, end,companyid);

            var list = obj.Select(a => new {
                amount_sales = a.amount_sales.ToString("N2"),
                //gross_amount = a.gross_amount.ToString("N2"),
                a.seller_account,
                exchangeloss_rate = 2.5,
                //exchangeloss_amount = ((a.amount_sales-a.gross_amount)*(decimal)0.025).ToString("N2")
                exchangeloss_amount = (a.amount_sales*(decimal)0.025).ToString("N2"),
                
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    seller_account = "总计",
                    amount_sales = countObj.amount_sales.ToString("N2"),
                    //gross_amount = countObj.gross_amount.ToString("N2"),
                    exchangeloss_amount = (countObj.amount_sales * (decimal)0.025).ToString("N2")
                }
            });
        }

        /// <summary>
        /// 内部编码利润
        /// </summary>
        /// <returns></returns>
        public ActionResult ListEbayInnerCodeProfit()
        {
            return View();
        }

        /// <summary>
        /// 内部编码维度
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="code"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListEbayInnerCodeProfitJson(BtTableParameter parameter, DateTime start, DateTime end, string code, string orderno)
        {
            var companyid = HttpContextHelper.Current.User.GetCompanyId();
            
            var total = 0;
            var _service = new Services.OrdersServices();
            var obj = _service.ListEbayInnerCodeProfit(parameter, start, end, code, orderno, ref total);
            var objCount = _service.ListEbayInnerCodeProfitCount(start, end, code, orderno);

            var list = obj.Select(a => new {
                amount_sales = a.amount_sales.ToString("N2"),
                a.bailun_order_status,
                bailun_sku_quantity_ordered = a.bailun_sku_quantity_ordered.ToString("N0"),
                cost_first = a.cost_first.ToString("N2"),
                cost_handle_bailun = a.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = a.cost_handle_platform.ToString("N2"),
                cost_logistics = a.cost_logistics.ToString("N2"),
                cost_paypal_fee = a.cost_paypal_fee.ToString("N2"),
                cost_platform_fee = a.cost_platform_fee.ToString("N2"),


                cost_product = a.cost_product.ToString("N2"),
                cost_total = a.cost_total.ToString("N2"),
                create_time = a.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                order_update_time = a.order_update_time.ToString("yyyy-MM-dd HH:mm:ss"),
                a.origin_order_id,
                a.pay_status,
                a.platform_type,
                a.product_inner_code,
                profit_rate = (a.profit_rate*100).ToString("N2"),
                profit_total = a.profit_total.ToString("N2"),
                a.seller_account,
                a.shipping_status,
                a.website,
                paid_time = a.paid_time.ToString("yyyy-MM-dd HH:mm:ss")

            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    shipping_status = "合计",
                    amount_sales = objCount.amount_sales.ToString("N2"),
                    bailun_sku_quantity_ordered = objCount.bailun_sku_quantity_ordered.ToString("N0"),
                    cost_first = objCount.cost_first.ToString("N2"),
                    cost_handle_bailun = objCount.cost_handle_bailun.ToString("N2"),
                    cost_handle_platform = objCount.cost_handle_platform.ToString("N2"),
                    cost_logistics = objCount.cost_logistics.ToString("N2"),
                    cost_paypal_fee = objCount.cost_paypal_fee.ToString("N2"),
                    cost_platform_fee = objCount.cost_platform_fee.ToString("N2"),


                    cost_product = objCount.cost_product.ToString("N2"),
                    cost_total = objCount.cost_total.ToString("N2"),
                    profit_rate = (objCount.profit_rate * 100).ToString("N2"),
                    profit_total = objCount.profit_total.ToString("N2")
                },
                companyid = companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportEbayInnerCodeProfit", HttpContextHelper.Current.User.GetUid()),
            });

        }

        /// <summary>
        /// 导出内部商品编码利润
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="code"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public ActionResult ExportEbayInnerCodeProfit(DateTime start, DateTime end, string code, string orderno)
        {
            var _service = new Services.OrdersServices();

            var obj = _service.ExportEbayInnerCodeProfit(start, end,code,orderno);
            var list = obj.Select(a => new {
                amount_sales = a.amount_sales.ToString("N2"),
                a.bailun_order_status,
                bailun_sku_quantity_ordered = a.bailun_sku_quantity_ordered.ToString("N0"),
                cost_first = a.cost_first.ToString("N2"),
                cost_handle_bailun = a.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = a.cost_handle_platform.ToString("N2"),
                cost_logistics = a.cost_logistics.ToString("N2"),
                cost_paypal_fee = a.cost_paypal_fee.ToString("N2"),
                cost_platform_fee = a.cost_platform_fee.ToString("N2"),


                cost_product = a.cost_product.ToString("N2"),
                cost_total = a.cost_total.ToString("N2"),
                create_time = a.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                order_update_time = a.order_update_time.ToString("yyyy-MM-dd HH:mm:ss"),
                a.origin_order_id,
                a.pay_status,
                a.platform_type,
                a.product_inner_code,
                profit_rate = (a.profit_rate * 100).ToString("N2"),
                profit_total = a.profit_total.ToString("N2"),
                a.seller_account,
                a.shipping_status,
                a.website,
                paid_time = a.paid_time.ToString("yyyy-MM-dd HH:mm:ss")
            });

            var colNames = new List<string> {"内部编码","平台单号","平台类型", "站点", "销售帐号",
                                             "订单状态", "付款状态","发货状态","销售额","平台费",
                                             "产品成本","头程费","尾程费","百伦处理费","平台操作费",
                                             "paypal费","总支出","销售数量","利润","利润率",
                                             "创建时间","付款时间","更新时间"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.product_inner_code + "|" + item.origin_order_id + "|" + item.platform_type + "|" + item.website + "|" + item.seller_account + "|" +
                    item.bailun_order_status + "|" + item.pay_status+"|"+item.shipping_status+"|"+item.amount_sales+"|"+item.cost_platform_fee+"|"+
                    item.cost_product+"|"+item.cost_first+"|"+item.cost_logistics+"|"+item.cost_handle_bailun+"|"+item.cost_handle_platform+"|"+
                    item.cost_paypal_fee+"|"+item.cost_total+"|"+item.bailun_sku_quantity_ordered+"|"+item.profit_total+"|"+item.profit_rate+"|"+
                    item.create_time+"|"+item.paid_time+"|"+item.order_update_time
                    );
            }

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

        #endregion

        #region 平台利润

        /// <summary>
        /// 平台利润统计
        /// </summary>
        /// <returns></returns>
        public ActionResult PlatformProfitCount()
        {
            return View();
        }

        /// <summary>
        /// 平台利润统计数据
        /// </summary>
        /// <param name="platform">平台类型</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult PlatformProfitCountJson(string platform,string website, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, string currency, string skucategoryids)
        {
            var _service = new Services.OrdersServices();
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();

            var result = new List<Models.Orders.dc_base_oms_sku>();

            var dtstart = start;
            var dtend = end;
            var ebayADFee = new dc_base_finance_ebay();  //Ebay 广告费
            var ebayPutAway = new dc_base_finance_ebay();   //Ebay 上架费
            var listRefund = new List<Models.Orders.dc_base_oms_order>();
            var ADfeeType = new string[] {
                    "FeeAd"
                };
            var PutAwayFeeType = new string[] {
                    "BuyItNowFee",
                    "CreditGalleryPlus",
                    "CreditInsertion",
                    "CreditSMBasicPro",
                    "ExtendedDurationFee",
                    "ExtendedDurationFeeCredit",
                    "FeeAuctionEndEarly",
                    "FeeBold",
                    "FeeFinalValueShipping",
                    "FeeGalleryPlus",
                    "FeeLargePicture",
                    "FeeSchedule",
                    "PrivateListing",
                    "SubscriptionSMBasic",
                    "SubscriptionSMBasicPro",
                    "SubscriptioneBayStores",
                    "SubtitleFee",
                    "SubtitleFeeCredit",
                    "CrediteBayStores"
                };


            if (shipstart.HasValue || shipend.HasValue)
            {
                result = _service.ListPlatformProfitByShipTime(platform,website, start, end, shipstart, shipend, currency.ToUpper() == "USD", companyid, skucategoryids);

                var fbaResult = _service.ListPlatformProfit(string.IsNullOrEmpty(platform) ? "FBA" : "",website, null,null,null, null, currency.ToUpper() == "USD", companyid, skucategoryids, shipstart, shipend);

                result.AddRange(fbaResult);

                dtstart = shipstart;
                dtend = shipend;
                listRefund = _service.ListPlatformRefund(dtstart, dtend, companyid, platform, website, currency.ToUpper() == "USD",false);  //不包含未发货的退款金额
            }
            else
            {
                result = _service.ListPlatformProfit(platform,website,start, end, shipstart, shipend, currency.ToUpper() == "USD", companyid, skucategoryids);
                listRefund = _service.ListPlatformRefund(dtstart, dtend, companyid, platform, website, currency.ToUpper() == "USD",true);   //包含未发货的退款金额
            }

            ebayADFee = _service.EbayFeeCount(companyid, dtstart, dtend, ADfeeType, "", "", currency.ToUpper() == "USD","");
            ebayPutAway = _service.EbayFeeCount(companyid, dtstart, dtend, PutAwayFeeType, "", "", currency.ToUpper() == "USD","");
            var amazonAD = _service.ListAmazonADSkuCount("", dtstart, dtend, companyid, currency.ToUpper() == "USD");

            var wishAD = _service.ListWishADCount(companyid, null, dtstart, dtend, currency.ToUpper() == "USD");

            var aliexpressAD = _service.ListAliexpressADCount(companyid, "", dtstart, dtend, currency.ToUpper() == "USD");

             foreach (var item in result)
            {
                item.adfee = 0;
                item.putawayfee = 0;

                //利润减去广告费和刊登费
                if (item.platform_type.ToLower() == "ebay")
                {
                    item.adfee = ebayADFee != null ? ebayADFee.gross_amount_rmb : 0;
                    item.putawayfee = ebayPutAway != null ? ebayPutAway.gross_amount_rmb : 0;

                    item.profit_total = (item.profit_total - (item.adfee ?? 0) - (item.putawayfee ?? 0));
                    item.profit_rate = item.amount_sales != 0?Math.Round((item.profit_total / item.amount_sales), 2):0;
                }

                else if (item.platform_type.ToLower() == "fba")  //亚马逊广告费
                {
                    item.adfee = amazonAD != null ? amazonAD.cost_rmb : 0;

                    item.profit_total = (item.profit_total - item.adfee ?? 0);
                    item.profit_rate = item.amount_sales != 0 ? Math.Round((item.profit_total / item.amount_sales), 2):0;
                }

                else if (item.platform_type.ToLower() == "wish")   //Wish广告费
                {
                    item.adfee = wishAD != null ? wishAD.daily_total_campaign_spend : 0;
                    item.profit_total = (item.profit_total - item.adfee ?? 0);
                    item.profit_rate = item.amount_sales != 0 ? Math.Round((item.profit_total / item.amount_sales), 2):0;
                }

                else if (item.platform_type.ToLower() == "aliexpress")  //速卖通广告费
                {
                    item.adfee = aliexpressAD != null ? aliexpressAD.cost_fee : 0;
                    item.profit_total = (item.profit_total - item.adfee ?? 0);
                    item.profit_rate = item.amount_sales != 0 ? Math.Round((item.profit_total / item.amount_sales), 2):0;
                }

                item.amount_refund = 0;
                item.amount_refund_rate = 0;
                var objRefund = listRefund.Where(a => a.platform_type.ToLower() == item.platform_type.ToLower()).FirstOrDefault();
                if (objRefund != null)
                {
                    item.amount_refund = objRefund.amount_refund;
                    item.amount_refund_rate = (item.amount_sales > 0 ? item.amount_refund / item.amount_sales : 0);
                }

                //利润减去退款
                item.profit_total = (item.profit_total - item.amount_refund);
                item.profit_rate = item.amount_sales!=0?Math.Round((item.profit_total / item.amount_sales), 2):0;

            }

            if (result.Count > 0)
            {
                var m = new Models.Orders.dc_base_oms_sku
                {
                    platform_type = "总计(" + currency + ")",
                    order_count = result.Sum(a => a.order_count),
                    amount_sales = result.Sum(a => a.amount_sales),
                    customerprice = result.Sum(a => a.customerprice) / result.Count,
                    cost_platform_fee = result.Sum(a => a.cost_platform_fee),
                    profit_total = result.Sum(a => a.profit_total),
                    profit_rate = result.Sum(a => a.amount_sales) > 0 ? result.Sum(a => a.amount_sales) / result.Sum(a => a.amount_sales) : 0,
                    amount_refund = result.Sum(a => a.amount_refund),
                    amount_refund_rate = result.Sum(a => a.amount_sales) > 0 ? (result.Sum(a => a.amount_refund) / result.Sum(a => a.amount_sales) * 100) : 0,
                    cost_first = result.Sum(a => a.cost_first),
                    cost_handle_bailun = result.Sum(a => a.cost_handle_bailun),
                    cost_handle_platform = result.Sum(a => a.cost_handle_platform),
                    cost_tail = result.Sum(a => a.cost_tail),
                    amount_prepaid = result.Sum(a => a.amount_prepaid),
                    cost_product = result.Sum(a => a.cost_product),
                    noshippingcount = result.Sum(a => a.noshippingcount),
                    cost_fba_fee = result.Sum(a => a.cost_fba_fee),
                    cost_paypal_fee = result.Sum(a => a.cost_paypal_fee),
                    adfee = result.Sum(a => a.adfee),
                    putawayfee = result.Sum(a => a.putawayfee)
                };
                result.Add(m);
            }



            var list = result.Select(p => new {
                p.platform_type,
                customerprice = (p.amount_sales / p.order_count).ToString("N2"),
                order_count = p.order_count.ToString("N0"),
                cost_platform_fee = p.cost_platform_fee > 0 ? p.cost_platform_fee.ToString("N2") : "0",
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (p.amount_sales > 0 ? p.profit_total * 100 / p.amount_sales : 0).ToString("N2"),
                amount_refund = p.amount_refund.ToString("N2"),
                amount_refund_rate = p.amount_sales > 0 ? (p.amount_refund * 100 / p.amount_sales).ToString("N4") : "0",
                amount_sales = p.amount_sales.ToString("N2"),

                cost_first = p.cost_first.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                noshippingcount = p.noshippingcount.ToString("N0"),
                cost_fba_fee = p.cost_fba_fee.ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),

                adfee = (p.adfee ?? 0).ToString("N2"),
                putawayfee = (p.putawayfee ?? 0).ToString("N2"),

            }).ToList();

            var objEbay = list.Where(a => a.platform_type == "Ebay").FirstOrDefault();
            if (objEbay != null && list.Count > 3)
            {
                list.Remove(objEbay);
                list.Insert(3, objEbay);
            }

            return Json(list);
        }

        /// <summary>
        /// 平台利润，按站点
        /// </summary>
        /// <param name="platform">平台编码</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        public ActionResult PlatformProfitCountByWebSite(string platform, DateTime? start, DateTime? end)
        {
            ViewBag.platform = platform;
            ViewBag.start = start.HasValue ? start.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.end = end.HasValue ? end.Value.ToString("yyyy-MM-dd") : "";

            return View();
        }

        /// <summary>
        /// 平台利润，按站点
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string PlatformProfitCountByWebSiteJson(string platform, DateTime? start, DateTime? end, BtTableParameter parameter)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var result = service.ListPlatformProfitByWebSite(platform, start, end, parameter, companyid, ref total);

            var countM = service.ListPlatformProfitByWebSiteCount(platform, start, end, parameter, companyid, ref total);
            countM.website = "合计：";
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_platform = Math.Round(countM.cost_handle_platform, 2, MidpointRounding.AwayFromZero);
            countM.cost_tail = Math.Round(countM.cost_tail, 2, MidpointRounding.AwayFromZero);
            countM.customerprice = Math.Round(countM.customerprice, 2, MidpointRounding.AwayFromZero);
            countM.platformfee = Math.Round(countM.platformfee, 2, MidpointRounding.AwayFromZero);
            countM.profit = Math.Round(countM.profit, 2, MidpointRounding.AwayFromZero);
            countM.returnamount = Math.Round(countM.returnamount, 2, MidpointRounding.AwayFromZero);
            countM.saleamount = Math.Round(countM.saleamount, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.returnamountrate = Math.Round(countM.returnamount * 100 / countM.saleamount, 2, MidpointRounding.AwayFromZero);
            countM.profitrate = Math.Round(countM.profit * 100 / countM.saleamount, 2, MidpointRounding.AwayFromZero);

            var list = result.Select(p => new {
                p.platform,
                customerprice = p.customerprice > 0 ? p.customerprice.ToString("N2") : "0",
                p.ordercount,
                platformfee = p.platformfee > 0 ? p.platformfee.ToString("N2") : "0",
                profit = p.profit > 0 ? p.profit.ToString("N2") : "0",
                profitrate = p.profitrate > 0 ? (p.profitrate * 100).ToString("N2") : "0",
                returnamount = p.returnamount > 0 ? p.returnamount.ToString("N2") : "0",
                returnamountrate = p.returnamountrate > 0 ? (p.returnamountrate * 100).ToString("N2") : "0",
                saleamount = p.saleamount > 0 ? p.saleamount.ToString("N2") : "0",

                cost_first = p.cost_first > 0 ? p.cost_first.ToString("N2") : "0",
                cost_handle_bailun = p.cost_handle_bailun > 0 ? p.cost_handle_bailun.ToString("N2") : "0",
                cost_handle_platform = p.cost_handle_platform > 0 ? p.cost_handle_platform.ToString("N2") : "0",
                cost_tail = p.cost_tail > 0 ? p.cost_tail.ToString("N2") : "0",
                p.website,
                amount_prepaid = p.amount_prepaid > 0 ? p.amount_prepaid.ToString("N2") : "0",
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    countM.website,
                    cost_first = countM.cost_first.ToString("N2"),
                    cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                    cost_handle_platform = countM.cost_handle_platform.ToString("N2"),
                    cost_tail = countM.cost_tail.ToString("N2"),
                    customerprice = countM.customerprice.ToString("N2"),
                    platformfee = countM.platformfee.ToString("N2"),
                    profit = countM.profit.ToString("N2"),
                    returnamount = countM.returnamount.ToString("N2"),
                    saleamount = countM.saleamount.ToString("N2"),
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),
                    returnamountrate = countM.returnamountrate.ToString("N2"),
                    profitrate = countM.profitrate.ToString("N2"),
                    countM.ordercount,
                }
            });
        }


        /// <summary>
        /// 订单明细列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ListOrderDetail(string platform, string website, string account, DateTime? start, DateTime? end, string orderno, int? showsingle, string col, string coltitle, DateTime? shipstart, DateTime? shipend)
        {

            ViewBag.platform = platform;
            ViewBag.website = website;
            ViewBag.start = start.HasValue ? start.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.end = end.HasValue ? end.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.orderno = orderno;
            ViewBag.account = account;
            ViewBag.showsingle = (showsingle ?? 0);
            ViewBag.col = col;
            ViewBag.coltitle = coltitle;

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

            return View();
        }

        /// <summary>
        /// 订单明细列表 数据
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="platform">平台类型</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">百伦订单号</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListOrderDetailJson(BtTableParameter parameter, string platform, string website, string account, DateTime? start, DateTime? end, string orderno, DateTime? shipstart, DateTime? shipend, decimal? rate_start, decimal? rate_end)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var obj = service.ListPlatformProfitOrders(parameter, platform, website, account, start, end, shipstart, shipend, orderno, companyid, ref total,rate_start,rate_end);

            var countM = service.ListPlatformProfitOrdersCount(platform, website, account, start, end, shipstart, shipend, orderno, companyid, rate_start, rate_end);

            countM.bailun_order_id = "总计";
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);
            countM.amount_total = Math.Round((countM.amount_total), 2, MidpointRounding.AwayFromZero);
            countM.amount_product = Math.Round((countM.amount_product), 2, MidpointRounding.AwayFromZero);
            countM.amount_shipping = Math.Round((countM.amount_shipping), 2, MidpointRounding.AwayFromZero);
            countM.amount_tax = Math.Round((countM.amount_tax), 2, MidpointRounding.AwayFromZero);
            countM.amount_adjustment = platform=="Aliexpress"?0:(Math.Round((countM.amount_adjustment), 2, MidpointRounding.AwayFromZero));  //速卖通的调整费改为0
            countM.amount_gift_wrap = Math.Round((countM.amount_gift_wrap), 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round((countM.amount_refund), 2, MidpointRounding.AwayFromZero);

            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_promotion = Math.Round(countM.cost_promotion, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_shipping = Math.Round(countM.cost_shipping, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.cost_fba_fee = Math.Round(countM.cost_fba_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_refund_commisson = Math.Round(countM.cost_refund_commisson, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_platform = Math.Round(countM.cost_handle_platform, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.cost_tail = Math.Round(countM.cost_tail, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.profit_rate = countM.amount_sales > 0 ? Math.Round((countM.profit_total / countM.amount_sales) * 100, 2, MidpointRounding.AwayFromZero) : 0;
            countM.cost_logistics = Math.Round(countM.cost_logistics, 2, MidpointRounding.AwayFromZero);

            var list = obj.Select(p => new
            {
                p.origin_order_id,
                p.bailun_order_id,
                p.platform_type,
                p.website,
                p.seller_account,
                p.order_currency,

                amount_total = p.amount_total.ToString("N2"),
                amount_sales = p.amount_sales.ToString("N2"),
                amount_product = p.amount_product.ToString("N2"),
                amount_shipping = p.amount_shipping.ToString("N2"),
                amount_tax = p.amount_tax.ToString("N2"),
                amount_adjustment = p.platform_type=="Aliexpress"?"0":p.amount_adjustment.ToString("N2"),
                amount_gift_wrap = p.amount_gift_wrap.ToString("N2"),
                amount_refund = p.amount_refund.ToString("N2"),

                cost_total = p.cost_total.ToString("N2"),
                cost_promotion = p.cost_promotion.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_shipping = p.cost_shipping.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_fba_fee = p.cost_fba_fee.ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),
                cost_refund_commisson = p.cost_refund_commisson.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (p.profit_rate * 100).ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),

                create_time = p.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                paid_time = p.paid_time.ToString("yyyy-MM-dd HH:mm:ss"),


                cost_logistics = p.cost_logistics.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list, count_row = countM, companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportListOrderDetail", HttpContextHelper.Current.User.GetUid())
            });

        }

        public ActionResult ExportListOrderDetail(string platform, string website, string account, DateTime? start, DateTime? end, string orderno, DateTime? shipstart, DateTime? shipend, decimal? rate_start, decimal? rate_end,int? companyid)
        {
            //var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var service = new Services.OrdersServices();
            var obj = service.ListPlatformProfitOrders(new BtTableParameter { offset = 1, limit = 500000 }, platform, website, account, start, end, shipstart, shipend, orderno, companyid, ref total, rate_start, rate_end);

            var list = obj.Select(p => new
            {
                p.origin_order_id,
                p.bailun_order_id,
                p.platform_type,
                p.website,
                p.seller_account,
                p.order_currency,

                amount_total = p.amount_total.ToString("N2"),
                amount_sales = p.amount_sales.ToString("N2"),
                amount_product = p.amount_product.ToString("N2"),
                amount_shipping = p.amount_shipping.ToString("N2"),
                amount_tax = p.amount_tax.ToString("N2"),
                amount_adjustment = p.platform_type == "Aliexpress" ? "0" : p.amount_adjustment.ToString("N2"),
                amount_gift_wrap = p.amount_gift_wrap.ToString("N2"),
                amount_refund = p.amount_refund.ToString("N2"),

                cost_total = p.cost_total.ToString("N2"),
                cost_promotion = p.cost_promotion.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_shipping = p.cost_shipping.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_fba_fee = p.cost_fba_fee.ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),
                cost_refund_commisson = p.cost_refund_commisson.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = p.cost_handle_platform.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (p.profit_rate * 100).ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),

                create_time = p.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                paid_time = p.paid_time.ToString("yyyy-MM-dd HH:mm:ss"),


                cost_logistics = p.cost_logistics.ToString("N2"),
            });

            var colNames = new List<string> {"平台订单号","订单号","平台", "站点", "销售账户",
                                             "销售额", "产品收入","运费收入","税费收入","调整金额"
                                             ,"礼品包装金额","退款金额","总支出","促销费用","平台费用"
                                             ,"产品成本","包装费用","FBA费用","Paypal费用","退款佣金费用"
                                             ,"处理费(百伦)","平台操作费","头程费","尾程费","利润"
                                             ,"利润率","预收款","下单时间","付款时间"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.origin_order_id + "|" + item.bailun_order_id + "|" + item.platform_type + "|" + item.website + "|" + item.seller_account + "|" +
                    item.amount_sales + "|" + item.amount_product + "|" + item.amount_shipping + "|" + item.amount_tax + "|" + item.amount_adjustment + "|" +
                    item.amount_gift_wrap + "|" + item.amount_refund + "|" + item.cost_total + "|" + item.cost_promotion + "|" + item.cost_platform_fee + "|" +
                    item.cost_product + "|" + item.cost_package + "|" + item.cost_fba_fee + "|" + item.cost_paypal_fee + "|" + item.cost_refund_commisson + "|" +
                    item.cost_handle_bailun + "|" + item.cost_handle_platform + "|" + item.cost_first + "|" + item.cost_logistics + "|" + item.profit_total + "|" +
                    item.profit_rate + "|" + item.amount_prepaid + "|" + item.create_time + "|" + item.paid_time
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = platform + "订单明细导出" + 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="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="colname">计算列</param>
        /// <param name="skucategoryids">sku分类</param>
        /// <returns></returns>
        public ActionResult SkuCategoryProfit(DateTime start,DateTime end,string colname,string coltitle,string skucategoryids,string platform)
        {
            var obj = new Services.OrdersServices().ListSkuCategoryProfit(platform,start, end, colname, skucategoryids);

            var listplatform = obj.Select(a => a.platform_type).Distinct().ToList();
            var listcategory = obj.Select(a => a.category_simple_name).Distinct().OrderBy(a=>a).ToArray();

            var listval = new List<Tuple<string,List<decimal>>>();
            
            foreach (var item in obj)
            {
                var val_item = listval.Where(a => a.Item1 == item.platform_type).FirstOrDefault();
                if (val_item == null)
                {
                    var itemvals = new List<decimal>();

                    foreach (var i in listcategory)
                    {
                        itemvals.Add(0);
                    }

                    val_item = new Tuple<string, List<decimal>>(item.platform_type, itemvals);
                }

                for (var i = 0; i < listcategory.Count(); i++)
                {
                    if (item.category_simple_name == listcategory[i])
                    {
                        val_item.Item2[i] += item.count;
                    }
                }

                listval.Remove(val_item);
                listval.Add(val_item);
            }

            var countval = new List<decimal>();
            foreach (var i in listcategory)
            {
                countval.Add(0);
            }
            
            foreach (var item in listval)
            {
                for (var i = 0; i < item.Item2.Count; i++)
                {
                    countval[i] += item.Item2[i];
                }
            }

            var countitem = new Tuple<string, List<decimal>>("合计", countval);

            //格式化数字
            foreach (var item in listval)
            {
                for (var i=0;i<item.Item2.Count;i++)
                {
                    item.Item2[i] = Math.Round(item.Item2[i], 2);
                }
            }

            for (var i= 0;i<countitem.Item2.Count;i++)
            {
                countitem.Item2[i] = Math.Round(countitem.Item2[i], 2);
            }

            ViewBag.header = listcategory;
            ViewBag.vals = listval;
            ViewBag.count = countitem;

            ViewBag.start = start;
            ViewBag.end = end;
            ViewBag.colname = colname;
            ViewBag.skucategoryids = skucategoryids;
            ViewBag.platform = platform;
            ViewBag.coltitle = coltitle;

            ViewBag.single = (colname == "order_count" || colname == "amount_sales" ? 0 : 1);

            return View();
        }

        #endregion

        #region 订单退款明细

        public ActionResult OrderRefundDetails()
        {

            return View();
        }

        /// <summary>
        /// 订单退款明细
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="platform">订单平台类型</param>
        /// <param name="website">站点</param>
        /// <param name="account">帐号</param>
        /// <param name="start">退款开始时间</param>
        /// <param name="end">退款结束时间</param>
        /// <returns></returns>
        public string OrderRefundDetailsJson(BtTableParameter request, string platform, string website, string account, DateTime? start, DateTime? end,string searchkey)
        {
            var total = 0;
            var _services = new Services.OrdersServices();
            var obj = _services.ListOrderRefund(request, platform, website, account, start, end, searchkey, ref total);

            var countM = _services.ListOrderRefundCount(platform, website, account, start, end,searchkey);

            var list = obj.Select(a => new {
                a.platform_type,
                a.website,
                a.bailun_account,
                a.origin_order_id,
                a.bailun_sku,
                a.platform_sku,
                amount_refund = a.amount_refund.ToString("N2"),
                a.order_currency,
                a.bailun_sku_quantity_refund,
                bailun_sku_unit_price = a.bailun_sku_unit_price.ToString("N2"),
                linked = (a.linked==1?"是":"否"),
                refund_time = a.refund_time.HasValue?a.refund_time.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
                amount_refund_rmb = a.amount_refund_rmb.ToString("N2"),
                a.bailun_shipping_status,
            });

            return JsonConvert.SerializeObject(new { total=total,rows = list,count_row=new {
                platform_type = "合计",
                bailun_sku_quantity_refund = countM!=null?countM.bailun_sku_quantity_refund:0,
                amount_refund_rmb = countM!=null?countM.amount_refund_rmb.ToString("N2"):"0",
                amount_refund = countM!=null?countM.amount_refund.ToString("N2"):"0"
            }
            });
        }
        
        #endregion

        #region 预收款

        /// <summary>
        /// 预收款明细
        /// </summary>
        /// <returns></returns>
        public ActionResult DepositReceived()
        {
            return View();
        }

        /// <summary>
        /// 预收款明细数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string DepositReceivedJson(BtTableParameter request, string platform, string website, string account, DateTime? start, DateTime? end)
        {
            var total = 0;
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var countM = new Models.Orders.dc_base_oms_order();
            var obj = new Services.OrdersServices().ListDepositReceived(request, platform, website, account, start, end, companyid, ref total, ref countM);

            var list = obj.Select(a => new {
                a.origin_order_id,
                a.bailun_order_id,
                a.platform_type,
                a.website,
                a.seller_account,
                paid_time = a.paid_time.ToString("yyyy-MM-dd HH:mm:ss"),


                amount_sales = a.amount_sales.ToString("N2"),
                amount_shipping = a.amount_shipping.ToString("N2"),
                amount_product = a.amount_product.ToString("N2"),
                amount_tax = a.amount_tax.ToString("N2"),
                amount_adjustment = a.amount_adjustment.ToString("N2"),
                amount_gift_wrap = a.amount_gift_wrap.ToString("N2"),
                amount_refund = a.amount_refund.ToString("N2"),
                amount_prepaid = a.amount_prepaid.ToString("N2"),


                cost_total = a.cost_total.ToString("N2"),
                cost_promotion = a.cost_promotion.ToString("N2"),
                cost_platform_fee = a.cost_platform_fee.ToString("N2"),
                cost_product = a.cost_product.ToString("N2"),
                cost_shipping = a.cost_shipping.ToString("N2"),
                cost_package = a.cost_package.ToString("N2"),
                cost_fba_fee = a.cost_fba_fee.ToString("N2"),
                cost_paypal_fee = a.cost_paypal_fee.ToString("N2"),
                cost_refund_commisson = a.cost_refund_commisson.ToString("N2"),
                cost_handle_bailun = a.cost_handle_bailun.ToString("N2"),
                cost_handle_platform = a.cost_handle_platform.ToString("N2"),
                cost_tail = a.cost_tail.ToString("N2"),
                cost_first= a.cost_first.ToString("N2"),
                profit_total = a.profit_total.ToString("N2"),
                profit_rate = (a.profit_rate*100).ToString("N2")
            });

            return JsonConvert.SerializeObject(new {
                total = total,
                rows = list,
                count_row = new {
                    platform_type="合计",
                    amount_sales = countM.amount_sales.ToString("N2"),
                    amount_shipping = countM.amount_shipping.ToString("N2"),
                    amount_product = countM.amount_product.ToString("N2"),
                    amount_tax = countM.amount_tax.ToString("N2"),
                    amount_adjustment = countM.amount_adjustment.ToString("N2"),
                    amount_gift_wrap = countM.amount_gift_wrap.ToString("N2"),
                    amount_refund = countM.amount_refund.ToString("N2"),
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),


                    cost_total = countM.cost_total.ToString("N2"),
                    cost_promotion = countM.cost_promotion.ToString("N2"),
                    cost_platform_fee = countM.cost_platform_fee.ToString("N2"),
                    cost_product = countM.cost_product.ToString("N2"),
                    cost_shipping = countM.cost_shipping.ToString("N2"),
                    cost_package = countM.cost_package.ToString("N2"),
                    cost_fba_fee = countM.cost_fba_fee.ToString("N2"),
                    cost_paypal_fee = countM.cost_paypal_fee.ToString("N2"),
                    cost_refund_commisson = countM.cost_refund_commisson.ToString("N2"),
                    cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                    cost_handle_platform = countM.cost_handle_platform.ToString("N2"),
                    cost_tail = countM.cost_tail.ToString("N2"),
                    cost_first = countM.cost_first.ToString("N2"),
                    profit_total = countM.profit_total.ToString("N2"),
                    profit_rate = countM.cost_total>0?((countM.profit_total / countM.cost_total) *100).ToString("N2"):"0"
                }
            });
        }

        #endregion

        #region 退款单

        /// <summary>
        /// 退款单
        /// </summary>
        /// <returns></returns>
        public ActionResult ListReturn(string platform)
        {

            ViewBag.platform = platform;
            return View();
        }

        [BailunAuthentication(LoginMode.Enforce)]
        public string ListReturnJson(BtTableParameter parameter,DateTime? start,DateTime? end,DateTime? paystart,DateTime? payend,string platform,string website, string orderno,int? shipstatus)
        {
            var _service = new Services.OrdersServices();
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;

            var obj = _service.ListOrderReturn(parameter, start, end, paystart, payend, companyid, platform, website, orderno,shipstatus, ref total);
            var countOjb = _service.ListOrderReturnCount(start, end, paystart, payend, companyid, platform, website, orderno,shipstatus);

            var list = obj.Select(a => new {
                a.platform_type,
                a.website,
                a.origin_order_id,
                a.bailun_account,
                amount_refund_rmb = a.amount_refund_rmb.ToString("N2"),
                amount_refund_usd = a.amount_refund_usd.ToString("N2"),
                refund_time = a.refund_time.Value.ToString("yyyy-MM-dd HH:mm:ss"),
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list, count_row = new {
                bailun_account = "合计",
                amount_refund_rmb = countOjb.amount_refund_rmb.ToString("N2"),
                amount_refund_usd = countOjb.amount_refund_usd.ToString("N2"),
            }, companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportListReturn", HttpContextHelper.Current.User.GetUid()),
            });
        }

        /// <summary>
        /// 导出退款流水
        /// </summary>
        /// <param name="start">退款开始时间</param>
        /// <param name="end">退款结束时间</param>
        /// <param name="platform">平台类型</param>
        /// <param name="website">站点</param>
        /// <param name="orderno">平台订单号</param>
        /// <returns></returns>
        public ActionResult ExportListReturn(DateTime? start, DateTime? end, DateTime? paystart, DateTime? payend, string platform, string website, string orderno,int companyid)
        {
            var _service = new Services.OrdersServices();
            
            var obj = _service.ListOrderReturn(start, end, paystart, payend, companyid, platform, website, orderno);
            var list = obj.Select(a => new {
                a.platform_type,
                a.website,
                a.origin_order_id,
                a.bailun_account,
                amount_refund_rmb = a.amount_refund_rmb.ToString("N2"),
                amount_refund_usd = a.amount_refund_usd.ToString("N2"),
                refund_time = a.refund_time.Value.ToString("yyyy-MM-dd HH:mm:ss"),
            });

            var colNames = new List<string> {"平台订单号","平台名称","平台站点", "卖家帐号", "退款金额",
                                             "退款USD", "退款时间"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.origin_order_id + "|" + item.platform_type + "|" + item.website + "|" + item.bailun_account + "|" + item.amount_refund_rmb + "|" +
                    item.amount_refund_usd + "|" + item.refund_time
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = platform + "平台退款流水导出" + 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");
        }

        #endregion

        #region 广告费

        public ActionResult AmazonAD()
        {
            return View();
        }

        /// <summary>
        /// 亚马逊广告
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="account">帐号</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string AmazonADJson(BtTableParameter parameter, DateTime? start, DateTime? end,string account)
        {
            var _service = new Services.OrdersServices();
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;

            var obj = _service.ListAmazonADSku(parameter, account, start, end, companyid, ref total);
            var countObj = _service.ListAmazonADSkuCount(account, start, end, companyid,false);

            var list = obj.Select(a => new {
                a.account_name,
                a.sku,
                cost = a.cost.ToString("N2"),
                a.currency,
                cost_rmb = a.cost_rmb.ToString("N2"),
                report_date = a.report_date.ToString("yyyy-MM-dd"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    sku = "总计",
                    cost = countObj.cost.ToString("N2"),
                    cost_rmb = countObj.cost_rmb.ToString("N2")
                },
                companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportAmazonAD", HttpContextHelper.Current.User.GetUid()),
            });
        }

        /// <summary>
        /// 导出亚马逊广告费
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public ActionResult ExportAmazonAD(DateTime? start, DateTime? end, string account,int companyid)
        {
            var _service = new Services.OrdersServices();
            var obj = _service.ListAmazonADSku(account, start, end, companyid);

            var list = obj.Select(a => new {
                a.asin,
                a.account_name,
                a.sku,
                cost = a.cost.ToString("N2"),
                a.currency,
                cost_rmb = a.cost_rmb.ToString("N2"),
                report_date = a.report_date.ToString("yyyy-MM-dd"),
                a.site_en,
            });

            var colNames = new List<string> {"帐号","SKU","费用", "币种", "费用RMB",
                                            "ASIN","站点","报告日期"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.account_name + "|" + item.sku + "|" + item.cost + "|" + item.currency + "|" + item.cost_rmb + "|" +
                    item.asin+"|"+item.site_en+"|"+item.report_date
                    );
            }

            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>
        /// Wish 广告费
        /// </summary>
        /// <returns></returns>
        public ActionResult WishAD()
        {
            return View();
        }

        /// <summary>
        /// Wish广告费数据
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="account">帐号</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string WishADJson(BtTableParameter parameter, DateTime? start, DateTime? end, string account,string currency)
        {
            var total = 0;
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var _service = new Services.OrdersServices();

            var obj = _service.ListWishAD(parameter, companyid, account, start, end, ref total, currency.ToUpper() == "USD");
            var countObj = _service.ListWishADCount(companyid, account, start, end, currency.ToUpper() == "USD");
            var list = obj.Select(a => new {
                a.account_name,
                a.campaign_name,
                a.daily_gmv,
                daily_total_campaign_spend = a.daily_total_campaign_spend.ToString("N2"),
                daily_total_campaign_spend_rmb = a.daily_total_campaign_spend_rmb.ToString("N2"),
                record_time = a.record_time.ToString("yyyy-MM-dd"),
            });

            return JsonConvert.SerializeObject(new {
                total = total,
                rows = list,
                count_row = new
                {
                    campaign_name = "总计",
                    daily_total_campaign_spend = countObj.daily_total_campaign_spend.ToString("N2"),
                    daily_total_campaign_spend_rmb = countObj.daily_total_campaign_spend_rmb.ToString("N2")
                },
                companyid
            });
        }

        /// <summary>
        /// 导出wish广告费
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="account">帐号</param>
        /// <param name="currency">币种</param>
        /// <param name="companyid">公司id</param>
        /// <returns></returns>
        public ActionResult ExportWishAD(DateTime? start, DateTime? end, string account, string currency, int? companyid)
        {
            var _service = new Services.OrdersServices();
            var obj = _service.ListWishAD(companyid, account, start, end, currency.ToUpper() == "USD");

            var list = obj.Select(a => new {
                a.account_name,
                a.campaign_name,
                a.daily_gmv,
                daily_total_campaign_spend = a.daily_total_campaign_spend.ToString("N2"),
                daily_total_campaign_spend_rmb = a.daily_total_campaign_spend_rmb.ToString("N2"),
                record_time = a.record_time.ToString("yyyy-MM-dd"),
            });

            var colNames = new List<string> {"帐号","广告名称","每日GMV", "币种","广告费原币",
                                            "广告费"+currency,"报告日期"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.account_name + "|" + item.campaign_name + "|" + item.daily_gmv + "|" + "USD" + "|" +item.daily_total_campaign_spend + "|" + 
                    item.daily_total_campaign_spend_rmb + "|" + item.record_time
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "Wish广告费导出" + 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>
        /// 速卖通广告费
        /// </summary>
        /// <returns></returns>
        public ActionResult AliexpressAD()
        {
            return View();
        }

        /// <summary>
        /// 速卖通广告费列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="account">帐号</param>
        /// <param name="currency">币种</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string AlipressADJson(BtTableParameter parameter, DateTime? start, DateTime? end, string account, string currency="CNY")
        {
            var total = 0;
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var _service = new Services.OrdersServices();

            var obj = _service.ListAliexpressAD(parameter, companyid, account, start, end, currency.ToUpper() == "USD", ref total);
            var countObj = _service.ListAliexpressADCount(companyid, account, start, end, currency.ToUpper() == "USD");

            var list = obj.Select(a => new
            {
                a.account_name,
                a.product_name,
                a.exposure,
                a.clickcount,
                a.clickrate,
                cost_fee = a.cost_fee.ToString("N2"),
                cost_fee_rmb = a.cost_fee_rmb.ToString("N2"),
                a.currency,
                recore_time = a.recore_time.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new {
                total = total,
                rows = list,
                count_row = new
                {
                    product_name = "总计",
                    cost_fee = countObj.cost_fee.ToString("N2"),
                    cost_fee_rmb = countObj.cost_fee_rmb.ToString("N2")
                },
                companyid
            });
        }

        /// <summary>
        /// 导出速卖通广告费
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="account">帐号</param>
        /// <param name="currency">币种</param>
        /// <param name="companyid">公司id</param>
        /// <returns></returns>
        public ActionResult ExportAliexpressAD(DateTime? start, DateTime? end, string account, int? companyid, string currency = "CNY")
        {

            var _service = new Services.OrdersServices();
            var obj = _service.ListAliexpressAD(companyid, account, start, end, currency.ToUpper() == "USD");
            var list = obj.Select(a => new
            {
                a.account_name,
                a.product_name,
                a.exposure,
                a.clickcount,
                a.clickrate,
                cost_fee = a.cost_fee.ToString("N2"),
                cost_fee_rmb = a.cost_fee_rmb.ToString("N2"),
                a.currency,
                recore_time = a.recore_time.ToString("yyyy-MM-dd")
            });

            var colNames = new List<string> {"帐号","产品名称","曝光量", "点击量","点击率",
                                            "费用","币种","费用"+currency,"记录日期"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.account_name + "|" + item.product_name + "|" + item.exposure + "|" + item.clickcount + "|" + item.clickrate + "|" +
                    item.cost_fee + "|" + item.currency +"|" + item.cost_fee_rmb+"|"+item.recore_time
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "Aliexpress广告费导出" + 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");
        }

        public JsonResult ImportAliExpressAD(int? companyid)
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            var file = Request.Form.Files[0];
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();
                var list = new List<dc_base_finance_aliexpress>();

                for (var i = 0; i < tb.Value.Rows.Count; i++)
                {
                    var row = tb.Value.Rows[i];

                    try
                    {
                        var account_name = row["账号"].ToString();
                        var product_id = row["商品ID"].ToString();
                        var product_name = row["商品名称"].ToString();
                        var exposure = row["曝光量"].ToString();
                        var clickcount = row["点击量"].ToString();
                        var clickrate = row["点击率"].ToString();
                        var cost_fee = row["花费"].ToString();
                        var avg_click_cost = row["平均点击花费"].ToString();

                        var p4p_ordercount = row["P4P下单数"].ToString();
                        var p4p_orderamount = row["P4P下单金额"].ToString();
                        var p4p_shoppingcart_count = row["P4P带来的购物车数"].ToString();
                        var p4p_collect_count = row["P4P带来的收藏数"].ToString();
                        var currency = row["币种"].ToString();
                        var recore_time = row["统计日期"].ToString();

                        if (string.IsNullOrEmpty(account_name))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i+1)}行帐号不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(product_id))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行商品id不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(product_name))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行商品名称不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(exposure))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行曝光量不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(clickcount))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行点击量不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(clickrate))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行点击率不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(cost_fee))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行花费不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(avg_click_cost))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行平均点击花费不能为空！"
                            });
                        }

                        

                        if (string.IsNullOrEmpty(p4p_ordercount))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行P4P下单数不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(p4p_orderamount))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行P4P下单金额不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(p4p_shoppingcart_count))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行P4P带来的购物车数不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(p4p_collect_count))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行P4P带来的收藏数不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(currency))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行币种不能为空！"
                            });
                        }
                        if (string.IsNullOrEmpty(recore_time))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"导入失败，第{(i + 1)}行统计日期不能为空！"
                            });
                        }

                        var m = new dc_base_finance_aliexpress {
                            company_id = companyid??0,
                            account_name = account_name,
                            avg_click_cost = decimal.Parse(avg_click_cost),
                            clickcount = int.Parse(clickcount),
                            clickrate = decimal.Parse(clickrate),
                            cost_fee = decimal.Parse(cost_fee),
                            
                            createtime = DateTime.Now,
                            currency = currency,
                            delstatus = 0,
                            exposure = int.Parse(exposure),
                            p4p_collect_count = int.Parse(p4p_collect_count),
                            p4p_orderamount = decimal.Parse(p4p_orderamount),
                            p4p_ordercount = int.Parse(p4p_ordercount),
                            p4p_shoppingcart_count = int.Parse(p4p_shoppingcart_count),

                            product_id = product_id,
                            product_name = product_name,
                            recore_time = DateTime.Parse(recore_time),
                            
                        };

                        list.Add(m);
                    }
                    catch (Exception ex)
                    {
                        return Json(new
                        {
                            success = false,
                            msg = "导入失败，异常信息：" + ex.Message
                        });
                    }
                }

                if (list.Count == 0)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "表格没有数据。",
                    });

                }

                var listRate = new List<Tuple<string,string,decimal>>();
                var listAccount = new List<Tuple<int, string>>();

                foreach (var item in list)
                {
                    //获取相关汇率
                    var rates = listRate.Where(a => a.Item1 == item.currency);
                    if (rates.Count() == 0)
                    {
                        var rateRMB = Services.CommonServices.GetExchangeRate(item.currency, "CNY");
                        var rateUSD = Services.CommonServices.GetExchangeRate(item.currency, "USD");

                        listRate.Add(new Tuple<string, string, decimal>(item.currency, "CNY", rateRMB));
                        listRate.Add(new Tuple<string, string, decimal>(item.currency, "USD", rateUSD));

                        item.cost_fee_rmb = item.cost_fee * rateRMB;
                        item.to_rmb_rate = rateRMB;
                        item.to_usd_rate = rateUSD;
                    }
                    else
                    {
                        var rateRMB = rates.Where(a=>a.Item2=="CNY").FirstOrDefault();
                        var rateUSD = rates.Where(a => a.Item2 == "USD").FirstOrDefault();

                        if (rateRMB == null)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"找不到币种【{item.currency}】转人民币的汇率",
                            });
                        }
                        if (rateUSD == null)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"找不到币种【{item.currency}】转美元的汇率",
                            });
                        }

                        item.cost_fee_rmb = item.cost_fee * rateRMB.Item3;
                        item.to_rmb_rate = rateRMB.Item3;
                        item.to_usd_rate = rateUSD.Item3;
                    }

                    //获取帐号id
                    var objAccount = listAccount.Where(a => a.Item2 == item.account_name).FirstOrDefault();
                    if (objAccount == null)
                    {
                        var _account = Services.CommonServices.GetCompanyAccount(item.account_name, companyid??0);
                        if (_account == null)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = $"找不到该账号【{item.account_name}】",
                            });
                        }

                        item.account_id = _account.account_id;

                        listAccount.Add(new Tuple<int, string>(_account.account_id,item.account_name));
                    }
                    else
                    {
                        item.account_id = objAccount.Item1;
                    }
                }

                var result = new Services.OrdersServices().SaveAliExpressAD(list);

                return Json(new
                {
                    success = string.IsNullOrEmpty(result),
                    msg = result
                });
            }
            else
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件"
                });
            }
        }

        #endregion

        #region Paypal费

        /// <summary>
        /// Paypal费流水
        /// </summary>
        /// <returns></returns>
        public ActionResult ListPaypal()
        {
            return View();
        }

        /// <summary>
        /// Paypal费流水数据
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public string ListPaypalJson(BtTableParameter parameter,DateTime? start,DateTime? end)
        {
            var total = 0;
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var _service = new Services.OrdersServices();

            var obj = _service.ListPaypal(parameter, start, end, companyid, ref total);
            var countObj = _service.ListPaypalCount(start, end, companyid);

            var list = obj.Select(a => new {
                a.transaction_id,
                a.receipt_id,
                a.transaction_type,
                a.payment_type,
                payment_date = a.payment_date.ToString("yyyy-MM-dd HH:mm:ss"),
                gross_amount = a.gross_amount.ToString("N2"),
                a.payment_status,
                a.business,
                a.receiver,
                a.currency,
                gross_amount_rmb = a.gross_amount_rmb.ToString("N2")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list, count_row = new {
                currency = "合计",
                gross_amount_rmb = countObj.gross_amount_rmb.ToString("N2"),
                gross_amount = countObj.gross_amount.ToString("N2")
                },
                companyid
            });
        }

        /// <summary>
        /// 导出paypal明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public ActionResult ExportPaypal(DateTime? start,DateTime? end,int companyid)
        {
            var obj = new Services.OrdersServices().ListPaypal(start, end, companyid);

            var list = obj.Select(a => new {
                a.transaction_id,
                a.receipt_id,
                a.transaction_type,
                a.payment_type,
                payment_date = a.payment_date.ToString("yyyy-MM-dd HH:mm:ss"),
                gross_amount = a.gross_amount.ToString("N2"),
                a.payment_status,
                a.business,
                a.receiver,
                a.currency,
                gross_amount_rmb = a.gross_amount_rmb.ToString("N2")
            });

            var colNames = new List<string> {"交易号","receipt_id","交易类型", "支付类型", "币种",
                                             "总费用","总费用RMB","交易状态","接收帐号","时间"
            };

            var listVal = new List<string>();
            foreach (var item in list)
            {
                listVal.Add(
                    item.transaction_id + "|" + item.receipt_id + "|" + item.transaction_type + "|" + item.payment_type + "|" + item.currency + "|" +
                    item.gross_amount+"|"+item.gross_amount_rmb+"|"+item.payment_status + "|"+item.receiver+"|"+item.payment_date
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "Ebay Paypal明细导出" + 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");
        }

        #endregion

        #region 共用统计

        /// <summary>
        /// 平台销售统计 按站点
        /// </summary>
        /// <returns></returns>
        public ActionResult StatisticsByWebsite(string platform)
        {

            ViewBag.platform = platform;
            return View();
        }

        /// <summary>
        /// 平台销售统计  按站点
        /// </summary>
        /// <param name="request"></param>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="selleraccount"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <param name="skucategoryids"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string StatisticsByWebsiteJson(BtTableParameter request, string platform, string website, string selleraccount, DateTime start, DateTime end, string warehousetype, string warehousecode, string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var _services = new Services.OrdersServices();
            var objwithdraw = new Services.PlatformSiteServices().GetPlatformLossWithdraw().Where(a => a.english_name == platform).FirstOrDefault();
            var withdrawpercent = 0.0000M;
            if (objwithdraw != null && objwithdraw.Loss_withdrawal_percent.HasValue)
            {
                withdrawpercent = objwithdraw.Loss_withdrawal_percent.Value;
            }

            if (platform.ToLower() == "ebay")  //ebay的汇损为2.5%
            {
                withdrawpercent = 0.025m;
            }

            var obj = _services.ListEbayStatisticsByWebsite(request, platform, website, selleraccount, start, end, warehousetype, warehousecode, companyid, ref total, skucategoryids);

            var countM = _services.ListEbayStatisticsCount(platform, website, selleraccount, start, end, warehousetype, warehousecode, companyid, skucategoryids);

            countM.website = "总计：";
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.loss_withdrawal = countM.amount_sales * (withdrawpercent);
            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_shipping = Math.Round(countM.cost_shipping, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.profit_rate = countM.amount_product > 0 ? Math.Round((countM.profit_total / countM.amount_product), 2, MidpointRounding.AwayFromZero) : 0;
            countM.cost_tail = Math.Round(countM.cost_tail, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);

            var list = obj.Select(p => new
            {
                p.platform_type,
                p.seller_account,
                p.website,
                amount_sales = p.amount_sales.ToString("N2"),
                amount_product = p.amount_product.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                p.order_count,
                loss_withdrawal = (p.amount_sales * withdrawpercent).ToString("N2"),

                cost_total = p.cost_total.ToString("N2"),
                cost_shipping = p.cost_shipping.ToString("N2"),
                amount_refund = p.amount_refund.ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (100 * p.profit_rate).ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                noshippingcount = p.noshippingcount.ToString("N0")
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    countM.platform_type,
                    countM.seller_account,
                    countM.website,
                    amount_sales = countM.amount_sales.ToString("N2"),
                    amount_product = countM.amount_product.ToString("N2"),
                    cost_product = countM.cost_product.ToString("N2"),
                    cost_platform_fee = countM.cost_platform_fee.ToString("N2"),
                    cost_package = countM.cost_package.ToString("N2"),
                    cost_paypal_fee = countM.cost_paypal_fee.ToString("N2"),
                    cost_first = countM.cost_first.ToString("N2"),
                    countM.order_count,
                    loss_withdrawal = countM.loss_withdrawal.ToString("N2"),
                    cost_total = countM.cost_total.ToString("N2"),
                    cost_shipping = countM.cost_shipping.ToString("N2"),
                    amount_refund = countM.amount_refund.ToString("N2"),
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),
                    profit_total = countM.profit_total.ToString("N2"),
                    profit_rate = (100 * countM.profit_rate).ToString("N2"),
                    cost_tail = countM.cost_tail.ToString("N2"),
                    cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                    noshippingcount = countM.noshippingcount.ToString("N0"),
                }
            });
        }


        /// <summary>
        /// 平台销售统计
        /// </summary>
        /// <returns></returns>
        public ActionResult PlatformSaleStatistics(string platform)
        {

            ViewBag.platform = platform;
            return View();
        }

        /// <summary>
        /// 平台销售统计 Json
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="platform">平台类型</param>
        /// <param name="selleraccount">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string PlatformSaleStatisticsJson(BtTableParameter parameter, string platform,string selleraccount, string website, DateTime start, DateTime end, string warehousetype, string warehousecode, string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();

            var total = 0;
            var services = new Services.OrdersServices();
            var objwithdraw = new Services.PlatformSiteServices().GetPlatformLossWithdraw().Where(a => a.english_name == platform).FirstOrDefault();
            var withdrawpercent = 0.0000M;
            if (objwithdraw != null && objwithdraw.Loss_withdrawal_percent.HasValue)
            {
                withdrawpercent = objwithdraw.Loss_withdrawal_percent.Value;
            }

            //withdrawpercent = 0.025m;

            var list = services.ListPlatformStatistics(parameter, platform,website, selleraccount, start, end, warehousetype, warehousecode, companyid, ref total, skucategoryids);

            var countM = services.ListEbayStatisticsCount(platform, website, selleraccount, start, end, warehousetype, warehousecode, companyid, skucategoryids);

            countM.seller_account = "总计：";
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);
            countM.amount_product = Math.Round(countM.amount_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_product = Math.Round(countM.cost_product, 2, MidpointRounding.AwayFromZero);
            countM.cost_platform_fee = Math.Round(countM.cost_platform_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_package = Math.Round(countM.cost_package, 2, MidpointRounding.AwayFromZero);
            countM.cost_paypal_fee = Math.Round(countM.cost_paypal_fee, 2, MidpointRounding.AwayFromZero);
            countM.cost_first = Math.Round(countM.cost_first, 2, MidpointRounding.AwayFromZero);
            countM.loss_withdrawal = countM.amount_sales * (withdrawpercent);
            countM.cost_total = Math.Round(countM.cost_total, 2, MidpointRounding.AwayFromZero);
            countM.cost_shipping = Math.Round(countM.cost_shipping, 2, MidpointRounding.AwayFromZero);
            countM.amount_refund = Math.Round(countM.amount_refund, 2, MidpointRounding.AwayFromZero);
            countM.amount_prepaid = Math.Round(countM.amount_prepaid, 2, MidpointRounding.AwayFromZero);
            countM.profit_total = Math.Round(countM.profit_total, 2, MidpointRounding.AwayFromZero);
            countM.profit_rate = countM.amount_product > 0 ? Math.Round((countM.profit_total / countM.amount_product), 2, MidpointRounding.AwayFromZero) : 0;
            countM.cost_tail = Math.Round(countM.cost_tail, 2, MidpointRounding.AwayFromZero);
            countM.cost_handle_bailun = Math.Round(countM.cost_handle_bailun, 2, MidpointRounding.AwayFromZero);
            countM.cost_logistics = Math.Round(countM.cost_logistics, 2, MidpointRounding.AwayFromZero);

            var obj = list.Select(p => new
            {
                p.platform_type,
                p.seller_account,
                p.website,
                amount_sales = p.amount_sales.ToString("N2"),
                amount_product = p.amount_product.ToString("N2"),
                cost_product = p.cost_product.ToString("N2"),
                cost_platform_fee = p.cost_platform_fee.ToString("N2"),
                cost_package = p.cost_package.ToString("N2"),
                cost_paypal_fee = p.cost_paypal_fee.ToString("N2"),
                cost_first = p.cost_first.ToString("N2"),
                p.order_count,
                loss_withdrawal = (p.amount_sales * withdrawpercent).ToString("N2"),

                cost_total = p.cost_total.ToString("N2"),
                cost_shipping = p.cost_shipping.ToString("N2"),
                amount_refund = p.amount_refund.ToString("N2"),
                amount_prepaid = p.amount_prepaid.ToString("N2"),
                profit_total = p.profit_total.ToString("N2"),
                profit_rate = (100 * p.profit_rate).ToString("N2"),
                cost_tail = p.cost_tail.ToString("N2"),
                cost_handle_bailun = p.cost_handle_bailun.ToString("N2"),
                noshippingcount = p.noshippingcount.ToString("N0"),
                cost_logistics = p.cost_logistics.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    countM.platform_type,
                    countM.seller_account,
                    countM.website,
                    amount_sales = countM.amount_sales.ToString("N2"),
                    amount_product = countM.amount_product.ToString("N2"),
                    cost_product = countM.cost_product.ToString("N2"),
                    cost_platform_fee = countM.cost_platform_fee.ToString("N2"),
                    cost_package = countM.cost_package.ToString("N2"),
                    cost_paypal_fee = countM.cost_paypal_fee.ToString("N2"),
                    cost_first = countM.cost_first.ToString("N2"),
                    countM.order_count,
                    loss_withdrawal = countM.loss_withdrawal.ToString("N2"),
                    cost_total = countM.cost_total.ToString("N2"),
                    cost_shipping = countM.cost_shipping.ToString("N2"),
                    amount_refund = countM.amount_refund.ToString("N2"),
                    amount_prepaid = countM.amount_prepaid.ToString("N2"),
                    profit_total = countM.profit_total.ToString("N2"),
                    profit_rate = (100 * countM.profit_rate).ToString("N2"),
                    cost_tail = countM.cost_tail.ToString("N2"),
                    cost_handle_bailun = countM.cost_handle_bailun.ToString("N2"),
                    noshippingcount = countM.noshippingcount.ToString("N0"),
                    cost_logistics = countM.cost_logistics.ToString("N2"),
                }
            });
        }

        
        #endregion

        #region Common

        /// <summary>
        /// 获取平台列表
        /// </summary>
        /// <returns></returns>
        public JsonResult ListPlatform()
        {
            var result = Services.CommonServices.ListPlatForm();
            return Json(result);
        }

        /// <summary>
        /// 获取帐号列表
        /// </summary>
        /// <param name="platform">平台编码</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult ListAccount(string platform)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();

            var result = Services.CommonServices.ListAccount(platform, companyid).Where(a=>!string.IsNullOrEmpty(a));
            return Json(result);
        }

        /// <summary>
        /// paypal账号列表
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult ListPaypalAccount()
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var result = Services.CommonServices.ListPaypalAccount(companyid).Select(a=>a.seller).ToList();

            return Json(result);
        }

        /// <summary>
        /// 获取站点列表
        /// </summary>
        /// <param name="platform">平台编码</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult ListWebSite(string platform,DateTime? start,DateTime? end)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var result = Services.CommonServices.ListWebSite(platform, companyid, start,end).Where(a => !string.IsNullOrEmpty(a));
            return Json(result);
        }

        /// <summary>
        /// 销售员列表
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult ListSeller()
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var result = Services.CommonServices.ListSeller(companyid);
            return Json(result);
        }

        /// <summary>
        /// 获取百伦Sku分类
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSkuCategory(int level=1)
        {
            var obj = Services.CommonServices.GetCategoryList(level);

            return Json(obj);
        }

        /// <summary>
        /// 获取sku 一、二级分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string ListSkuCategoryOneAndSecondLevel()
        {
            var obj = Services.CommonServices.GetCategoryList(1);
            var obj1 = Services.CommonServices.GetCategoryList(2);

            var listcategory = new List<Models.Api.mSkuCategoryTree>();

            foreach (var item in obj)
            {
                var m = new Models.Api.mSkuCategoryTree();
                m.id = item.C_ID;
                m.name = item.C_CNAME;
                m.open = false;
                m.children = new List<Models.Api.mSkuCategoryTree>();
                var childrens = obj1.Where(a => a.C_PARENTID == item.C_ID);
                if (childrens.Count() > 0)
                {
                    foreach (var second in childrens)
                    {
                        m.children.Add(new Models.Api.mSkuCategoryTree {
                            id = second.C_ID,
                            name = second.C_CNAME,
                            open=false,
                            //children = new List<Models.Api.mSkuCategoryTree>(),
                        });
                    }
                }

                listcategory.Add(m);
            }

            return JsonConvert.SerializeObject(listcategory);
        }


        /// <summary>
        /// 获取百伦sku的所有分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSkuCategoryAll()
        {
            var obj = Services.CommonServices.GetCategoryListAll(null, 0);

            return Json(obj);
        }

        #endregion

        #region 图表

        /// <summary>
        /// 平台利润统计报表曲线图
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderProfitGraph(string col, string platform, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, string currency, string skucategoryids,string titlename)
        {
            ViewBag.platform = platform;
            ViewBag.shipstart = shipstart.HasValue ? shipstart.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.shipend = shipend.HasValue ? shipend.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.currency = currency;
            ViewBag.skucategoryids = skucategoryids;
            ViewBag.col = col;
            ViewBag.start = start.HasValue ? start.Value.ToString("yyyy-MM-dd"):"";
            ViewBag.end = end.HasValue ? end.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.titlename = titlename;

            return View();
        }

        /// <summary>
        /// 平台利润统计报表曲线图
        /// </summary>
        /// <param name="col"></param>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="shipstart"></param>
        /// <param name="shipend"></param>
        /// <param name="currency"></param>
        /// <param name="skucategoryids"></param>
        /// <returns></returns>
        [HttpPost]
        [BailunAuthentication(LoginMode.Enforce)]
        public JsonResult OrderProfitGraphJson(string col, string platform, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, string currency, string skucategoryids)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var _service = new Services.OrdersServices();
            var list = new List<Models.OrderChart.ProformProfitChart>();

            if (string.IsNullOrWhiteSpace(col))
            {
                return Json(new {
                    success = false,
                    msg = "请选择字段。"
                });
            }

            if (shipstart.HasValue || shipend.HasValue)
            {
                //var obj = _service
            }
            else
            {
                if (start.HasValue && end.HasValue && start.Value == end.Value)
                {
                    start = start.Value.AddDays(-6);
                }

                list = _service.ListOrderProfitGraph(col, platform, start, end, shipstart, shipend, currency.ToUpper() == "USD", companyid, skucategoryids);
            }

            return Json(new {
                success = true,
                data = list.Select(a=>new {
                    val = decimal.Parse(a.val.ToString("N2")),
                    date = a.date.ToString("yyyy-MM-dd")
                }),
                msg = ""
            });

        }


        /// <summary>
        /// 平台销售统计曲线图
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderSalesGraph(string col, string platform, string sellaccount, string website, DateTime? start, DateTime? end, string warehousetype, string warehousecode, string skucategoryids,string titlename, int websitegroup = 0)
        {
            ViewBag.col = col;
            ViewBag.platform = platform;
            ViewBag.sellaccount = sellaccount;
            ViewBag.website = website;
            ViewBag.start = start.HasValue ? start.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.end = end.HasValue ? end.Value.ToString("yyyy-MM-dd") : "";
            ViewBag.warehousetype = warehousetype;
            ViewBag.warehousecode = warehousecode;
            ViewBag.skucategoryids = skucategoryids;

            ViewBag.titlename = titlename;
            ViewBag.websitegroup = websitegroup;

            return View();
        }

        [HttpPost]
        [BailunAuthentication(LoginMode.Enforce)]
        public JsonResult OrderSalesGraphJson(string col,string platform,string sellaccount, string website, DateTime? start, DateTime? end, string warehousetype, string warehousecode, string skucategoryids,int websitegroup=0)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var _service = new Services.OrdersServices();
            var list = new List<Models.OrderChart.ProformProfitChart>();

            if (string.IsNullOrWhiteSpace(col))
            {
                return Json(new
                {
                    success = false,
                    msg = "请选择字段。"
                });
            }

            list = _service.ListOrderSalesGraph(col, platform, start, end, website, sellaccount, companyid, skucategoryids, warehousetype, warehousecode, websitegroup==1);

            return Json(new
            {
                success = true,
                data = list.Select(a => new {
                    val = decimal.Parse(a.val.ToString("N2")),
                    date = a.date.ToString("yyyy-MM-dd")
                }),
                msg = ""
            });
        }
        



        #endregion
    }
}