using System;
using System.Collections.Generic;
using System.Text;
using Bailun.DC.Models;
using Bailun.DC.DB;
using Dapper;
using MySql.Data.MySqlClient;
using System.Linq;
using Bailun.DC.Models.Orders;

namespace Bailun.DC.Services
{
    public class OrdersServices
    {
        #region 

        /// <summary>
        /// 平台费用流水
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_oms_order> ListPlatformCost(BtTableParameter parameter, string platform, DateTime? start, DateTime? end, string website, string account, string warehousetype, string warehousecode, int? companyid, ref int total, string skucategoryids)
        {
            var sql = "select t1.* from dc_base_oms_order t1";
            var sqlparam = new DynamicParameters();

            if (!string.IsNullOrEmpty(warehousetype))
            {
                sql += " join (select tb.bailun_order_id from dc_base_oms_sku tb join dc_base_warehouse t2 on tb.warehouse_code = t2.warehouse_code and t2.hq_type= @warehousetype";
                sqlparam.Add("warehousetype", warehousetype);

                if (!string.IsNullOrEmpty(warehousecode))
                {
                    sql += " and tb.warehouse_code=@warehousecode";
                    sqlparam.Add("warehousecode", warehousecode);
                }

                sql += " group by tb.bailun_order_id limit 1) t2 on t1.bailun_order_id=t2.bailun_order_id ";
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ")";

                    }
                }
            }


            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += "and t1.company_id = " + companyid.Value; //增加公司id判断
            }

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paidtimestart";
                sqlparam.Add("paidtimestart", start.Value.ToString("yyyy-MM-dd"));
            }
            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paidtimeend";
                sqlparam.Add("paidtimeend", end.Value.AddDays(1).ToString("yyyy-MM-dd"));
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrEmpty(parameter.sort))
            {
                sql += " order by t1." + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_oms_order>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam);

                return obj.AsList();
            }
        }


        public dc_base_oms_order ListPlatformCostCount(string platform, DateTime? start, DateTime? end, string website, string account, string warehousetype, string warehousecode, int? companyid, string skucategoryids)
        {
            var sql = "select sum(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales,sum((if(t1.platform_type='Ebay',t1.seller_other_exchange_rate,t1.seller_order_exchange_rate))*t1.cost_platform_fee) as cost_platform_fee,sum(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,sum(t1.cost_promotion*t1.seller_order_exchange_rate) cost_promotion,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,sum(t1.cost_logistics) cost_logistics,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.amount_shipping*t1.seller_order_exchange_rate) amount_shipping,sum(cost_product) cost_product,sum(t1.cost_first) cost_first,sum(t1.amount_prepaid) amount_prepaid,sum(t1.profit_total) profit_total,(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)), profit_rate,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund from dc_base_oms_order t1 ";
            var sqlparam = new DynamicParameters();

            if (!string.IsNullOrEmpty(warehousetype))
            {
                sql += " join (select tb.bailun_order_id from dc_base_oms_sku tb join dc_base_warehouse t2 on tb.warehouse_code = t2.warehouse_code and t2.hq_type = @warehousetype";
                sqlparam.Add("warehousetype", warehousetype);

                if (!string.IsNullOrEmpty(warehousecode))
                {
                    sql += " and tb.warehouse_code=@warehousecode";
                    sqlparam.Add("warehousecode", warehousecode);
                }

                sql += " group by tb.bailun_order_id limit 1) t2 on t1.bailun_order_id=t2.bailun_order_id ";
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ")";

                    }
                }

            }


            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id = " + companyid.Value; //增加公司id判断
            }

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paidtimestart";
                sqlparam.Add("paidtimestart", start.Value.ToString("yyyy-MM-dd"));
            }
            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paidtimeend";
                sqlparam.Add("paidtimeend", end.Value.AddDays(1).ToString("yyyy-MM-dd"));
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirst<dc_base_oms_order>(sql, sqlparam);

                return obj;
            }
        }


        /// <summary>
        /// 导出 平台费用流水
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_oms_order> ListPlatformCost(string platform, DateTime? start, DateTime? end, string website, string account, string warehousetype, string warehousecode, int? companyid, string skucategoryids)
        {
            var sql = "select t1.* from dc_base_oms_order t1";
            var sqlparam = new DynamicParameters();

            if (!string.IsNullOrEmpty(warehousetype))
            {
                sql += " join (select tb.bailun_order_id from dc_base_oms_sku tb join dc_base_warehouse t2 on tb.warehouse_code = t2.warehouse_code and t2.hq_type= @warehousetype";
                sqlparam.Add("warehousetype", warehousetype);

                if (!string.IsNullOrEmpty(warehousecode))
                {
                    sql += " and tb.warehouse_code=@warehousecode";
                    sqlparam.Add("warehousecode", warehousecode);
                }

                sql += " group by tb.bailun_order_id limit 1) t2 on t1.bailun_order_id=t2.bailun_order_id ";
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += " join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    var AllCategory = Services.CommonServices.GetCategoryList(0);
                    var listcategory = new List<Models.Common.CategoryDto>();

                    foreach (var item in arr)
                    {
                        listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    }

                    var s = string.Join(",", listcategory.Select(a => a.C_ID));
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t3.bailun_category_id in (" + s + ")";

                    }
                }
            }


            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += "and t1.company_id = " + companyid.Value; //增加公司id判断
            }

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paidtimestart";
                sqlparam.Add("paidtimestart", start.Value.ToString("yyyy-MM-dd"));
            }
            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paidtimeend";
                sqlparam.Add("paidtimeend", end.Value.AddDays(1).ToString("yyyy-MM-dd"));
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_oms_order>(sql, sqlparam);

                return obj.AsList();
            }
        }

        #endregion

        #region 亚马逊

        /// <summary>
        /// 获取亚马逊的销售统计数据（非FBA）
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="account">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_base_oms_order> ListAmazonStatistics(BtTableParameter parameter, string account, string website, DateTime start, DateTime end, string warehoursetype, string warehousecode, int? companyid, ref int total, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var sql = @"select t1.platform_type,t1.seller_account,t1.website,sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_sales',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) 'cost_platform_fee',sum(t1.cost_first) 'cost_first',count(t1.id) 'order_count',sum(t1.cost_total) 'cost_total',sum(t1.cost_logistics) 'cost_logistics',sum(t1.profit_total) 'profit_total',(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,count(t1.amount_prepaid>0 or null) as noshippingcount,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform  from dc_base_oms_order t1";

            if (!string.IsNullOrEmpty(warehoursetype) || !string.IsNullOrEmpty(warehousecode) || !string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += " join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id ";

                if (!string.IsNullOrWhiteSpace(skucategoryids))
                {
                    sql += " join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku ";

                    var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                    if (arr.Count > 0)
                    {
                        //获取选中分类下所有的分类
                        //var AllCategory = Services.CommonServices.GetCategoryList(0);
                        //var listcategory = new List<Models.Common.CategoryDto>();

                        //foreach (var item in arr)
                        //{
                        //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                        //}

                        var s = string.Join(",", arr);
                        if (!string.IsNullOrEmpty(s))
                        {
                            sql += " and t4.category_simple_id in (" + s + ") ";
                        }
                    }
                }

            }

            if (!string.IsNullOrEmpty(warehoursetype))
            {
                sql += " join dc_base_warehouse t2 on t3.warehouse_code=t2.warehouse_code and t2.warehouse_type_ex=@warehoursetype";
                sqlparam.Add("warehoursetype", warehoursetype);
            }
            if (!string.IsNullOrEmpty(warehousecode))
            {
                if (!string.IsNullOrEmpty(warehoursetype))
                {
                    sql += " and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
                else
                {
                    sql += " join dc_base_warehouse t2 on t3.warehouse_code=t2.warehouse_code and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
            }

            var fromsql = " where t1.paid_time>='" + start.ToString("yyyy-MM-dd") + "' and t1.paid_time<'" + end.AddDays(1).ToString("yyyy-MM-dd") + "' and t1.platform_type='Amazon' and t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";
            if (companyid.HasValue && companyid.Value > 0)
            {
                fromsql += "and t1.company_id = " + companyid.Value; //增加公司id判断
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                fromsql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                fromsql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }


            var prefromsql = fromsql;
            fromsql += "  and t1.bailun_payment_status!='Canceled'  and t1.bailun_order_status!='CantHandle'";
            fromsql += " group by t1.seller_account,t1.website,t1.platform_type";

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                fromsql += " order by " + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_oms_order>(parameter.pageIndex, parameter.limit, sql + fromsql, ref total, sqlparam);

                return obj.ToList();
            }

        }

        /// <summary>
        /// 获取亚马逊的销售统计数据（非FBA） 统计
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="account">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public dc_base_oms_order ListAmazonStatisticsCount(string account, string website, DateTime start, DateTime end, string warehoursetype, string warehousecode, int? companyid, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var presql = "select sum(t1.amount_prepaid) as amount_prepaid from dc_base_oms_sku t1 ";
            var sql = "select sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_sales',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) 'cost_platform_fee',sum(t1.cost_first) 'cost_first',count(t1.id) 'order_count',sum(t1.cost_total) 'cost_total',sum(t1.cost_logistics) 'cost_logistics',sum(t1.profit_total) 'profit_total',(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,count(t1.amount_prepaid>0 or null) as noshippingcount,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform  from dc_base_oms_order t1 ";

            if (!string.IsNullOrEmpty(warehoursetype))
            {
                sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_type_ex=@warehoursetype";
                presql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_type_ex=@warehoursetype";
                sqlparam.Add("warehoursetype", warehoursetype);
            }
            if (!string.IsNullOrEmpty(warehousecode))
            {
                if (!string.IsNullOrEmpty(warehoursetype))
                {
                    sql += " and t2.warehouse_code=@warehouse_code";
                    presql += " and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
                else
                {
                    sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_code=@warehouse_code";
                    presql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
            }
            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ")";

                    }
                }
            }

            var fromsql = " where t1.paid_time>='" + start.ToString("yyyy-MM-dd") + "' and t1.paid_time<'" + end.AddDays(1).ToString("yyyy-MM-dd") + "' and t1.platform_type='Amazon' and t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                fromsql += " and t1.company_id=" + companyid.Value;   //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                fromsql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                fromsql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            var prefromsql = fromsql;
            fromsql += "  and t1.bailun_payment_status!='Canceled'  and t1.bailun_order_status!='CantHandle'";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                try
                {
                    var obj = cn.QueryFirst<dc_base_oms_order>(sql + fromsql, sqlparam);

                    return obj;
                }
                catch (Exception ex)
                {
                    return new Models.Orders.dc_base_oms_order();
                }
            }

        }

        /// <summary>
        /// 获取亚马逊的销售统计数据（FBA）
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="account">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<Models.Orders.mAmazonStatistics> ListFBAStatistics(BtTableParameter parameter, string account, string website, DateTime start, DateTime end, int? companyid, ref int total, string skucategoryids)
        {

            var sqlparam = new DynamicParameters();

            var sql = @"select t1.platform_type,t1.seller_account,t1.website,sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_product',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) 'platform_fee',sum(t1.cost_first) 'head_fee',count(t1.id) 'order_count',sum(t1.cost_total) 'cost_count',sum(t1.cost_shipping) 'nofba_logisticsfee',sum(t1.profit_total) 'profit_count',(sum(t1.profit_total)/sum(t1.amount_total*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,sum(t1.cost_package) cost_package,count(t1.amount_prepaid>0 or null) as noshippingcount  from dc_base_oms_order t1 ";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku  
                        ";


                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ") ";

                    }
                }
            }

            sql += " where t1.paid_time>='" + start.ToString("yyyy-MM-dd") + "' and t1.paid_time<'" + end.AddDays(1).ToString("yyyy-MM-dd") + "' and t1.platform_type='FBA' and t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;   //增加公司id过滤
            }

            sql += " group by t1.seller_account,t1.website,t1.platform_type";

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                sql += " order by " + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.mAmazonStatistics>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam,"",2*60);

                return obj.AsList();
            }

        }

        /// <summary>
        /// 获取亚马逊的销售统计数据（FBA） 统计
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="account">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        public Models.Orders.mAmazonStatistics ListFBAStatisticsCount(string account, string website, DateTime start, DateTime end, int? companyid, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var sql = @"select sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_product',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) 'platform_fee',sum(t1.cost_first) 'head_fee',count(t1.id) 'order_count',sum(t1.cost_total) 'cost_count',sum(t1.cost_shipping) 'nofba_logisticsfee',sum(t1.profit_total) 'profit_count',(sum(t1.profit_total)/sum(t1.amount_product*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,sum(t1.cost_package) cost_package,count(t1.amount_prepaid>0 or null) as noshippingcount   from dc_base_oms_order t1 ";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku  
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ") ";
                    }
                }
            }

            sql += " where t1.paid_time>='" + start.ToString("yyyy-MM-dd") + "' and t1.paid_time<'" + end.AddDays(1).ToString("yyyy-MM-dd") + "' and t1.platform_type='FBA' and t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;   //增加公司id筛选
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirst<Models.Orders.mAmazonStatistics>(sql, sqlparam,null,2*60);

                return obj;
            }
        }


        /// <summary>
        /// 订单流水
        /// </summary>
        /// <param name="parameter">页面信息</param>
        /// <param name="platform">所属平台</param>
        /// <param name="website">站点</param>
        /// <param name="account">帐号</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">平台单号</param>
        /// <param name="sku">sku编码</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_order> ListOrders(BtTableParameter parameter, string platform, string website, string account, DateTime? start, DateTime? end, string orderno, string sku, int? companyid, ref int total, string skucategoryids, decimal? rate_start, decimal? rate_end, string itemid = null)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t1.origin_order_id,t1.bailun_order_id,t1.platform_type,t1.website,t1.seller_account,t1.platform_order_type,t1.bailun_order_status,t1.bailun_payment_status,t1.bailun_shipping_status,t1.order_currency,(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales,(t1.amount_shipping*t1.seller_order_exchange_rate) amount_shipping,(t1.amount_product*t1.seller_order_exchange_rate) amount_product,(t1.amount_adjustment*t1.seller_order_exchange_rate) amount_adjustment,(t1.cost_promotion*t1.seller_order_exchange_rate) cost_promotion,((if(t1.platform_type='Ebay',t1.seller_other_exchange_rate,t1.seller_order_exchange_rate))*t1.cost_platform_fee) cost_platform_fee,t1.cost_product,t1.cost_first,t1.cost_package,(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,t1.cost_total,(t1.profit_total) profit_total,t1.profit_rate,t1.create_time,t1.order_update_time,t1.profit_oms,t1.cost_handle_bailun,t1.cost_handle_platform,t1.cost_logistics,(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee from dc_base_oms_order t1";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t5 on t1.bailun_order_id=t5.bailun_order_id 
                          join dc_base_sku t6 on t5.bailun_sku=t6.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t6.category_simple_id in (" + s + ") ";
                    }
                }
            }

            var strwhere = " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                strwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    strwhere += " and t1.platform_type in ('Amazon','FBA')";
                    sqlparam.Add("platform_type", platform);
                }
                else
                {
                    strwhere += " and t1.platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                strwhere += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                strwhere += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(orderno))
            {
                strwhere += " and t1.origin_order_id=@origin_order_id";
                sqlparam.Add("origin_order_id", orderno);
            }

            if (!string.IsNullOrWhiteSpace(sku))
            {
                sql += " join dc_base_oms_sku t2 on t1.origin_order_id = t2.origin_order_id and t2.bailun_sku=@bailun_sku";
                sqlparam.Add("bailun_sku", sku);
            }

            if (!string.IsNullOrWhiteSpace(itemid))
            {
                //sql += " join dc_base_oms_platform_sku t3 on t1.bailun_order_id=t3.bailun_order_id and t3.item_id=@itemid";
                sql += $" join (select bailun_order_id,item_id from dc_base_oms_platform_sku where has_delete=0 and has_cancle=0 and item_id=@itemid {(start.HasValue ? " and paid_time>=@ppaid_time_start " : "") + (end.HasValue ? " and paid_time<@ppaid_time_end " : "")} GROUP BY bailun_order_id,item_id) t3 on t1.bailun_order_id=t3.bailun_order_id ";

                if (start.HasValue)
                {
                    sqlparam.Add("ppaid_time_start", start.Value);
                }

                if (end.HasValue)
                {
                    sqlparam.Add("ppaid_time_end", end.Value);
                }
                
                sqlparam.Add("itemid", itemid);
                
            }

            if (start.HasValue)
            {
                strwhere += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (end.HasValue)
            {
                strwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            if (rate_start.HasValue && rate_start.Value != 0)
            {
                strwhere += " and t1.profit_rate>=" + (rate_start.Value / 100);
            }

            if (rate_end.HasValue && rate_end.Value != 0)
            {
                strwhere += " and t1.profit_rate<" + (rate_end.Value / 100);
            }


            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                strwhere += " order by t1." + parameter.sort + " " + parameter.order;
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.dc_base_oms_order>(parameter.pageIndex, parameter.limit, sql + strwhere, ref total, sqlparam);
                var list = obj.AsList();
                var arr = list.Select(p => p.origin_order_id);
                sql = "select origin_order_id,sum(bailun_sku_quantity_ordered) as bailun_sku_quantity_ordered from dc_base_oms_sku where bailun_order_status!='Canceled' and bailun_order_status!='CantHandle' and has_scalp=0 and has_innersale=0 and origin_order_id in ('" + string.Join("','", arr) + "') group by origin_order_id ";

                var skucounts = cn.Query<Models.Orders.dc_base_oms_sku>(sql);
                foreach (var item in list)
                {
                    var m = skucounts.FirstOrDefault(a => a.origin_order_id == item.origin_order_id);
                    item.salecount = m != null ? m.bailun_sku_quantity_ordered : 0;
                }

                return obj.AsList();
            }

        }

        /// <summary>
        /// 订单流水 统计
        /// </summary>
        /// <param name="parameter">页面信息</param>
        /// <param name="platform">所属平台</param>
        /// <param name="website">站点</param>
        /// <param name="account">帐号</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">平台单号</param>
        /// <param name="sku">sku编码</param>
        /// <returns></returns>
        public Models.Orders.dc_base_oms_order ListOrdersCount(string platform, string website, string account, DateTime? start, DateTime? end, string orderno, string sku, int? companyid, string skucategoryids, decimal? rate_start, decimal? rate_end, string itemid = null)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select sum(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales,sum(t1.amount_shipping*t1.seller_order_exchange_rate) amount_shipping,sum(t1.amount_product*t1.seller_order_exchange_rate) amount_product,sum(t1.amount_adjustment*t1.seller_order_exchange_rate) amount_adjustment,sum(t1.cost_promotion*t1.seller_order_exchange_rate) cost_promotion,sum((if(t1.platform_type='Ebay',t1.seller_other_exchange_rate,t1.seller_order_exchange_rate))*t1.cost_platform_fee) cost_platform_fee,sum(t1.cost_product) cost_product,sum(t1.cost_first) cost_first,sum(t1.cost_package) cost_package,sum(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,sum(t1.cost_total) cost_total,sum(t1.profit_total) profit_total,sum(t1.profit_oms) profit_oms,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,sum(t1.cost_logistics) cost_logistics,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee from dc_base_oms_order t1";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t5 on t1.bailun_order_id=t5.bailun_order_id 
                          join dc_base_sku t6 on t5.bailun_sku=t6.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t6.category_simple_id in (" + s + ") ";

                    }
                }
            }

            var strwhere = " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                strwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    strwhere += " and t1.platform_type in ('Amazon','FBA')";
                    sqlparam.Add("platform_type", platform);
                }
                else
                {
                    strwhere += " and t1.platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                strwhere += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                strwhere += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(orderno))
            {
                strwhere += " and t1.origin_order_id=@origin_order_id";
                sqlparam.Add("origin_order_id", orderno);
            }

            if (!string.IsNullOrWhiteSpace(sku))
            {
                sql += " join dc_base_oms_sku t2 on t1.origin_order_id = t2.origin_order_id and t2.bailun_sku=@bailun_sku";
                sqlparam.Add("bailun_sku", sku);
            }

            if (!string.IsNullOrWhiteSpace(itemid))
            {
                //sql += " join dc_base_oms_platform_sku t3 on t1.bailun_order_id=t3.bailun_order_id and t3.item_id=@itemid";
                sql += $" join (select bailun_order_id,item_id from dc_base_oms_platform_sku where has_delete=0 and has_cancle=0 and item_id=@itemid {(start.HasValue ? " and paid_time>=@ppaid_time_start " : "") + (end.HasValue ? " and paid_time<@ppaid_time_end " : "")} GROUP BY bailun_order_id,item_id) t3 on t1.bailun_order_id=t3.bailun_order_id ";

                sqlparam.Add("itemid", itemid);

                if (start.HasValue)
                {
                    sqlparam.Add("ppaid_time_start", start.Value);
                }

                if (end.HasValue)
                {
                    sqlparam.Add("ppaid_time_end", end.Value);
                }
            }

            if (start.HasValue)
            {
                strwhere += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (end.HasValue)
            {
                strwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            if (rate_start.HasValue && rate_start.Value != 0)
            {
                strwhere += " and t1.profit_rate>=" + (rate_start.Value / 100);
            }

            if (rate_end.HasValue && rate_end.Value != 0)
            {
                strwhere += " and t1.profit_rate<" + (rate_end.Value / 100);
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                try
                {
                    var obj = cn.QueryFirst<Models.Orders.dc_base_oms_order>(sql + strwhere, sqlparam);
                    return obj;

                }
                catch (Exception ex)
                {
                    return new Models.Orders.dc_base_oms_order();
                }

            }
        }


        /// <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>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_sku> ListFinanceFee(BtTableParameter parameter, string platform, int feetype, int feecharacter, string account, DateTime? start, DateTime? end, string orderno, int? companyid, ref int total)
        {
            
            var sqlparam = new DynamicParameters();
            var sql = "select t1.origin_order_id,t1.platform_type,t1.website,t1.seller_account,(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales,(t1.cost_platform_fee*if(t1.platform_type='Ebay',t1.seller_other_exchange_rate,t1.seller_order_exchange_rate)) cost_platform_fee,(t1.cost_promotion*t1.seller_order_exchange_rate) cost_promotion,t1.cost_first,(t1.amount_shipping*t1.seller_order_exchange_rate) amount_shipping,t1.cost_logistics,(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,t1.cost_total,t1.amount_total,t1.paid_time from dc_base_oms_order t1";
            
            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    sql += " and t1.platform_type in ('Amazon','FBA')";
                    sqlparam.Add("platform_type", platform);
                }
                else
                {
                    sql += " and platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(orderno))
            {
                sql += " and t1.origin_order_id=@origin_order_id";
                sqlparam.Add("origin_order_id", orderno);
            }

            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                sql += " order by t1." + parameter.sort;

                if (!string.IsNullOrWhiteSpace(parameter.order))
                {
                    sql += (" " + parameter.order);
                }
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.dc_base_oms_sku>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam);

                return obj.AsList();
            }
        }

        /// <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>
        public Models.Orders.dc_base_oms_sku ListFinanceFeeCount(string platform, int feetype, int feecharacter, string account, DateTime? start, DateTime? end, string orderno, int? companyid)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select sum(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales,sum(t1.cost_platform_fee*if(t1.platform_type='Ebay',t1.seller_other_exchange_rate,t1.seller_order_exchange_rate)) cost_platform_fee,sum(t1.cost_promotion*t1.seller_order_exchange_rate) cost_promotion,sum(t1.cost_first) cost_first,sum(t1.amount_shipping*t1.seller_order_exchange_rate) amount_shipping,sum(t1.cost_logistics) cost_logistics,sum(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,sum(t1.cost_total) cost_total,sum(t1.amount_total) amount_total  from dc_base_oms_order t1";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " join dc_base_oms_order t2 on t1.bailun_order_id=t2.bailun_order_id ";
                sql += " and t2.company_id=" + companyid.Value;    //增加公司id过滤
            }

            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (!string.IsNullOrWhiteSpace(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    sql += " and t1.platform_type in ('Amazon','FBA')";
                    sqlparam.Add("platform_type", platform);
                }
                else
                {
                    sql += " and t1.platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(orderno))
            {
                sql += " and t1.origin_order_id=@origin_order_id";
                sqlparam.Add("origin_order_id", orderno);
            }

            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                try
                {
                    var obj = cn.QueryFirst<Models.Orders.dc_base_oms_sku>(sql, sqlparam);
                    return obj;
                }
                catch (Exception ex)
                {
                    return new Models.Orders.dc_base_oms_sku();
                }

            }
        }

        /// <summary>
        /// FBA费用异常订单
        /// </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="total"></param>
        /// <returns></returns>
        public List<Models.Orders.mFBAAbnormalOrder> ListFbaAbnormalOrder(BtTableParameter parameter, string account, string website, DateTime? start, DateTime? end, string orderno, int? companyid, ref int total, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t1.origin_order_id,t1.platform_type,t1.website,t1.seller_account,t1.bailun_sku,t1.order_currency,t1.cost_fba_fee,(t1.cost_fba_fee*t1.seller_order_exchange_rate) fba_fee_rmb,t2.average_fba_fee,t2.min_fba_fee,t2.max_fba_fee,t1.create_time,t1.seller_order_exchange_rate";
            var strwhere = " from dc_mid_fba_fee_avg t2 ";

            strwhere += " join (select t1.* from dc_base_oms_sku t1  ";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                strwhere += " join dc_base_sku t4 on t1.bailun_sku=t4.bailun_sku";
                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        strwhere += " and t4.category_simple_id in (" + s + ") ";

                    }
                }
            }

            strwhere += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.platform_type in ('Amazon','FBA') and t1.has_fba_exception=1 and t1.company_id=1 ";


            if (companyid.HasValue && companyid.Value > 0)
            {
                strwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                strwhere += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                strwhere += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(orderno))
            {
                strwhere += " and t1.origin_order_id=@origin_order_id";
                sqlparam.Add("origin_order_id", orderno);
            }

            if (start.HasValue)
            {
                strwhere += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (end.HasValue)
            {
                strwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            strwhere += " ) t1 on t1.bailun_sku=t2.bailun_sku and t1.website=t2.website";

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                strwhere += " order by " + parameter.sort;

                if (!string.IsNullOrWhiteSpace(parameter.order))
                {
                    strwhere += (" " + parameter.order);
                }
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.mFBAAbnormalOrder>(parameter.pageIndex, parameter.limit, sql + strwhere, ref total, sqlparam, "select count(t1.id) " + strwhere, 2 * 60);

                return obj.AsList();
            }
        }



        public List<Models.Orders.dc_base_oms_order> ListPlatformFeeAbnormal(BtTableParameter parameter, string platform, string account, string website, string orderno, DateTime? start, DateTime? end, int? companyid, ref int total, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();
            var strwhere = "select t1.origin_order_id,t1.bailun_order_id,t1.seller_account,t1.amount_product,t1.cost_platform_fee,(t1.cost_platform_fee/t1.amount_product) platform_fee_rate,t1.platform_type,t1.website,t1.create_time from dc_base_oms_order t1 ";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                strwhere += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                               join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                            ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        strwhere += " and t4.category_simple_id in (" + s + ") ";

                    }
                }
            }

            strwhere += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.has_platform_exception=1 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                strwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    strwhere += " and t1.platform_type in ('Amazon','FBA')";
                    sqlparam.Add("platform_type", platform);
                }
                else
                {
                    strwhere += " and t1.platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }
            }


            if (!string.IsNullOrWhiteSpace(website))
            {
                strwhere += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                strwhere += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(orderno))
            {
                strwhere += " and t1.origin_order_id=@origin_order_id";
                sqlparam.Add("origin_order_id", orderno);
            }

            if (start.HasValue)
            {
                strwhere += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (end.HasValue)
            {
                strwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                strwhere += " order by t1." + parameter.sort;

                if (!string.IsNullOrWhiteSpace(parameter.order))
                {
                    strwhere += (" " + parameter.order);
                }
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.dc_base_oms_order>(parameter.pageIndex, parameter.limit, strwhere, ref total, sqlparam);

                return obj.AsList();
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="account"></param>
        /// <param name="website"></param>
        /// <param name="orderno"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public Models.Orders.dc_base_oms_order ListPlatformFeeAbnormalCount(string platform, string account, string website, string orderno, DateTime? start, DateTime? end, int? companyid, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();
            var strwhere = "select sum(t1.amount_product) amount_product,sum(t1.cost_platform_fee) cost_platform_fee from dc_base_oms_order t1 ";


            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                strwhere += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                               join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                            ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        strwhere += " and t4.category_simple_id in (" + s + ") ";

                    }
                }
            }

            strwhere += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.has_platform_exception=1 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                strwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    strwhere += " and t1.platform_type in ('Amazon','FBA')";
                    sqlparam.Add("platform_type", platform);
                }
                else
                {
                    strwhere += " and t1.platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }
            }


            if (!string.IsNullOrWhiteSpace(website))
            {
                strwhere += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                strwhere += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(orderno))
            {
                strwhere += " and t1.origin_order_id=@origin_order_id";
                sqlparam.Add("origin_order_id", orderno);
            }

            if (start.HasValue)
            {
                strwhere += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (end.HasValue)
            {
                strwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirst<Models.Orders.dc_base_oms_order>(strwhere, sqlparam);

                return obj;
            }
        }


        #endregion

        #region 平台利润

        /// <summary>
        /// 获取平台利润
        /// </summary>
        /// <param name="platform">平台类型</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_sku> ListPlatformProfit(string platform, string website, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, bool isUSD, int? companyid, string skucategoryids, DateTime? createstart=null,DateTime? createend=null)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select tb.platform_type,count(tb.bailun_order_id) order_count,sum(tb.amount_sales*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ") as amount_sales,sum(tb.cost_platform_fee*(if(tb.platform_type='Ebay'," + (isUSD ? "tb.other_to_usd_exchange_rate" : "tb.seller_other_exchange_rate") + "," + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "))) as cost_platform_fee,sum(tb.cost_first*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ") as cost_first,sum(tb.cost_logistics*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ") cost_tail,sum(tb.cost_handle_bailun*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ") cost_handle_bailun,sum(tb.cost_handle_platform*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ") cost_handle_platform,sum(tb.amount_refund*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ") amount_refund,sum(tb.cost_fba_fee*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ") cost_fba_fee,sum(tb.cost_paypal_fee*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ") cost_paypal_fee,sum(tb.amount_shipping*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ") amount_shipping,sum(tb.cost_promotion*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ") cost_promotion,sum(tb.cost_product*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ") cost_product,sum(tb.profit_total*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ") profit_total,(sum(tb.profit_total*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ")/sum(tb.amount_sales*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ")) profit_rate,count((tb.amount_prepaid>0 and tb.bailun_order_status!='Finished') or null) as noshippingcount,sum(tb.amount_prepaid*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ") amount_prepaid  from dc_base_oms_order tb ";

            if (shipstart.HasValue || shipend.HasValue)
            {
                sql += " left join dc_base_oms_pick t1 on tb.bailun_order_id =t1.bailun_order_id ";
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join (select distinct bailun_order_id from dc_base_oms_sku t3
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        //sql += " and t3.bailun_category_id in (" + s + ") ";
                        sql += " and t4.category_simple_id in (" + s + ")";
                    }
                }

                sql += " where t3.bailun_order_status!='Canceled' and ((t3.platform_type!='FBA' and t3.bailun_order_status!='CantHandle') or t3.platform_type='FBA') and t3.has_scalp=0 and t3.has_innersale=0 and t3.bailun_interception_status in ('None','Failed') and t3.has_delete=0  ";
                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and t3.company_id=" + companyid.Value;    //增加公司id过滤
                }

                if (!string.IsNullOrWhiteSpace(platform))
                {
                    sql += " and t3.platform_type='"+ platform + "'";
                }

                if (!string.IsNullOrWhiteSpace(website))
                {
                    sql += " and t3.website='"+website+"'";
                }
                if (start.HasValue)
                {
                    sql += " and t3.paid_time>='"+start.Value.ToString("yyyy-MM-dd")+"'";
                }
                if (end.HasValue)
                {
                    sql += " and t3.paid_time<'"+end.Value.AddDays(1).ToString("yyyy-MM-dd")+"'";
                }

                sql += ") t33 on tb.bailun_order_id=t33.bailun_order_id";

            }
            

            sql += "  where tb.bailun_order_status!='Canceled' and ((tb.platform_type!='FBA' and tb.bailun_order_status!='CantHandle') or tb.platform_type='FBA') and tb.has_scalp=0 and tb.has_innersale=0 and tb.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and tb.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and tb.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and tb.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                sql += " and tb.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and tb.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }
            if (shipstart.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time>=@shipstart) or (tb.platform_type!='FBA' and t1.shipping_time>=@shipstart))";
                sqlparam.Add("shipstart", shipstart.Value);
            }
            if (shipend.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time<@shipend) or (tb.platform_type!='FBA' and t1.shipping_time<@shipend))";
                sqlparam.Add("shipend", shipend.Value.AddDays(1));
            }

            if (createstart.HasValue)
            {
                sql += " and tb.create_time>=@createstart";
                sqlparam.Add("createstart", createstart.Value);
            }
            if (createend.HasValue)
            {
                sql += " and tb.create_time<@createend";
                sqlparam.Add("createend", createend.Value.AddDays(1));
            }
            

            sql += "  group by tb.platform_type";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Orders.dc_base_oms_sku>(sql, sqlparam, null, true, 2 * 60);

                return obj.AsList();
            }

        }

        
        /// <summary>
        /// 获取平台利润
        /// </summary>
        /// <param name="platform">平台类型</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_sku> ListPlatformProfit(string platform, string website, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, bool isUSD, int? companyid, string skucategoryids, int[] producttype, int? skusource, int? shippingstrategy,int statistictype,int? skunewcategoryid,DateTime? createstart = null, DateTime? createend = null)
        {
            var str_statistic_col = "tb.platform_type";

            if(statistictype==1) //sku品类
            {
                str_statistic_col = "t60.bailun_category_id as platform_type";
            }
            else if(statistictype==2) //sku来源
            {
                str_statistic_col = "t60.source as platform_type";
            }

            var sqlparam = new DynamicParameters();
            var sql = $"select {str_statistic_col},count(distinct tb.bailun_order_id) order_count,sum(tb.amount_sales*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "* tb.bailun_sku_quantity_ordered) as amount_sales,sum(tb.cost_platform_fee*(if(tb.platform_type='Ebay'," + (isUSD ? "tb.other_to_usd_exchange_rate" : "tb.seller_other_exchange_rate") + "," + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "))*tb.bailun_sku_quantity_ordered) as cost_platform_fee,sum(tb.cost_first*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) as cost_first,sum(tb.cost_logistics*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_tail,sum(tb.cost_handle_bailun*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_handle_bailun,sum(tb.cost_handle_platform*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_handle_platform,sum(tb.amount_refund*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) amount_refund,sum(tb.cost_fba_fee*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) cost_fba_fee,sum(tb.cost_paypal_fee*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) cost_paypal_fee,sum(tb.amount_shipping*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) amount_shipping,sum(tb.cost_promotion*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) cost_promotion,sum(tb.cost_product*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_product,sum(tb.profit_total*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) profit_total,(sum(tb.profit_total*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ")/sum(tb.amount_sales*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ")) profit_rate,count(distinct (case when (tb.amount_prepaid>0 and tb.bailun_order_status!='Finished') then tb.bailun_order_id else null end)) as noshippingcount,sum(tb.amount_prepaid*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) amount_prepaid  from dc_base_oms_sku tb ";

            if (shipstart.HasValue || shipend.HasValue)
            {
                sql += " left join dc_base_oms_pick t1 on tb.bailun_order_id =t1.bailun_order_id ";
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join (select distinct bailun_order_id from dc_base_oms_sku t3
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        //sql += " and t3.bailun_category_id in (" + s + ") ";
                        sql += " and t4.category_simple_id in (" + s + ")";
                    }
                }

                sql += " where t3.bailun_order_status!='Canceled' and ((t3.platform_type!='FBA' and t3.bailun_order_status!='CantHandle') or t3.platform_type='FBA') and t3.has_scalp=0 and t3.has_innersale=0 and t3.bailun_interception_status in ('None','Failed') and t3.has_delete=0 ";
                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and t3.company_id=" + companyid.Value;    //增加公司id过滤
                }

                if (!string.IsNullOrWhiteSpace(platform))
                {
                    sql += " and t3.platform_type='" + platform + "'";
                }

                if (!string.IsNullOrWhiteSpace(website))
                {
                    sql += " and t3.website='" + website + "'";
                }
                if (start.HasValue)
                {
                    sql += " and t3.paid_time>='" + start.Value.ToString("yyyy-MM-dd") + "'";
                }
                if (end.HasValue)
                {
                    sql += " and t3.paid_time<'" + end.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
                }

                sql += ") t33 on tb.bailun_order_id=t33.bailun_order_id";

            }

            //Add by Allan at 20200320，for 增加sku级别的利润统计
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue)
            {
                sql += " join dc_base_sku t10 on tb.bailun_sku=t10.bailun_sku ";

                if (producttype.Count()>0)
                {
                    sql += " and t10.product_type in (" + string.Join(",",producttype)+") ";
                }

                if (skusource.HasValue)
                {
                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3海外仓; 4FBA仓
                {
                    if (shippingstrategy.Value != 1)
                    {
                        sql += " join dc_base_warehouse t20 on tb.warehouse_code = t20.warehouse_code ";

                        if (shippingstrategy.Value == 2)  //中国发货
                        {
                            sql += "  and t20.area_id=18 ";
                            
                        }
                        else if (shippingstrategy.Value == 3)  //海外仓
                        {
                            sql += " and t20.hq_type='第三方仓库' ";
                        }
                        else if (shippingstrategy.Value == 4)  //FBA仓
                        {
                            sql += " and t20.hq_type='FBA仓' ";
                        }

                    }
                }
            }

            if (statistictype == 1)  //sku品类
            {
                sql += " join dc_base_sku t60 on tb.bailun_sku=t60.bailun_sku ";

                if (skunewcategoryid.HasValue)
                {
                    var str_children_category = Services.CommonServices.BailunNewCategory(skunewcategoryid.Value, null);
                    if (str_children_category == "")
                    {
                        str_children_category = skunewcategoryid.Value + "";
                    }

                    sql += " and t60.bailun_category_id in (" + str_children_category + ")";
                }
            }
            else if (statistictype == 2)   //sku来源
            {
                sql += " join dc_base_sku t60 on tb.bailun_sku=t60.bailun_sku and t60.source in (1,2,3,6,7,11) ";
            }


            sql += "  where tb.bailun_order_status!='Canceled' and ((tb.platform_type!='FBA' and tb.bailun_order_status!='CantHandle') or tb.platform_type='FBA') and tb.has_scalp=0 and tb.has_innersale=0 and tb.bailun_interception_status in ('None','Failed') and tb.has_delete=0 ";
            

            if (shippingstrategy.HasValue)  //1专线;2中国发货;3海外仓; 4FBA仓
            {
                var listSpecialLogistics = CommonServices.ListLogisticsConfig(1);

                if (shippingstrategy.Value == 1)
                {
                    sql += " and tb.logistics_method_code in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                }
                else if (shippingstrategy.Value == 2)
                {
                    sql += " and tb.logistics_method_code not in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                }
                
            }
            
            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and tb.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and tb.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and tb.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                sql += " and tb.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and tb.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }
            if (shipstart.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time>=@shipstart) or (tb.platform_type!='FBA' and t1.shipping_time>=@shipstart))";
                sqlparam.Add("shipstart", shipstart.Value);
            }
            if (shipend.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time<@shipend) or (tb.platform_type!='FBA' and t1.shipping_time<@shipend))";
                sqlparam.Add("shipend", shipend.Value.AddDays(1));
            }

            if (createstart.HasValue)
            {
                sql += " and tb.create_time>=@createstart";
                sqlparam.Add("createstart", createstart.Value);
            }
            if (createend.HasValue)
            {
                sql += " and tb.create_time<@createend";
                sqlparam.Add("createend", createend.Value.AddDays(1));
            }

            if (statistictype == 0)
            {
                sql += "  group by tb.platform_type";
            }
            else if (statistictype == 1) //sku品类
            {
                sql += " group by t60.bailun_category_id";
            }
            else if (statistictype == 2)
            {
                sql += " group by t60.source";
            }
            
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Orders.dc_base_oms_sku>(sql, sqlparam, null, true, 2 * 60);

                return obj.AsList();
            }

        }

        
        /// <summary>
        /// 根据发货时间获取平台利润统计
        /// </summary>
        /// <param name="platform">平台类型</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="shipstart">发货开始时间</param>
        /// <param name="shipend">发货结束时间</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_sku> ListPlatformProfitByShipTime(string platform, string website, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, bool isUSD, int? companyid, string skucategoryids, int[] producttype, int? skusource, int? shippingstrategy,int statistictype, int? skunewcategoryid)
        {
            var str_statistic_col = "t2.platform_type";

            if (statistictype == 1)  //sku品类
            {
                str_statistic_col = "t60.bailun_category_id as platform_type";
            }
            else if (statistictype == 2) //sku来源
            {
                str_statistic_col = "t60.source as platform_type";
            }

            var sqlparam = new DynamicParameters();
            var sql = $@"select {str_statistic_col},count(DISTINCT t2.bailun_order_id) order_count,sum(t2.amount_sales*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) as amount_sales,sum(t2.cost_platform_fee*(if(t2.platform_type='Ebay'," + (isUSD ? "t2.other_to_usd_exchange_rate" : "t2.seller_other_exchange_rate") + "," + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "))*t1.quantity_shipped) as cost_platform_fee,sum(t2.cost_first*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) as cost_first,sum(t2.cost_logistics*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_tail,sum(t2.cost_handle_bailun*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_handle_bailun,sum(t2.cost_handle_platform*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_handle_platform,sum(t2.amount_refund*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) amount_refund,sum(t2.cost_product*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_product,sum(t2.profit_total*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) profit_total,(sum(t2.profit_total*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped)/sum(t2.amount_sales*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped)) profit_rate,count(distinct (case when (t2.amount_prepaid>0 and t2.bailun_order_status!='Finished') then t2.bailun_order_id else null end)) as noshippingcount,sum(t2.amount_prepaid*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) amount_prepaid,sum(t2.cost_fba_fee*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) cost_fba_fee,sum(t2.cost_paypal_fee*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) cost_paypal_fee,sum(t2.amount_shipping*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) amount_shipping,sum(t2.cost_promotion*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) cost_promotion from (select t0.id,t0.bailun_order_id,t0.quantity_shipped,t0.bailun_sku from dc_base_oms_pick t0 ";
            

            var tempsql = "";

            if (shippingstrategy.HasValue) //1专线;2中国发货;3海外仓 4 FBA仓
            {
                var listSpecialLogistics = CommonServices.ListLogisticsConfig(1);

                if (shippingstrategy.Value == 1)  //专线
                {
                    tempsql = " and t0.logistics_order_id in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "') ";
                }
                else if (shippingstrategy.Value == 2)  //中国发货
                {
                    sql += " join dc_base_warehouse t2 on t0.warehouse_code=t2.warehouse_code and t2.area_id=18 ";
                    tempsql = " and t0.logistics_order_id  not in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "') ";
                }
                else if (shippingstrategy.Value == 3)  //海外仓
                {
                    sql += " join dc_base_warehouse t2 on t0.warehouse_code=t2.warehouse_code and t2.hq_type='第三方仓库' ";
                }
                else if (shippingstrategy.Value == 4)  //FBA仓
                {
                    sql += " join dc_base_warehouse t2 on t0.warehouse_code=t2.warehouse_code and t2.hq_type='FBA仓' ";
                }
            }

            sql += " where t0.has_delete=0 and t0.shipping_status = 'TotalShipping'"+ tempsql;

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t0.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (shipstart.HasValue)
            {
                sql += " and t0.shipping_time>='" + shipstart.Value.ToString("yyyy-MM-dd") + "'";
            }
            if (shipend.HasValue)
            {
                sql += " and t0.shipping_time<'" + shipend.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }

            sql += " ) t1 ";
            sql += " join dc_base_oms_sku t2 on t1.bailun_order_id = t2.bailun_order_id  and t1.bailun_sku=t2.bailun_sku  and t2.bailun_order_status != 'Canceled' and t2.has_scalp = 0 and ((t2.platform_type!='FBA' and t2.bailun_order_status!='CantHandle') or t2.platform_type='FBA') and t2.has_scalp = 0 and t2.has_innersale = 0  and t2.has_delete=0  ";

            //Add by Allan at 20200325
            if (statistictype == 1)  //sku品类
            {
                sql += " join dc_base_sku t60 on t2.bailun_sku=t60.bailun_sku ";

                if (skunewcategoryid.HasValue)
                {
                    var str_children_category = Services.CommonServices.BailunNewCategory(skunewcategoryid.Value, null);
                    if (str_children_category == "")
                    {
                        str_children_category = skunewcategoryid.Value + "";
                    }

                    sql += " and t60.bailun_category_id in (" + str_children_category + ")";
                }

            }
            else if (statistictype == 2) //sku来源
            {
                sql += " join dc_base_sku t60 on t2.bailun_sku=t60.bailun_sku and t60.source in (1,2,3,6,7,11) ";
            }


            //Add by Allan at 20200320，for 增加sku级别的利润统计
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue)
            {
                sql += " join dc_base_sku t10 on t2.bailun_sku=t10.bailun_sku ";

                if (producttype.Count() > 0)
                {
                    sql += " and t10.product_type in ("+string.Join(",", producttype)+") ";
                }

                if (skusource.HasValue)
                {
                    sql += " and t10.source="+skusource;
                }
            }
            
            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t2.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and t2.website=@website";
                sqlparam.Add("website", website);

            }

            if (start.HasValue)
            {
                sql += " and t2.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t2.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += " join dc_base_sku t4 on t2.bailun_sku=t4.bailun_sku ";
                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        //sql += " and t4.bailun_category_id in (" + s + ") ";
                        sql += " and t4.category_simple_id in (" + s + ") ";
                    }
                }
            }

            var strwhere = " ";
            
            //Edit by Allan at 20200325
            if (statistictype == 0)
            {
                strwhere += "  group by t2.platform_type";
            }
            else if (statistictype == 1)  //sku品类
            {
                sql += " group by t60.bailun_category_id";
            }
            else if (statistictype == 2) //sku来源
            {
                sql += "  group by t60.source ";
            }



            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Orders.dc_base_oms_sku>(sql + strwhere, sqlparam, null, true, 10 * 60);

                return obj.AsList();
            }
        }


        /// <summary>
        /// 获取平台利润 按站点
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="parameter"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<Models.Orders.mPlatformProfit> ListPlatformProfitByWebSite(string platform, DateTime? start, DateTime? end, BtTableParameter parameter, int? companyid, ref int total)
        {
            var sqlparam = new DynamicParameters();

            //var precolumn = "select website,platform_type as platform,sum(amount_prepaid) amount_prepaid  from dc_base_oms_sku where bailun_order_status!='Canceled'  and bailun_order_status!='CantHandle' ";
            var sql = "select t1.platform_type as platform,t1.website,sum(t1.amount_sales*t1.seller_order_exchange_rate) saleamount,count(t1.bailun_order_id) ordercount,sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) platformfee,(sum(t1.amount_sales*t1.seller_order_exchange_rate)/count(t1.bailun_order_id)) customerprice,sum(t1.profit_total) profit,(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) profitrate,sum(t1.amount_refund*t1.seller_order_exchange_rate) returnamount,(sum(t1.amount_refund)/sum(t1.amount_sales)) returnamountrate,sum(t1.cost_first) cost_first,sum(t1.cost_logistics) cost_tail,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,sum(t1.amount_prepaid) amount_prepaid from dc_base_oms_order t1 ";

            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            sql += " group by t1.website,t1.platform_type";

            if (!string.IsNullOrEmpty(parameter.sort))
            {
                sql += " order by t1." + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.mPlatformProfit>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam);


                return obj.AsList();
            }
        }

        /// <summary>
        /// 获取平台利润 按站点 统计
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="parameter"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public Models.Orders.mPlatformProfit ListPlatformProfitByWebSiteCount(string platform, DateTime? start, DateTime? end, BtTableParameter parameter, int? companyid, ref int total)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select sum(t1.amount_sales*t1.seller_order_exchange_rate) saleamount,count(t1.bailun_order_id) ordercount,sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) platformfee,(sum(t1.amount_sales*t1.seller_order_exchange_rate)/count(t1.bailun_order_id)) customerprice,sum(t1.profit_total) profit,(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) profitrate,sum(t1.amount_refund*t1.seller_order_exchange_rate) returnamount,(sum(t1.amount_refund)/sum(t1.amount_sales)) returnamountrate,sum(t1.cost_first) cost_first,sum(t1.cost_logistics) cost_tail,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,sum(t1.amount_prepaid) amount_prepaid  from dc_base_oms_order t1 ";

            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirst<Models.Orders.mPlatformProfit>(sql, sqlparam);

                return obj;
            }
        }

        /// <summary>
        /// 利润统计订单明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="platform">平台信息</param>
        /// <param name="website">站点信息</param>
        /// <param name="account">销售帐号</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">百伦单号</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_order> ListPlatformProfitOrders(BtTableParameter parameter, string platform, string website, string account, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, string orderno, int? companyid, ref int total, decimal? rate_start, decimal? rate_end)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t1.platform_type,t1.website,t1.origin_order_id,t1.bailun_order_id,t1.seller_account,t1.order_currency,(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales,(t1.amount_product*t1.seller_order_exchange_rate) amount_product,(t1.amount_shipping*t1.seller_order_exchange_rate) amount_shipping,(t1.amount_tax*t1.seller_order_exchange_rate) amount_tax,(t1.amount_adjustment*t1.seller_order_exchange_rate) amount_adjustment,(t1.amount_gift_wrap*t1.seller_order_exchange_rate) amount_gift_wrap,(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,(t1.cost_total) cost_total,(t1.cost_promotion*t1.seller_order_exchange_rate) cost_promotion,(t1.cost_platform_fee*t1.seller_order_exchange_rate) cost_platform_fee,(t1.cost_product) cost_product,(t1.cost_shipping) cost_shipping,(t1.cost_package*t1.seller_order_exchange_rate) cost_package,(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,(t1.cost_refund_commisson*t1.seller_order_exchange_rate) cost_refund_commisson,(t1.cost_handle_bailun) cost_handle_bailun,(t1.cost_handle_platform) cost_handle_platform,(t1.cost_logistics) cost_tail,(t1.cost_first) cost_first,(t1.profit_total) profit_total,((t1.profit_total)/(t1.amount_sales*t1.seller_order_exchange_rate)) profit_rate,t1.create_time,t1.paid_time,t1.seller_order_exchange_rate,t1.seller_other_exchange_rate,(t1.amount_prepaid) amount_prepaid,t1.cost_logistics from dc_base_oms_order t1 ";

            if (shipstart.HasValue || shipend.HasValue)
            {
                sql += " join (select bailun_order_id from dc_base_oms_pick where shipping_status='TotalShipping' ";
                if (shipstart.HasValue)
                {
                    sql += " and shipping_time>=@shipstart ";
                    sqlparam.Add("shipstart", shipstart.Value);
                }
                if (shipend.HasValue)
                {
                    sql += " and shipping_time<@shipend";
                    sqlparam.Add("shipend", shipend.Value.AddDays(1));
                }

                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and company_id=" + companyid.Value;    //增加公司id过滤
                }

                sql += " group by bailun_order_id) t2 on t1.bailun_order_id=t2.bailun_order_id ";
            }

            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }
            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and (t1.bailun_order_id=@bailun_order_id or t1.origin_order_id=@bailun_order_id)";
                sqlparam.Add("bailun_order_id", orderno);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            //利润率
            if (rate_start.HasValue && rate_start.Value != 0)
            {
                sql += " and t1.profit_rate>=" + (rate_start.Value / 100);
            }

            if (rate_end.HasValue && rate_end.Value != 0)
            {
                sql += " and t1.profit_rate<" + (rate_end.Value / 100);
            }

            if (!string.IsNullOrEmpty(parameter.sort))
            {
                sql += " order by t1." + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.dc_base_oms_order>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam, "", 2 * 60);

                return obj.AsList();
            }

        }

        /// <summary>
        /// 利润统计订单明细 统计
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public Models.Orders.dc_base_oms_order ListPlatformProfitOrdersCount(string platform, string website, string account, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, string orderno, int? companyid, decimal? rate_start, decimal? rate_end)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select sum(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales,sum(t1.amount_product*t1.seller_order_exchange_rate) amount_product,sum(t1.amount_shipping*t1.seller_order_exchange_rate) amount_shipping,sum(t1.amount_tax*t1.seller_order_exchange_rate) amount_tax,sum(t1.amount_adjustment*t1.seller_order_exchange_rate) amount_adjustment,sum(t1.amount_gift_wrap*t1.seller_order_exchange_rate) amount_gift_wrap,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_total) cost_total,sum(t1.cost_promotion*t1.seller_order_exchange_rate) cost_promotion,sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) cost_platform_fee,sum(t1.cost_product) cost_product,sum(t1.cost_shipping) cost_shipping,sum(t1.cost_package*t1.seller_order_exchange_rate) cost_package,sum(t1.cost_fba_fee*t1.seller_order_exchange_rate) cost_fba_fee,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,sum(t1.cost_refund_commisson*t1.seller_order_exchange_rate) cost_refund_commisson,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,sum(t1.cost_logistics) cost_tail,sum(t1.cost_first) cost_first,sum(t1.profit_total) profit_total,(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) profit_rate,sum(t1.amount_prepaid) amount_prepaid,sum(t1.cost_logistics) cost_logistics from dc_base_oms_order t1 ";

            if (shipstart.HasValue || shipend.HasValue)
            {
                sql += " join (select bailun_order_id from dc_base_oms_pick where shipping_status='TotalShipping' ";
                if (shipstart.HasValue)
                {
                    sql += " and shipping_time>=@shipstart ";
                    sqlparam.Add("shipstart", shipstart.Value);
                }
                if (shipend.HasValue)
                {
                    sql += " and shipping_time<@shipend";
                    sqlparam.Add("shipend", shipend.Value.AddDays(1));
                }

                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and company_id=" + companyid.Value;    //增加公司id过滤
                }

                sql += " group by bailun_order_id) t2 on t1.bailun_order_id=t2.bailun_order_id ";
            }

            sql += " where t1.bailun_order_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA')  and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }
            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and (t1.bailun_order_id=@bailun_order_id or t1.origin_order_id=@bailun_order_id) ";
                sqlparam.Add("bailun_order_id", orderno);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            //利润率
            if (rate_start.HasValue && rate_start.Value != 0)
            {
                sql += " and t1.profit_rate>=" + (rate_start.Value / 100);
            }

            if (rate_end.HasValue && rate_end.Value != 0)
            {
                sql += " and t1.profit_rate<" + (rate_end.Value / 100);
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<Models.Orders.dc_base_oms_order>(sql, sqlparam);
                return obj;
            }
        }

        /// <summary>
        /// 销售订单
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehouse">仓库信息</param>
        /// <param name="seller">销售帐号</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">百伦订单号</param>
        /// <param name="sku">sku编码</param>
        /// <param name="total">符合条件的记录数</param>
        /// <param name="isFBA">是否FBA订单</param>
        /// <returns></returns>
        public List<Models.Orders.mSkuOrder> ListSkuOrder(BtTableParameter parameter, string warehousetype, string warehouse, string seller, DateTime? start, DateTime? end, string orderno, string sku, string orderstatus, string shippingstatus, ref int total, int isFBA, int? companyid)
        {
            var sqlparam = new DynamicParameters();
            var sqlwhere = "";
            var sql = @"select t1.transaction_id,t1.bailun_sku,t2.sku_image,t2.category_name,t2.sku_title_en,t2.sku_title_cn,t1.amount_product/t1.bailun_sku_quantity_ordered 'price',t1.bailun_sku_quantity_ordered,t1.amount_product,t1.order_currency,t1.platform_type,t1.website,t1.seller_account,t1.seller_name,t1.bailun_order_id,t1.origin_order_id,t1.bailun_order_status,t1.warehouse_name,t1.shipping_status,t1.create_time,t1.order_update_time,t1.gmt_modified from dc_base_oms_sku t1
                                left join dc_base_sku t2 on t1.bailun_sku = t2.bailun_sku
                                left join dc_base_warehouse t3 on t1.warehouse_code=t3.warehouse_code
                                ";

            sqlwhere += " where t1.bailun_order_status != 'Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sqlwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            sqlwhere += " and t1.platform_type" + (isFBA == 1 ? "" : "!") + "='FBA'";

            if (!string.IsNullOrWhiteSpace(warehousetype))
            {
                sqlwhere += " and t3.hq_type=@hq_type";
                sqlparam.Add("hq_type", warehousetype);
            }

            if (!string.IsNullOrWhiteSpace(warehouse))
            {
                sqlwhere += " and t1.warehouse_code=@warehouse_code";
                sqlparam.Add("warehouse_code", warehouse);
            }

            if (!string.IsNullOrWhiteSpace(seller))
            {
                sqlwhere += " and t1.seller_name=@seller_name";
                sqlparam.Add("seller_name", seller);
            }

            if (start.HasValue)
            {
                sqlwhere += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sqlwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value);
            }
            if (!string.IsNullOrWhiteSpace(orderno))
            {
                sqlwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value);
            }
            if (!string.IsNullOrWhiteSpace(orderno))
            {
                sqlwhere += " and t1.bailun_order_id=@bailun_order_id";
                sqlparam.Add("bailun_order_id", orderno);
            }
            if (!string.IsNullOrWhiteSpace(sku))
            {
                sqlwhere += " and t1.bailun_sku=@bailun_sku";
                sqlparam.Add("bailun_sku", sku);
            }

            if (!string.IsNullOrWhiteSpace(orderstatus))
            {
                sqlwhere += " and t1.bailun_order_status=@bailun_order_status";
                sqlparam.Add("bailun_order_status", orderstatus);
            }
            if (!string.IsNullOrWhiteSpace(shippingstatus))
            {
                sqlwhere += " and t1.shipping_status=@shipping_status";
                sqlparam.Add("shipping_status", shippingstatus);
            }

            if (!string.IsNullOrEmpty(parameter.sort))
            {
                sqlwhere += " order by t1." + parameter.sort;

                if (!string.IsNullOrEmpty(parameter.order))
                {
                    sqlwhere += " " + parameter.order;
                }
            }
            else
            {
                sqlwhere += " order by t1.paid_time desc";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.mSkuOrder>(parameter.pageIndex, parameter.limit, sql + sqlwhere, ref total, sqlparam, "select count(t1.origin_order_id) from dc_base_oms_sku t1 left join dc_base_sku t2 on t1.bailun_sku = t2.bailun_sku left join dc_base_warehouse t3 on t1.warehouse_code = t3.warehouse_code" + sqlwhere);

                return obj.AsList();
            }

        }

        /// <summary>
        /// 销售订单 统计
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehouse">仓库信息</param>
        /// <param name="seller">销售帐号</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="orderno">百伦订单号</param>
        /// <param name="sku">sku编码</param>
        /// <param name="total">符合条件的记录数</param>
        /// <param name="isFBA">是否FBA订单</param>
        /// <returns></returns>
        public Models.Orders.mSkuOrder ListSkuOrderCount(string warehousetype, string warehouse, string seller, DateTime? start, DateTime? end, string orderno, string sku, string orderstatus, string shippingstatus, int isFBA, int? companyid)
        {
            var sqlparam = new DynamicParameters();
            var sqlwhere = "";
            var sql = @"select sum(t1.bailun_sku_quantity_ordered) bailun_sku_quantity_ordered,sum(t1.amount_product) amount_product from dc_base_oms_sku t1
                                left join dc_base_sku t2 on t1.bailun_sku = t2.bailun_sku
                                left join dc_base_warehouse t3 on t1.warehouse_code=t3.warehouse_code
                                ";

            sqlwhere += " where t1.bailun_order_status != 'Canceled'  and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sqlwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            sqlwhere += " and t1.platform_type" + (isFBA == 1 ? "" : "!") + "='FBA'";

            if (!string.IsNullOrWhiteSpace(warehousetype))
            {
                sqlwhere += " and t3.hq_type=@hq_type";
                sqlparam.Add("hq_type", warehousetype);
            }

            if (!string.IsNullOrWhiteSpace(warehouse))
            {
                sqlwhere += " and t1.warehouse_code=@warehouse_code";
                sqlparam.Add("warehouse_code", warehouse);
            }

            if (!string.IsNullOrWhiteSpace(seller))
            {
                sqlwhere += " and t1.seller_name=@seller_name";
                sqlparam.Add("seller_name", seller);
            }

            if (start.HasValue)
            {
                sqlwhere += " and t1.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sqlwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value);
            }
            if (!string.IsNullOrWhiteSpace(orderno))
            {
                sqlwhere += " and t1.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value);
            }
            if (!string.IsNullOrWhiteSpace(orderno))
            {
                sqlwhere += " and t1.bailun_order_id=@bailun_order_id";
                sqlparam.Add("bailun_order_id", orderno);
            }
            if (!string.IsNullOrWhiteSpace(sku))
            {
                sqlwhere += " and t1.bailun_sku=@bailun_sku";
                sqlparam.Add("bailun_sku", sku);
            }

            if (!string.IsNullOrWhiteSpace(orderstatus))
            {
                sqlwhere += " and t1.bailun_order_status=@bailun_order_status";
                sqlparam.Add("bailun_order_status", orderstatus);
            }
            if (!string.IsNullOrWhiteSpace(shippingstatus))
            {
                sqlwhere += " and t1.shipping_status=@shipping_status";
                sqlparam.Add("shipping_status", shippingstatus);
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                try
                {
                    var obj = cn.QueryFirst<Models.Orders.mSkuOrder>(sql + sqlwhere, sqlparam);

                    return obj;
                }
                catch (Exception ex)
                {
                    return new Models.Orders.mSkuOrder();
                }

            }
        }

        /// <summary>
        /// 订单汇总 sku维度
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="platform">平台</param>
        /// <param name="account">销售帐号</param>
        /// <param name="website">站点</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="sku">sku编码</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<Models.Orders.mSkuSaleCount> ListSkuSaleCount(BtTableParameter parameter, string platform, string account, string website, string warehouse, DateTime? start, DateTime? end, string sku, int? companyid, ref int total)
        {
            var sqlparam = new DynamicParameters();
            var strwhere = "";
            var sql = "select platform_type,bailun_sku,warehouse_name,count(origin_order_id) ordercount,sum(bailun_sku_quantity_ordered) count,sum(bailun_sku_quantity_shipped) shippingcount from dc_base_oms_sku where bailun_order_status!='Canceled' and warehouse_code!='' and ((platform_type!='FBA' and bailun_order_status!='CantHandle') or platform_type='FBA') and has_scalp=0 and has_innersale=0 and bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                strwhere += " and platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                strwhere += " and website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                strwhere += " and seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (start.HasValue)
            {
                strwhere += " and paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (!string.IsNullOrWhiteSpace(sku))
            {
                strwhere += " and bailun_sku>=@bailun_sku";
                sqlparam.Add("bailun_sku", sku);
            }

            if (end.HasValue)
            {
                strwhere += " and paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            strwhere += "  group by platform_type,bailun_sku,warehouse_name";

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                strwhere += " order by " + parameter.sort;

                if (!string.IsNullOrWhiteSpace(parameter.order))
                {
                    strwhere += (" " + parameter.order);
                }
            }



            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.mSkuSaleCount>(parameter.pageIndex, parameter.limit, sql + strwhere, ref total, sqlparam);

                return obj.AsList();
            }

        }

        /// <summary>
        /// 订单汇总 sku维度 统计
        /// </summary>
        /// <param name="platform">分页信息</param>
        /// <param name="account">平台</param>
        /// <param name="website">销售帐号</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="sku">sku编码</param>
        /// <returns></returns>
        public Models.Orders.mSkuSaleCount ListSkuSaleCounts(string platform, string account, string website, string warehouse, DateTime? start, DateTime? end, string sku, int? companyid)
        {
            var sqlparam = new DynamicParameters();
            var strwhere = "";
            var sql = "select count(origin_order_id) ordercount,sum(bailun_sku_quantity_ordered) count,sum(bailun_sku_quantity_shipped) shippingcount from dc_base_oms_sku where bailun_order_status!='Canceled' and ((platform_type!='FBA' and bailun_order_status!='CantHandle') or platform_type='FBA') and has_scalp=0 and has_innersale=0 and warehouse_code!='' and bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                strwhere += " and platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                strwhere += " and website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                strwhere += " and seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (start.HasValue)
            {
                strwhere += " and paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }

            if (!string.IsNullOrWhiteSpace(sku))
            {
                strwhere += " and bailun_sku>=@bailun_sku";
                sqlparam.Add("bailun_sku", sku);
            }

            if (end.HasValue)
            {
                strwhere += " and paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                try
                {
                    var obj = cn.QueryFirst<Models.Orders.mSkuSaleCount>(sql + strwhere, sqlparam);

                    return obj;
                }
                catch (Exception ex)
                {
                    return new Models.Orders.mSkuSaleCount();
                }

            }

        }

        /// <summary>
        /// 获取Sku分类利润
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="colname">需要统计的字段</param>
        /// <returns></returns>
        public List<mSkuCategoryProfit> ListSkuCategoryProfit(string platform, DateTime start, DateTime end, string colname, string skucategoryids)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sqlwhere = "";
                var sqlparam = new DynamicParameters();
                var showcol = "";
                var selcol = "";
                if (colname.Trim() == "amount_sales" || colname.Trim() == "cost_platform_fee")
                {
                    showcol = $"sum(t0.{colname.Trim()})";
                    selcol = $"(t1.{colname.Trim()}*t1.bailun_sku_quantity_shipped*t1.seller_order_exchange_rate) as {colname.Trim()}";
                }
                else if (colname.Trim() == "order_count")
                {
                    showcol = $"count(distinct t0.bailun_order_id)";
                    selcol = $"t1.bailun_order_id";
                }
                else if (colname.Trim() == "noshippingcount")
                {
                    showcol = $"count(amount_prepaid)";
                    selcol = "(if(t1.amount_prepaid>0,t1.amount_prepaid,null)) amount_prepaid";
                }
                else
                {
                    showcol = $"sum(t0.{colname.Trim()})";
                    selcol = $"t1.{colname.Trim()}";
                }

                if (!string.IsNullOrEmpty(platform))
                {
                    sqlwhere += " and t1.platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }

                var sql = $@"select {showcol} as count,t0.platform_type,t2.category_simple_id,t2.category_simple_name from (select t1.bailun_sku,{selcol},platform_type from dc_base_oms_sku t1 where t1.has_scalp=0 and t1.has_delete=0 and t1.has_innersale=0 and t1.bailun_order_status!='Canceled' and t1.has_innersale=0  and t1.bailun_interception_status in ('None','Failed') and t1.company_id=1 and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA')
                            and t1.paid_time >= '{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.paid_time < '{end.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")}' {sqlwhere}) t0
                            left join dc_base_sku t2 on t0.bailun_sku = t2.bailun_sku
                            group by t0.platform_type,t2.category_simple_id";

                var obj = cn.Query<mSkuCategoryProfit>(sql, sqlparam, null, true, 2 * 60).AsList();

                return obj;
            }
        }

        #endregion

        #region Ebay

        /// <summary>
        /// Ebay 销售统计记录
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="website">站点信息</param>
        /// <param name="account">帐号信息</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="warehousetype">发货仓库类型</param>
        /// <param name="warehousecode">发货仓库编码</param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_order> ListEbayStatistics(BtTableParameter parameter, string website, string account, DateTime? start, DateTime? end, string warehousetype, string warehousecode, int? companyid, ref int total, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var sql = @"select t1.platform_type,t1.seller_account,t1.website,sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_sales',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_other_exchange_rate) 'cost_platform_fee',sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) as cost_paypal_fee,sum(t1.cost_first) 'cost_first',count(t1.bailun_order_id) 'order_count',sum(t1.cost_total) 'cost_total',sum(t1.cost_logistics) 'cost_tail',sum(t1.profit_total) 'profit_total',(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,count(t1.amount_prepaid>0 or null) as noshippingcount,sum(t1.cost_logistics) cost_logistics  from dc_base_oms_order t1";

            if (!string.IsNullOrEmpty(warehousetype))
            {
                sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_type_ex=@warehoursetype";
                sqlparam.Add("warehoursetype", warehousetype);
            }
            if (!string.IsNullOrEmpty(warehousecode))
            {
                if (!string.IsNullOrEmpty(warehousetype))
                {
                    sql += " and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
                else
                {
                    sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku  
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ") ";
                    }
                }
            }


            var fromsql = " where t1.platform_type='Ebay' and t1.bailun_order_status!='Canceled' and t1.bailun_order_status!='CantHandle' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                fromsql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                fromsql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                fromsql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                fromsql += " and t1.paid_time>='" + start.Value.ToString("yyyy-MM-dd") + "'";
            }

            if (end.HasValue)
            {
                fromsql += " and t1.paid_time<'" + end.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }

            var prefromsql = fromsql;
            fromsql += " group by t1.seller_account,t1.website,t1.platform_type";

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                fromsql += " order by " + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.dc_base_oms_order>(parameter.pageIndex, parameter.limit, sql + fromsql, ref total, sqlparam);

                return obj.AsList();
            }
        }


        /// <summary>
        /// Ebay 销售统计记录 统计
        /// </summary>
        /// <param name="website"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public Models.Orders.dc_base_oms_order ListEbayStatisticsCount(string platform, string website, string account, DateTime? start, DateTime? end, string warehousetype, string warehousecode, int? companyid, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var sql = @"select sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_sales',sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) 'cost_paypal_fee',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_other_exchange_rate) 'cost_platform_fee',sum(t1.cost_first) 'cost_first',count(t1.bailun_order_id) 'order_count',sum(t1.cost_total) 'cost_total',sum(t1.cost_logistics) 'cost_tail',sum(t1.profit_total) 'profit_total',(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,count(t1.amount_prepaid>0 or null) as noshippingcount,sum(t1.cost_logistics) cost_logistics  from dc_base_oms_order t1";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ") ";

                    }
                }
            }

            var sqlwhere = " where t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sqlwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrEmpty(platform))
            {
                if (platform.ToUpper().Trim() != "FBA")
                {
                    sqlwhere += "  and t1.bailun_order_status!='CantHandle' ";
                }

                sqlwhere += " and t1.platform_type=@platform ";
                sqlparam.Add("platform", platform);
            }

            if (!string.IsNullOrEmpty(warehousetype) || (!string.IsNullOrEmpty(warehousetype) && !string.IsNullOrEmpty(warehousecode)))
            {
                sql += " join  dc_base_oms_pick t2 on t1.origin_order_id=t2.origin_order_id " + (!string.IsNullOrEmpty(warehousecode) ? " and t2.warehouse_code=@warehousecode" : "");
                sql += " join  dc_base_warehouse t3 on t2.warehouse_code =t3.warehouse_code and hq_type=@warehousetype";

                sqlparam.Add("warehousetype", warehousetype);
                if (!string.IsNullOrEmpty(warehousecode))
                {
                    sqlparam.Add("warehousecode", warehousecode);
                }
            }
            else if (!string.IsNullOrEmpty(warehousecode))
            {
                sql += " join  dc_base_oms_pick t2 on t1.origin_order_id=t2.origin_order_id and t2.warehouse_code=@warehousecode";
                sqlparam.Add("warehousecode", warehousecode);
            }


            if (!string.IsNullOrWhiteSpace(account))
            {
                sqlwhere += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sqlwhere += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                sqlwhere += " and t1.paid_time>='" + start.Value.ToString("yyyy-MM-dd") + "'";
            }

            if (end.HasValue)
            {
                sqlwhere += " and t1.paid_time<'" + end.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }

            var prefromsql = sqlwhere;

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<Models.Orders.dc_base_oms_order>(sql + sqlwhere, sqlparam);

                return obj;
            }
        }

        /// <summary>
        /// 按站点显示Ebay的统计记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="website"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public List<dc_base_oms_order> ListEbayStatisticsByWebsite(BtTableParameter request, string platform, string website, string account, DateTime? start, DateTime? end, string warehousetype, string warehousecode, int? companyid, ref int total, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var sql = @"select t1.platform_type,t1.website,sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_sales',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_other_exchange_rate) 'cost_platform_fee',sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) as cost_paypal_fee,sum(t1.cost_first) 'cost_first',count(t1.bailun_order_id) 'order_count',sum(t1.cost_total) 'cost_total',sum(t1.cost_logistics) 'cost_tail',sum(t1.profit_total) 'profit_total',(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,count(t1.amount_prepaid>0 or null) as noshippingcount  from dc_base_oms_order t1";

            if (!string.IsNullOrEmpty(warehousetype))
            {
                sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_type_ex=@warehoursetype";
                sqlparam.Add("warehoursetype", warehousetype);
            }
            if (!string.IsNullOrEmpty(warehousecode))
            {
                if (!string.IsNullOrEmpty(warehousetype))
                {
                    sql += " and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
                else
                {
                    sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ") ";
                    }
                }
            }



            var fromsql = " where t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed')  ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                fromsql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrEmpty(platform))
            {
                if (platform.ToUpper().Trim() != "FBA")
                {
                    fromsql += " and t1.bailun_order_status!='CantHandle' ";
                }

                fromsql += " and t1.platform_type=@platform";
                sqlparam.Add("platform", platform);
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                fromsql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                fromsql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                fromsql += " and t1.paid_time>='" + start.Value.ToString("yyyy-MM-dd") + "'";
            }

            if (end.HasValue)
            {
                fromsql += " and t1.paid_time<'" + end.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }

            var prefromsql = fromsql;
            fromsql += " group by t1.website,t1.platform_type";

            if (!string.IsNullOrWhiteSpace(request.sort))
            {
                fromsql += " order by " + request.sort + " " + request.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.dc_base_oms_order>(request.pageIndex, request.limit, sql + fromsql, ref total, sqlparam);

                return obj.AsList();
            }
        }

        /// <summary>
        /// 获取Ebay UK站点 平邮发货名字
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public List<Models.Ebay.ebayUKLogistics> ListEbayUKLogistics(DateTime start, DateTime end)
        {
            var sqlparam = new DynamicParameters();
            //var sql = $@"select t1.seller_account,t1.origin_order_id,t1.logistics_warehouse_code,t1.logistics_method_code from dc_base_oms_order t1
            //                        join dc_ebay_report_uk_config t2 on t2.type>1 and t1.logistics_method_code=t2.config_value
            //                        join dc_ebay_report_uk_config t3 on t3.type=1 and t1.seller_account=t3.config_value
            //                        where t1.platform_type='Ebay' and t1.website='uk' and t1.bailun_payment_status!='Canceled'
            //                        and t1.paid_time>='{start.ToString("yyyy-MM-dd")}' and t1.paid_time<'{end.AddDays(1).ToString("yyyy-MM-dd")}'";

            var sql = $@"select * from (select distinct t1.seller_account,t1.origin_order_id,t1.logistics_warehouse_code,t1.logistics_method_code,t2.logistics_order_id from dc_base_oms_order t1
                                    join dc_base_oms_pick t2 on t1.bailun_order_id=t2.bailun_order_id and t2.logistics_order_id is not null
                                    join dc_ebay_report_uk_config t3 on t3.type=1 and t1.seller_account=t3.config_value
                                    join dc_ebay_report_uk_config t4 on t2.logistics_order_id = t4.config_value
                                    where t1.platform_type='Ebay' and t1.website='uk' and t1.bailun_payment_status!='Canceled'
                                    and t1.paid_time>='{start.ToString("yyyy-MM-dd")}' and t1.paid_time<'{end.AddDays(1).ToString("yyyy-MM-dd")}') t1";


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var list = cn.Query<Models.Ebay.ebayUKLogistics>(sql, null, null, true, 2 * 60).AsList();

                return list;
            }

        }

        /// <summary>
        /// 获取Ebay UK站点 leter的发货占比
        /// Add by Allan at 20200711
        /// </summary>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <returns></returns>
        public List<Models.Ebay.ebayUKLogistics> ListEbayUKLogistics_Letter(DateTime start, DateTime end)
        {
            var sqlparam = new DynamicParameters();

            var sql = $@"select * from (
                        select distinct t1.seller_account,t1.origin_order_id,t1.logistics_warehouse_code,t1.logistics_method_code,t2.logistics_order_id 
                        from dc_base_oms_order t1 
                        join dc_base_oms_pick t2 on t1.bailun_order_id=t2.bailun_order_id and t2.logistics_order_id is not null 
                        join dc_ebay_report_uk_config t4 on t2.logistics_order_id = t4.config_value and t4.type in (4,5,6,7)
                        where t1.platform_type='Ebay' and t1.website='uk' and t1.bailun_payment_status!='Canceled' and t1.paid_time>='{start.ToString("yyyy-MM-dd")}' and t1.paid_time<'{end.AddDays(1).ToString("yyyy-MM-dd")}') t1";


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var list = cn.Query<Models.Ebay.ebayUKLogistics>(sql, null, null, true, 2 * 60).AsList();

                return list;
            }
        }

        /// <summary>
        /// 获取Ebay UK站点 配置信息
        /// </summary>
        /// <returns></returns>
        public List<Models.Ebay.dc_ebay_report_uk_config> ListEbayReportUKConfig()
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                return cn.Query<Models.Ebay.dc_ebay_report_uk_config>("select * from dc_ebay_report_uk_config where type>0").AsList();
            }
        }

        /// <summary>
        /// 获取Ebay订单的Itemid
        /// </summary>
        /// <param name="orderid">订单号列表</param>
        /// <returns></returns>
        public List<dc_base_oms_platform_sku> GetOrderItemId(List<string> orderid)
        {
            var sql = "select bailun_order_id,GROUP_CONCAT(item_id) as item_id from dc_base_oms_platform_sku where bailun_order_id in ('" + string.Join("','", orderid) + "') group by bailun_order_id;";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var list = new List<Tuple<string, string>>();
                var obj = cn.Query<dc_base_oms_platform_sku>(sql);

                return obj.ToList();
            }
        }

        /// <summary>
        /// 获取Ebay的费用明细
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="feetype"></param>
        /// <returns></returns>
        public List<dc_base_finance_ebay> ListEbayFee(int page, int pagesize, DateTime start, DateTime end, string[] feetype)
        {
            var sqlparam = new DynamicParameters();
            var sql = $"select id,account_entry_type,description,bj_date,gross_amount,item_id,account_id,currency,exchange_rate,company_id from dc_base_finance_ebay where bj_date>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and bj_date<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' and account_entry_type in ('{string.Join("','", feetype)}') ";
            var sqllimit = " limit " + (page - 1) * pagesize + "," + pagesize;

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var list = cn.Query<dc_base_finance_ebay>(sql + sqllimit, null, null, true, 2 * 60);

                return list.AsList();
            }

        }

        /// <summary>
        /// 获取Ebay的费用
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="companyid"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="total"></param>
        /// <param name="feetype">费用类型</param>
        /// <returns></returns>
        public List<dc_base_finance_ebay> ListEbayFee(BtTableParameter parameter, int? companyid, DateTime? start, DateTime? end, ref int total, string[] feetype, string orderno, string account,string itemid)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t1.id,t1.account_entry_type,t1.description,t1.bj_date as gmt_date,t1.gross_amount,t1.item_id,t1.net_amount,t1.vat_percent,t1.order_line_id,t1.currency,t1.exchange_rate,(t1.exchange_rate*t1.gross_amount) gross_amount_rmb,t2.account_name from dc_base_finance_ebay t1 ";
            sql += " left join dc_base_company_account t2 on t1.company_id=t2.company_id and t1.account_id=t2.account_id ";
            sql += " where 1=1 ";

            if (start.HasValue)
            {
                sql += " and t1.bj_date>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.bj_date<@end";
                sqlparam.Add("end", end.Value);
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=@companyid";
                sqlparam.Add("companyid", companyid.Value);
            }

            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and t1.order_line_id=@orderno";
                sqlparam.Add("orderno", orderno);
            }

            if (feetype != null && feetype.Length > 0)
            {
                sql += " and t1.account_entry_type in ('" + string.Join("','", feetype) + "')";
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " and t2.account_name=@account_name";
                sqlparam.Add("account_name", account);
            }

            if (!string.IsNullOrWhiteSpace(itemid))
            {
                sql += " and t1.item_id=@item_id";
                sqlparam.Add("item_id", itemid);
            }

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                sql += " order by t1." + parameter.sort + " " + parameter.order;
            }
            else
            {
                sql += " order by t1.gmt_date desc";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                try
                {
                    if (parameter.pageIndex > 0 && parameter.limit > 0)
                    {
                        var obj = cn.Page<dc_base_finance_ebay>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam);

                        return obj.ToList();
                    }
                    else
                    {
                        var obj = cn.Query<dc_base_finance_ebay>(sql, sqlparam, null, true, 2 * 60).ToList();
                        return obj;
                    }
                    
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

        }

        /// <summary>
        /// 获取Ebay的费用统计
        /// </summary>
        /// <param name="companyid"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="total"></param>
        /// <param name="feetype"></param>
        /// <returns></returns>
        public dc_base_finance_ebay EbayFeeCount(int? companyid, DateTime? start, DateTime? end, string[] feetype, string orderno, string account,bool isUSD,string itemid, int[] producttype, int? skusource, int? shippingstrategy,string platform, string website)
        {
            if (platform != null && platform.ToLower() != "ebay")
            {
                return new dc_base_finance_ebay();
            }

            var sqlparam = new DynamicParameters();
            var sql = $"select sum(t1.gross_amount) gross_amount,sum(t1.net_amount) net_amount,sum(t1.{(isUSD? "exchange_rate_usd" : "exchange_rate")}*t1.gross_amount) gross_amount_rmb from dc_base_finance_ebay t1 ";

            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " join dc_base_company_account t2 on t1.company_id=t2.company_id and t1.account_id=t2.account_id ";
                sql += " and t2.account_name=@account_name ";
                sqlparam.Add("account_name", account);
            }

            //Add by Allan at 20200320
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue)
            {
                sql = $"select 0 gross_amount,0 net_amount,sum(t1.{(isUSD ? "exchange_rate_usd" : "exchange_rate")}*t1.sku_amount*t1.sku_count) gross_amount_rmb from dc_base_finance_ebay_item t1 ";

                sqlparam = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(account))
                {
                    sql += " join dc_base_company_account t2 on t1.company_id=t2.company_id and t1.account_id=t2.account_id ";
                    sql += " and t2.account_name=@account_name ";
                    sqlparam.Add("account_name", account);
                }


                sql += " join dc_base_sku t10 on t1.bailun_sku=t10.bailun_sku ";

                if (producttype.Count() > 0)
                {
                    sql += " and t10.product_type in (" + string.Join(",", producttype) + ") ";
                }

                if (skusource.HasValue)
                {
                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3美国仓
                {

                }
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " join dc_base_company_account t20 on t20.account_id = t1.account_id and t20.company_id=1 and t20.status=1 and t20.site_en='"+website+"'";
            }

            sql += " where t1.id!=0 ";

            if (start.HasValue)
            {
                sql += " and t1.bj_date>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.bj_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=@companyid";
                sqlparam.Add("companyid", companyid.Value);
            }

            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and t1.order_line_id=@orderno";
                sqlparam.Add("orderno", orderno);
            }

            if (!string.IsNullOrWhiteSpace(itemid))
            {
                sql += " and t1.item_id=@item_id";
                sqlparam.Add("item_id", itemid);
            }

            if (feetype != null && feetype.Length > 0)
            {
                sql += " and t1.account_entry_type in ('" + string.Join("','", feetype) + "')";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_finance_ebay>(sql, sqlparam);

                return obj;
            }
        }

        /// <summary>
        /// 获取Ebay的费用统计
        /// </summary>
        /// <param name="companyid"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="total"></param>
        /// <param name="feetype"></param>
        /// <returns></returns>
        public List<dc_base_finance_ebay> EbayFeeCount(int? companyid, DateTime? start, DateTime? end, string[] feetype, string orderno, string account, bool isUSD, string itemid, int[] producttype, int? skusource, int? shippingstrategy, int statistictype,string platform,string website)
        {
            if (platform != null && platform.ToLower() != "ebay")
            {
                return new List<dc_base_finance_ebay>();
            }

            var sqlparam = new DynamicParameters();
            var sql = $"select sum(t1.gross_amount) gross_amount,sum(t1.net_amount) net_amount,sum(t1.{(isUSD ? "exchange_rate_usd" : "exchange_rate")}*t1.gross_amount) gross_amount_rmb from dc_base_finance_ebay t1 ";

            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " join dc_base_company_account t2 on t1.company_id=t2.company_id and t1.account_id=t2.account_id ";
                sql += " and t2.account_name=@account_name ";
                sqlparam.Add("account_name", account);
            }

            //Add by Allan at 20200320
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue || statistictype!=0)
            {
                var s = "";
                if (statistictype == 1) //sku产品类型
                {
                    s = " t10.bailun_category_id as platform,";
                }
                else if (statistictype == 2)  //sku来源
                {
                    s = " t10.source as platform,";
                }

                sql = $"select {s}0 gross_amount,0 net_amount,sum(t1.{(isUSD ? "exchange_rate_usd" : "exchange_rate")}*t2.sku_ratio*t1.gross_amount) gross_amount_rmb from dc_base_finance_ebay t1 ";

                sqlparam = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(account))
                {
                    sql += " join dc_base_company_account t2 on t1.company_id=t2.company_id and t1.account_id=t2.account_id ";
                    sql += " and t2.account_name=@account_name ";
                    sqlparam.Add("account_name", account);
                }


                sql += @" 
                        join dc_base_ebay_sku_ratio t2 on t1.item_id=t2.item_id
                        join dc_base_sku t10 on t2.sku_code=t10.bailun_sku ";

                if (producttype.Count() > 0)
                {
                    sql += " and t10.bailun_category_id in (" + string.Join(",", producttype) + ") ";
                }

                if (skusource.HasValue)
                {
                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3美国仓
                {

                }
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " join dc_base_company_account t20 on t20.account_id = t1.account_id and t20.company_id=1 and t20.status=1 and t20.site_en='" + website + "'";
            }

            sql += " where t1.id!=0 ";

            if (start.HasValue)
            {
                sql += " and t1.bj_date>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.bj_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=@companyid";
                sqlparam.Add("companyid", companyid.Value);
            }

            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and t1.order_line_id=@orderno";
                sqlparam.Add("orderno", orderno);
            }

            if (!string.IsNullOrWhiteSpace(itemid))
            {
                sql += " and t1.item_id=@item_id";
                sqlparam.Add("item_id", itemid);
            }

            if (feetype != null && feetype.Length > 0)
            {
                sql += " and t1.account_entry_type in ('" + string.Join("','", feetype) + "')";
            }


            if (statistictype == 1)   //1：sku品类
            {
                sql += "group by t10.bailun_category_id";
            }
            else if (statistictype == 2)  //2：sku来源
            {
                sql += "group by t10.source";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_finance_ebay>(sql, sqlparam).ToList();

                return obj;
            }
        }


        /// <summary>
        /// 获取汇损费用列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<mExchangeLoss> ListExchangeLoss(BtTableParameter parameter, string account, DateTime? start, DateTime? end, ref int total, int? companyid)
        {
            //var sqlparam = new DynamicParameters();

            //var s1 = " ";
            //var s2 = " ";



            //if (!string.IsNullOrWhiteSpace(account))
            //{
            //    s1 += " and t1.seller_account=@seller_account ";
            //    sqlparam.Add("seller_account", account);

            //    s2 += " and t2.account_name=@account_name ";
            //    sqlparam.Add("account_name", account);
            //}

            //if (start.HasValue)
            //{
            //    s1 += " and t1.paid_time>=@t1_start";
            //    sqlparam.Add("t1_start", start.Value);

            //    s2 += " and t1.gmt_date>=@t2_start";
            //    sqlparam.Add("t2_start", start.Value);
            //}

            //if (end.HasValue)
            //{
            //    s1 += " and t1.paid_time<@t1_end";
            //    sqlparam.Add("t1_end", end.Value.AddDays(1));

            //    s2 += " and t1.gmt_date<@t2_end";
            //    sqlparam.Add("t2_end", end.Value.AddDays(1));
            //}

            //if (companyid.HasValue && companyid.Value > 0)
            //{
            //    s1 += " and t1.company_id=" + companyid.Value + " ";
            //    s2 += " and t1.company_id=" + companyid.Value + " ";
            //}

            //var sql = $@"select t01.seller_account,t01.amount_sales,t02.gross_amount from
            //            (select t1.seller_account,sum(t1.amount_sales*t1.seller_order_exchange_rate) as amount_sales from dc_base_oms_order t1
            //            where t1.bailun_payment_status!='Canceled' and t1.bailun_order_status!='CantHandle' and t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.platform_type='Ebay' 
            //            {s1}
            //            group by t1.seller_account) t01
            //            join (
            //            select t2.account_name,sum(t1.gross_amount*t1.exchange_rate) as gross_amount from dc_base_finance_ebay t1
            //            left join dc_base_company_account t2 on t1.account_id=t2.account_id
            //            where t1.account_entry_type!='Unknown' 
            //            {s2}
            //            group by t1.account_id) t02 on t01.seller_account=t02.account_name";

            //using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            //{
            //    if (cn.State == System.Data.ConnectionState.Closed)
            //    {
            //        cn.Open();
            //    }

            //    var obj = cn.Page<mExchangeLoss>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam);

            //    return obj.ToList();
            //}


            var sqlparam = new DynamicParameters();

            var sql = "select t1.seller_account,(t1.amount_sales*seller_order_exchange_rate) amount_sales  from dc_base_oms_order t1 where t1.bailun_order_status!='Canceled' and t1.platform_type='Ebay' and t1.bailun_order_status!='CantHandle' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";


            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " and t1.seller_account=@seller_account ";
                sqlparam.Add("seller_account", account);
            }

            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@t1_start";
                sqlparam.Add("t1_start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.paid_time<@t1_end";
                sqlparam.Add("t1_end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value + " ";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<mExchangeLoss>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam,"",2*60);
                return obj.ToList();
            }

        }


        public mExchangeLoss ListExchangeLossCount(string account, DateTime? start, DateTime? end, int? companyid)
        {
            var sqlparam = new DynamicParameters();

            var sql = "select sum(t1.amount_sales*t1.seller_order_exchange_rate) amount_sales from dc_base_oms_order t1 where t1.bailun_order_status!='Canceled' and t1.platform_type='Ebay' and t1.bailun_order_status!='CantHandle' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";


            if (!string.IsNullOrWhiteSpace(account))
            {
                sql += " and t1.seller_account=@seller_account ";
                sqlparam.Add("seller_account", account);
            }

            if (start.HasValue)
            {
                sql += " and t1.paid_time>=@t1_start";
                sqlparam.Add("t1_start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.paid_time<@t1_end";
                sqlparam.Add("t1_end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value + " ";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<mExchangeLoss>(sql,sqlparam);
                return obj;
            }
        }

        /// <summary>
        /// 检查ebay交易号是否已发货
        /// </summary>
        /// <param name="transactions">交易号集合</param>
        /// <returns></returns>
        public List<Models.Ebay.mPaypalIncomingShipStatus> CheckShipStatusByTranId(List<string> transactions)
        {
            //区分合并订单和不合并订单
            var sql = $@"select t2.order_currency as currency,t1.transaction_id,sum(t1.amount_sales*t1.bailun_sku_quantity_ordered) sales_amount_sku,sum(bailun_sku_quantity_ordered) count_sales,sum(t1.bailun_sku_quantity_shipped) count_shipping from dc_base_oms_sku t1 
                        join dc_base_oms_order t2 on t1.origin_order_id=t2.origin_order_id and t2.bailun_merge_status!='Merged'
                        where t1.transaction_id in ('{string.Join("','",transactions)}') and t1.has_delete=0 
                        group by t1.transaction_id
                        union all
                        select t2.order_currency as currency,t2.transaction_id,sum(t1.amount_sales*t1.bailun_sku_quantity_ordered) sales_amount_sku,sum(bailun_sku_quantity_ordered) count_sales,sum(t1.bailun_sku_quantity_shipped) count_shipping from dc_base_oms_sku t1 
                        join dc_base_oms_order t2 on t1.bailun_order_id=t2.aftermerged_bailun_order_no and t2.bailun_merge_status='Merged' and t2.transaction_id in ('{string.Join("','", transactions)}')
                        where t1.has_delete=0 
                        group by t2.transaction_id";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Ebay.mPaypalIncomingShipStatus>(sql, null, null, true, 2 * 60).Distinct().ToList();

                return obj;
            }



        }

        /// <summary>
        /// 获取Ebay Sku的销售数据
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="skus">sku数组</param>
        /// <param name="platform">平台类型</param>
        /// <param name="timetype">1:创建时间，2：付款时间</param>
        /// <returns></returns>
        public List<Models.Ebay.mEbaySkuSales> ListEbaySkuSalesCount(int page, int pagesize, DateTime start, DateTime end, string[] skus, string platform,int timetype=1)
        {
            var sql = $@"select t1.platform_type,t1.website,t1.bailun_sku,sum(t1.bailun_sku_quantity_ordered) as bailun_sku_quantity_ordered,sum(t1.bailun_sku_quantity_ordered*t1.amount_sales*t1.seller_order_exchange_rate) as amount_sales from dc_base_oms_sku t1 
                        where bailun_order_status!='Canceled' and has_scalp=0 and has_delete=0 and has_innersale=0 and has_innersale=0 ";

            if (timetype == 1)
            {
                sql += $" and t1.create_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.create_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' ";
            }
            else if (timetype == 2)
            {
                sql += $" and t1.paid_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.paid_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' ";
            }

            if (!string.IsNullOrEmpty(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    sql += $" and platform_type in ('{platform}','FBA')";
                }
                else
                {
                    sql += $" and platform_type = '{platform}'";
                }
                
            }

            if (skus.Length > 0)
            {
                sql += $" and bailun_sku in ('{string.Join("','",skus)}')";
            }

            sql += " group by t1.bailun_sku,t1.website,t1.platform_type";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Ebay.mEbaySkuSales>(sql+" limit "+(page-1)*pagesize+","+pagesize, null, null, true, 2 * 60).ToList();

                return obj;
            }


        }

        /// <summary>
        /// 获取Ebay Sku的销售数据
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="skus">sku数组</param>
        /// <param name="platform">平台类型</param>
        /// <returns></returns>
        public List<Models.Ebay.mEbaySkuSales> ListEbaySkuSalesCountByPlatformCreateTime(int page, int pagesize, DateTime start, DateTime end, string[] skus, string platform)
        {
            var sql = $@"select t1.platform_type,t1.website,t1.bailun_sku,sum(t1.bailun_sku_quantity_ordered) as bailun_sku_quantity_ordered,sum(t1.bailun_sku_quantity_ordered*t1.amount_sales*t1.seller_order_exchange_rate) as amount_sales from dc_base_oms_sku t1 
                        where t1.purchase_create_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.purchase_create_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_delete=0 and t1.has_innersale=0  ";

            if (!string.IsNullOrEmpty(platform))
            {
                if (platform.ToUpper() == "AMAZON")
                {
                    sql += $" and platform_type in ('{platform}','FBA')";
                }
                else
                {
                    sql += $" and platform_type = '{platform}'";
                }

            }

            if (skus.Length > 0)
            {
                sql += $" and bailun_sku in ('{string.Join("','", skus)}')";
            }

            sql += " group by t1.bailun_sku,t1.website,t1.platform_type";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Ebay.mEbaySkuSales>(sql + " limit " + (page - 1) * pagesize + "," + pagesize, null, null, true, 2 * 60).ToList();

                return obj;
            }


        }

        /// <summary>
        /// 根据订单更新的时间获取下单的日期
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public List<DateTime> ListSaleCountChangeDate(DateTime start,DateTime end)
        {
            var sql = $@"select distinct DATE_FORMAT(t1.purchase_create_time,'%Y-%m-%d') from dc_base_oms_sku as t1 where (t1.gmt_modified >= '{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.gmt_modified <='{end.ToString("yyyy-MM-dd HH:mm:ss")}') or (
(t1.has_delete = 1 or t1.has_scalp = 1) and t1.gmt_modified >= '{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.gmt_modified <='{end.ToString("yyyy-MM-dd HH:mm:ss")}')";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                return cn.Query<DateTime>(sql).ToList();

            }

        }

        /// <summary>
        /// 内部编码Sku的利润
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="skucode"></param>
        /// <param name="orderno"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<mInnerCodeProfit> ListEbayInnerCodeProfit(BtTableParameter parameter, DateTime start, DateTime end, string skucode, string orderno, ref int total)
        {
            var sqlparam = new DynamicParameters();

            var sqlwhere = $@"from dc_base_oms_sku t1 
                        join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku
                        where t1.company_id=1 and t1.bailun_order_status!='Canceled' and t1.paid_time>='{start.ToString("yyyy-MM-dd")}' and t1.paid_time<'{end.AddDays(1).ToString("yyyy-MM-dd")}' and t1.has_scalp=0 and t1.has_cancle=0 and t1.has_delete=0 and t1.has_innersale=0 and t1.platform_type='Ebay'
                        ";

            var sql = $@"select t2.product_inner_code,t1.origin_order_id,t1.platform_type,t1.website,t1.seller_account,t1.bailun_order_status,t1.pay_status,t1.shipping_status,sum(t1.amount_sales*seller_order_exchange_rate) amount_sales,sum(t1.cost_platform_fee*t1.seller_other_exchange_rate) cost_platform_fee,sum(t1.cost_product) cost_product,sum(t1.cost_first) cost_first,sum(t1.cost_logistics) cost_logistics,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,sum(t1.cost_total) cost_total,sum(t1.bailun_sku_quantity_ordered) bailun_sku_quantity_ordered,sum(t1.profit_total) profit_total,(sum(t1.profit_rate)/count(t1.id)) profit_rate,t1.create_time,t1.order_update_time,t1.transaction_id,t1.paid_time  
                        ";

            if (!string.IsNullOrEmpty(skucode))
            {
                sqlwhere += " and t2.product_inner_code='"+skucode+"'";
                //sqlparam.Add("skucode", skucode);
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sqlwhere += " and t1.origin_order_id='"+orderno+"'";
                
            }

            var strOrder = "";
            if (!string.IsNullOrEmpty(parameter.sort))
            {
                strOrder += " order by "+parameter.sort+" "+parameter.order;
            }

            sqlwhere += "group by t1.origin_order_id,t2.product_inner_code ";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<mInnerCodeProfit>(sql + sqlwhere+ strOrder + (" limit "+ (parameter.pageIndex-1)*parameter.limit+","+parameter.limit), sqlparam, null, true, 2 * 60);

                total = cn.QueryFirstOrDefault<int>("select count(*) from (select t2.product_inner_code,t1.origin_order_id,t1.platform_type,t1.website " + sqlwhere + ") tb",sqlparam);

                return obj.ToList();
            }
        }

        /// <summary>
        /// 内部编码Sku的利润汇总
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="skucode"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public mInnerCodeProfit ListEbayInnerCodeProfitCount(DateTime start, DateTime end, string skucode, string orderno)
        {
            var sqlparam = new DynamicParameters();

            var sqlwhere = $@"from dc_base_oms_sku t1 
                        join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku
                        where t1.company_id=1 and t1.bailun_order_status!='Canceled' and t1.paid_time>='{start.ToString("yyyy-MM-dd")}' and t1.paid_time<'{end.AddDays(1).ToString("yyyy-MM-dd")}' and t1.has_scalp=0 and t1.has_cancle=0 and t1.has_delete=0 and t1.has_innersale=0 and t1.platform_type='Ebay'
                        ";

            var sql = $@"select sum(t1.amount_sales*seller_order_exchange_rate) amount_sales,sum(t1.cost_platform_fee*t1.seller_other_exchange_rate) cost_platform_fee,sum(t1.cost_product) cost_product,sum(t1.cost_first) cost_first,sum(t1.cost_logistics) cost_logistics,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,sum(t1.cost_total) cost_total,sum(t1.bailun_sku_quantity_ordered) bailun_sku_quantity_ordered,sum(t1.profit_total) profit_total,(sum(t1.profit_rate)/count(t1.id)) profit_rate 
                        ";

            if (!string.IsNullOrEmpty(skucode))
            {
                sqlwhere += " and t2.product_inner_code='" + skucode + "'";
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sqlwhere += " and t1.origin_order_id='" + orderno + "'";
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<mInnerCodeProfit>(sql + sqlwhere ,sqlparam, null,2*60);
                
                return obj;
            }
        }

        /// <summary>
        /// 导出内部编码sku利润
        /// </summary>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="skucode">内部商品编码</param>
        /// <param name="orderno">平台订单号</param>
        /// <returns></returns>
        public List<mInnerCodeProfit> ExportEbayInnerCodeProfit(DateTime start, DateTime end, string skucode, string orderno)
        {
            var sqlparam = new DynamicParameters();

            var sqlwhere = $@"from dc_base_oms_sku t1 
                        join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku
                        where t1.company_id=1 and t1.bailun_order_status!='Canceled' and t1.paid_time>='{start.ToString("yyyy-MM-dd")}' and t1.paid_time<'{end.AddDays(1).ToString("yyyy-MM-dd")}' and t1.has_scalp=0 and t1.has_cancle=0 and t1.has_delete=0 and t1.has_innersale=0 and t1.platform_type='Ebay'
                        ";

            var sql = $@"select t2.product_inner_code,t1.origin_order_id,t1.platform_type,t1.website,t1.seller_account,t1.bailun_order_status,t1.pay_status,t1.shipping_status,sum(t1.amount_sales*seller_order_exchange_rate) amount_sales,sum(t1.cost_platform_fee*t1.seller_other_exchange_rate) cost_platform_fee,sum(t1.cost_product) cost_product,sum(t1.cost_first) cost_first,sum(t1.cost_logistics) cost_logistics,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) cost_paypal_fee,sum(t1.cost_total) cost_total,sum(t1.bailun_sku_quantity_ordered) bailun_sku_quantity_ordered,sum(t1.profit_total) profit_total,(sum(t1.profit_rate)/count(t1.id)) profit_rate,t1.create_time,t1.order_update_time,t1.transaction_id 
                        ";

            if (!string.IsNullOrEmpty(skucode))
            {
                sqlwhere += " and t2.product_inner_code='" + skucode + "'";
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sqlwhere += " and t1.origin_order_id='" + orderno + "'";

            }
            
            sqlwhere += "group by t1.origin_order_id,t2.product_inner_code ";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<mInnerCodeProfit>(sql + sqlwhere, sqlparam, null, true, 2 * 60);
                
                return obj.ToList();
            }
        }

        #endregion

        #region Platform Common

        /// <summary>
        /// 平台 销售统计记录
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="website">站点信息</param>
        /// <param name="account">帐号信息</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="warehousetype">发货仓库类型</param>
        /// <param name="warehousecode">发货仓库编码</param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_order> ListPlatformStatistics(BtTableParameter parameter, string platform,string website, string account, DateTime? start, DateTime? end, string warehousetype, string warehousecode, int? companyid, ref int total, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var sql = @"select t1.platform_type,t1.seller_account,t1.website,sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_sales',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_order_exchange_rate) 'cost_platform_fee',sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) as cost_paypal_fee,sum(t1.cost_first) 'cost_first',count(t1.bailun_order_id) 'order_count',sum(t1.cost_total) 'cost_total',sum(t1.cost_logistics) 'cost_tail',sum(t1.profit_total) 'profit_total',(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,count(t1.amount_prepaid>0 or null) as noshippingcount,sum(t1.cost_logistics) cost_logistics  from dc_base_oms_order t1";

            if (!string.IsNullOrEmpty(warehousetype))
            {
                sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_type_ex=@warehoursetype";
                sqlparam.Add("warehoursetype", warehousetype);
            }
            if (!string.IsNullOrEmpty(warehousecode))
            {
                if (!string.IsNullOrEmpty(warehousetype))
                {
                    sql += " and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
                else
                {
                    sql += " join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku  
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ") ";
                    }
                }
            }


            var fromsql = " where t1.bailun_order_status!='Canceled' and t1.bailun_order_status!='CantHandle' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (!string.IsNullOrWhiteSpace(platform))
            {
                fromsql += " and t1.platform_type = @platform";
                sqlparam.Add("platform", platform);
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                fromsql += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                fromsql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                fromsql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                fromsql += " and t1.paid_time>='" + start.Value.ToString("yyyy-MM-dd") + "'";
            }

            if (end.HasValue)
            {
                fromsql += " and t1.paid_time<'" + end.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }

            var prefromsql = fromsql;
            fromsql += " group by t1.seller_account,t1.website,t1.platform_type";

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                fromsql += " order by " + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<Models.Orders.dc_base_oms_order>(parameter.pageIndex, parameter.limit, sql + fromsql, ref total, sqlparam);

                return obj.AsList();
            }
        }


        /// <summary>
        /// 平台销售统计记录 统计
        /// </summary>
        /// <param name="website"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="warehousetype"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public Models.Orders.dc_base_oms_order ListPlatformStatisticsCount(string platform, string website, string account, DateTime? start, DateTime? end, string warehousetype, string warehousecode, int? companyid, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            var sql = @"select sum(t1.amount_sales*t1.seller_order_exchange_rate) 'amount_sales',sum(t1.cost_paypal_fee*t1.seller_order_exchange_rate) 'cost_paypal_fee',sum(t1.cost_product) 'cost_product',sum(t1.cost_platform_fee*t1.seller_other_exchange_rate) 'cost_platform_fee',sum(t1.cost_first) 'cost_first',count(t1.bailun_order_id) 'order_count',sum(t1.cost_total) 'cost_total',sum(t1.cost_logistics) 'cost_tail',sum(t1.profit_total) 'profit_total',(sum(t1.profit_total)/sum(t1.amount_sales*t1.seller_order_exchange_rate)) 'profit_rate',sum(t1.amount_prepaid) amount_prepaid,sum(t1.amount_refund*t1.seller_order_exchange_rate) amount_refund,sum(t1.cost_handle_bailun) cost_handle_bailun,sum(t1.cost_handle_platform) cost_handle_platform,count(t1.amount_prepaid>0 or null) as noshippingcount,sum(t1.cost_logistics) cost_logistics  from dc_base_oms_order t1";

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id 
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t4.category_simple_id in (" + s + ") ";

                    }
                }
            }

            var sqlwhere = " where t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sqlwhere += " and t1.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrEmpty(platform))
            {
                if (platform.ToUpper().Trim() != "FBA")
                {
                    sqlwhere += "  and t1.bailun_order_status!='CantHandle' ";
                }

                sqlwhere += " and t1.platform_type=@platform ";
                sqlparam.Add("platform", platform);
            }

            if (!string.IsNullOrEmpty(warehousetype) || (!string.IsNullOrEmpty(warehousetype) && !string.IsNullOrEmpty(warehousecode)))
            {
                sql += " join  dc_base_oms_pick t2 on t1.origin_order_id=t2.origin_order_id " + (!string.IsNullOrEmpty(warehousecode) ? " and t2.warehouse_code=@warehousecode" : "");
                sql += " join  dc_base_warehouse t3 on t2.warehouse_code =t3.warehouse_code and hq_type=@warehousetype";

                sqlparam.Add("warehousetype", warehousetype);
                if (!string.IsNullOrEmpty(warehousecode))
                {
                    sqlparam.Add("warehousecode", warehousecode);
                }
            }
            else if (!string.IsNullOrEmpty(warehousecode))
            {
                sql += " join  dc_base_oms_pick t2 on t1.origin_order_id=t2.origin_order_id and t2.warehouse_code=@warehousecode";
                sqlparam.Add("warehousecode", warehousecode);
            }


            if (!string.IsNullOrWhiteSpace(account))
            {
                sqlwhere += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sqlwhere += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                sqlwhere += " and t1.paid_time>='" + start.Value.ToString("yyyy-MM-dd") + "'";
            }

            if (end.HasValue)
            {
                sqlwhere += " and t1.paid_time<'" + end.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }

            var prefromsql = sqlwhere;

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<Models.Orders.dc_base_oms_order>(sql + sqlwhere, sqlparam);

                return obj;
            }
        }



        #endregion

        #region （作废）退款单

        /// <summary>
        /// CRM退款单明细
        /// </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>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_crm_refund> ListOrderRefund(BtTableParameter request, string platform, string website, string account, DateTime? start, DateTime? end, string searchkey, ref int total)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t1.*,if(t2.bailun_shipping_status is null,t3.bailun_shipping_status,t2.bailun_shipping_status) as bailun_shipping_status from dc_base_crm_refund t1 left join dc_base_oms_order t2 on t1.origin_order_id=t2.origin_order_id left join dc_base_oms_order t3 on t1.origin_order_id=t3.transaction_id where 1=1 ";

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t1.bailun_account=@bailun_account";
                sqlparam.Add("bailun_account", account);
            }
            if (start.HasValue)
            {
                sql += " and t1.refund_time>=@refund_time_start";
                sqlparam.Add("refund_time_start", start.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (end.HasValue)
            {
                sql += " and t1.refund_time<@refund_time_end";
                sqlparam.Add("refund_time_end", end.Value.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (!string.IsNullOrEmpty(searchkey))
            {
                sql += " and t1.origin_order_id=@key";
                sqlparam.Add("key", searchkey);
            }

            if (!string.IsNullOrEmpty(request.sort))
            {
                sql += " order by t1." + request.sort + " " + request.order;
            }
            else
            {
                sql += " order by t1.refund_time desc";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_crm_refund>(request.pageIndex, request.limit, sql, ref total, sqlparam);

                return obj.AsList();
            }

        }

        /// <summary>
        /// 退款明细统计
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public dc_base_crm_refund ListOrderRefundCount(string platform, string website, string account, DateTime? start, DateTime? end, string searchkey)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select sum(amount_refund) amount_refund,sum(bailun_sku_quantity_refund) bailun_sku_quantity_refund,sum(amount_refund_rmb) amount_refund_rmb from dc_base_crm_refund where 1=1 ";

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (!string.IsNullOrEmpty(website))
            {
                sql += " and website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and bailun_account=@bailun_account";
                sqlparam.Add("bailun_account", account);
            }
            if (start.HasValue)
            {
                sql += " and refund_time>=@refund_time_start";
                sqlparam.Add("refund_time_start", start.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (end.HasValue)
            {
                sql += " and refund_time<@refund_time_end";
                sqlparam.Add("refund_time_end", end.Value.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (!string.IsNullOrEmpty(searchkey))
            {
                sql += " and t1.origin_order_id=@key";
                sqlparam.Add("key", searchkey);
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_crm_refund>(sql, sqlparam);
                return obj;
            }
        }

        #endregion

        #region 预收款

        /// <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>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_oms_order> ListDepositReceived(BtTableParameter request, string platform, string website, string account, DateTime? start, DateTime? end, int? companyid, ref int total, ref dc_base_oms_order m)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select origin_order_id,bailun_order_id,platform_type,website,seller_account,paid_time,(amount_sales*seller_order_exchange_rate) amount_sales,(amount_shipping*seller_order_exchange_rate) amount_shipping,(amount_product*seller_order_exchange_rate) amount_product,(amount_tax*seller_order_exchange_rate) amount_tax,(amount_adjustment*seller_order_exchange_rate) amount_adjustment,(amount_gift_wrap*seller_order_exchange_rate) amount_gift_wrap,(amount_refund*seller_order_exchange_rate) amount_refund,amount_prepaid,(cost_promotion*seller_order_exchange_rate) cost_promotion,(cost_platform_fee*seller_order_exchange_rate) cost_platform_fee,cost_product,cost_shipping,cost_package,(cost_fba_fee*seller_order_exchange_rate) cost_fba_fee,(cost_paypal_fee*seller_order_exchange_rate) cost_paypal_fee,(cost_refund_commisson*seller_order_exchange_rate) cost_refund_commisson,cost_handle_bailun,cost_handle_platform,cost_logistics as cost_tail,cost_first,profit_total,profit_rate,(cost_total) cost_total  from dc_base_oms_order where bailun_order_status='Handling' and bailun_shipping_status!='TotalShipping' and amount_prepaid>0 and has_scalp=0 and has_innersale=0 and bailun_interception_status in ('None','Failed') ";
            var sqlcount = "select sum(amount_sales*seller_order_exchange_rate) amount_sales,sum(amount_shipping*seller_order_exchange_rate) amount_shipping,sum(amount_product*seller_order_exchange_rate) amount_product,sum(amount_tax*seller_order_exchange_rate) amount_tax,sum(amount_adjustment*seller_order_exchange_rate) amount_adjustment,sum(amount_gift_wrap*seller_order_exchange_rate) amount_gift_wrap,sum(amount_refund*seller_order_exchange_rate) amount_refund,sum(amount_prepaid) amount_prepaid,sum(cost_promotion*seller_order_exchange_rate) cost_promotion,sum(cost_platform_fee*seller_order_exchange_rate) cost_platform_fee,sum(cost_product) cost_product,sum(cost_shipping) cost_shipping,sum(cost_package) cost_package,sum(cost_fba_fee*seller_order_exchange_rate) cost_fba_fee,sum(cost_paypal_fee*seller_order_exchange_rate) cost_paypal_fee,sum(cost_refund_commisson*seller_order_exchange_rate) cost_refund_commisson,sum(cost_handle_bailun) cost_handle_bailun,sum(cost_handle_platform) cost_handle_platform,sum(cost_logistics) cost_tail,sum(cost_first) cost_first,sum(profit_total) profit_total,sum(cost_total) cost_total from dc_base_oms_order where bailun_order_status='Handling' and bailun_shipping_status!='TotalShipping' and has_scalp=0 and has_innersale=0 and amount_prepaid>0 and bailun_interception_status in ('None','Failed') ";

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and platform_type=@platform_type";
                sqlcount += " and platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (!string.IsNullOrEmpty(website))
            {
                sql += " and website=@website";
                sqlcount += " and website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(account))
            {
                sql += " and seller_account=@seller_account";
                sqlcount += " and seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }
            if (start.HasValue)
            {
                sql += " and paid_time>=@paid_time_start";
                sqlcount += " and paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value.ToString("yyyy-MM-dd"));
            }
            if (end.HasValue)
            {
                sql += " and paid_time<@paid_time_end";
                sqlcount += " and paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1).ToString("yyyy-MM-dd"));
            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;    //增加公司id过滤
                sqlcount += " and company_id=" + companyid.Value;
            }

            if (!string.IsNullOrEmpty(request.sort))
            {
                sql += " order by " + request.sort + " " + request.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_oms_order>(request.pageIndex, request.limit, sql, ref total, sqlparam);

                m = cn.QueryFirstOrDefault<dc_base_oms_order>(sqlcount, sqlparam);

                return obj.AsList();
            }

        }

        #endregion

        #region 发货单

        /// <summary>
        /// sku发货重量差异列表
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="start">发货开始时间</param>
        /// <param name="end">发货结束时间</param>
        /// <param name="min">差异开始值</param>
        /// <param name="max">差异结束值</param>
        /// <param name="sku">sku编码</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_mid_skudeliver_weighdiff> ListWeighDiff(BtTableParameter request, DateTime? start, DateTime? end, int? min, int? max, string sku, ref int total,string warehousetype,string warehousecode)
        {
            var sqlparam = new DynamicParameters();
            var sql = @"select t1.*,t3.warehouse_name from dc_mid_skudeliver_weighdiff t1 ";

            sql += " join dc_base_oms_pick t2 on t1.pick_order_id=t2.pick_order_id and t1.bailun_sku=t2.bailun_sku ";
            sql += " join dc_base_warehouse t3 on t2.warehouse_code=t3.warehouse_code ";
            
            if (!string.IsNullOrWhiteSpace(warehousetype))
            {
                sql += " and t3.hq_type=@warehousetype";
                sqlparam.Add("warehousetype", warehousetype);
            }

            if (!string.IsNullOrWhiteSpace(warehousecode))
            {
                sql += " and t3.warehouse_code=@warehousecode";
                sqlparam.Add("warehousecode", warehousecode);
            }
            
            sql += " where t1.id>0 ";

            if (start.HasValue)
            {
                sql += " and t1.day>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.day<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }
            if (min.HasValue)
            {
                sql += " and t1.diffweigh>=@min";
                sqlparam.Add("min", min.Value);
            }
            if (max.HasValue)
            {
                sql += " and t1.diffweigh<@max";
                sqlparam.Add("max", max.Value);
            }
            if (!string.IsNullOrEmpty(sku))
            {
                sql += " and t1.bailun_sku=@sku";
                sqlparam.Add("sku", sku.Trim());
            }

            if (!string.IsNullOrEmpty(request.sort))
            {
                sql += (" order by t1." + request.sort + " " + request.order);
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_mid_skudeliver_weighdiff>(request.pageIndex, request.limit, sql, ref total, sqlparam);

                return obj.AsList();
            }
        }

        /// <summary>
        /// sku发货重量差异列表
        /// </summary>
        /// <param name="start">发货开始时间</param>
        /// <param name="end">发货结束时间</param>
        /// <param name="min">差异开始值</param>
        /// <param name="max">差异结束值</param>
        /// <param name="sku">sku编码</param>
        /// <returns></returns>
        public List<dc_mid_skudeliver_weighdiff> ListWeighDiff(DateTime? start, DateTime? end, int? min, int? max, string sku, string warehousetype, string warehousecode)
        {
            var sqlparam = new DynamicParameters();
            var sql = @"select t1.*,t3.warehouse_name from dc_mid_skudeliver_weighdiff t1 ";

            sql += " join dc_base_oms_pick t2 on t1.pick_order_id=t2.pick_order_id and t1.bailun_sku=t2.bailun_sku ";
            sql += " join dc_base_warehouse t3 on t2.warehouse_code=t3.warehouse_code ";

            if (!string.IsNullOrWhiteSpace(warehousetype))
            {
                sql += " and t3.hq_type=@warehousetype";
                sqlparam.Add("warehousetype", warehousetype);
            }

            if (!string.IsNullOrWhiteSpace(warehousecode))
            {
                sql += " and t3.warehouse_code=@warehousecode";
                sqlparam.Add("warehousecode", warehousecode);
            }

            sql += " where t1.id>0 ";

            if (start.HasValue)
            {
                sql += " and day>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and day<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }
            if (min.HasValue)
            {
                sql += " and diffweigh>=@min";
                sqlparam.Add("min", min.Value);
            }
            if (max.HasValue)
            {
                sql += " and diffweigh<@max";
                sqlparam.Add("max", max.Value);
            }
            if (!string.IsNullOrEmpty(sku))
            {
                sql += " and bailun_sku=@sku";
                sqlparam.Add("sku", sku.Trim());
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_mid_skudeliver_weighdiff>(sql, sqlparam, null, true, 2 * 60);

                return obj.AsList();
            }
        }

        /// <summary>
        /// 保存sku发货重量差异
        /// </summary>
        /// <param name="day">统计日期</param>
        /// <returns></returns>
        public string SaveWeighDiff(DateTime? day)
        {
            try
            {
                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
                {
                    if (cn.State == System.Data.ConnectionState.Closed)
                    {
                        cn.Open();
                    }

                    if (!day.HasValue)
                    {
                        day = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
                    }

                    var sql = $@"select t1.pick_order_id,t1.bailun_sku,t2.weight,t1.bailun_sku_outbound_weight,(t2.weight-t1.bailun_sku_outbound_weight) as diffweigh from dc_base_oms_pick t1
                                    join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku and t2.has_delete=0
                                    where t1.shipping_status = 'TotalShipping' and t1.has_delete=0 and t1.shipping_time>='{day.Value.ToString("yyyy-MM-dd")}' and t1.shipping_time<'{day.Value.AddDays(1).ToString("yyyy-MM-dd")}'";

                    var list = cn.Query<dc_mid_skudeliver_weighdiff>(sql);

                    var sql_insert = "insert dc_mid_skudeliver_weighdiff(day,pick_order_id,bailun_sku,weight,bailun_sku_outbound_weight,diffweigh,createtime) values ";
                    var str = "";
                    var index = 1;
                    foreach (var item in list)
                    {
                        str += $"('{day.Value.ToString("yyyy-MM-dd")}','{item.pick_order_id}','{item.bailun_sku}',{item.weight},{item.bailun_sku_outbound_weight},{item.diffweigh},'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'),";
                        index++;

                        if (index % 2000 == 0 || index == list.Count())
                        {
                            cn.Execute(sql_insert + str.Substring(0, str.Length - 1));
                            str = "";
                        }
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 获取发货sku的利润数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_oms_sku> ListOrderSkuProfit(int page, int pagesize, DateTime start, DateTime end,string orderno)
        {
            var sqlparam = new DynamicParameters();

            var str = "";
            if (!string.IsNullOrEmpty(orderno))
            {
                str += $" and t2.bailun_order_id='{orderno}'";
            }

            var sql = $@"select t1.id,t2.warehouse_code,(t1.amount_general_cargo*t2.quantity_shipped) as productvalue, t1.platform_type,t1.seller_account,t1.bailun_account_id,t1.website,t1.bailun_order_id,t1.origin_order_id,t1.transaction_id,t1.paid_time,t1.gmt_modified,t1.bailun_sku,(t1.amount_sales*t1.seller_order_exchange_rate*t2.quantity_shipped) amount_sales,(t1.profit_total*t2.quantity_shipped) profit_total,t2.quantity_shipped as platform_sku_quantity_shipped,t1.company_id,t2.pick_order_id,t2.shipping_time,if((t2.has_delete=1 or t1.has_delete=1),1,0) has_delete from 
                        (select t2.bailun_order_id,t2.bailun_sku,t2.quantity_shipped,t2.warehouse_code,t2.shipping_time,t2.has_delete,t2.pick_order_id from dc_base_oms_pick t2 where t2.gmt_modified>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t2.gmt_modified<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' and t2.shipping_status='TotalShipping' and t2.company_id=1 {str} {" limit " + (page - 1) * pagesize + "," + pagesize}) t2
                        left join dc_base_oms_sku t1 on t1.bailun_order_id=t2.bailun_order_id and t1.bailun_sku=t2.bailun_sku";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_oms_sku>(sql,sqlparam,null,true,2 * 60);

                return obj.ToList();
            }
        }

        /// <summary>
        /// 获取FBA的Sku利润
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="orderno">百伦单号</param>
        /// <returns></returns>
        public List<dc_base_oms_sku> ListFBASkuProfit(int page, int pagesize, DateTime start, DateTime end, string orderno)
        {
            var sqlparam = new DynamicParameters();

            var sql = $@"select t1.id,t1.warehouse_code,t1.platform_type,t1.seller_account,t1.bailun_account_id,t1.website,t1.transaction_id,t1.company_id,t1.paid_time,t1.gmt_modified,t1.bailun_sku,t1.origin_order_id,t1.bailun_order_id,((((t1.amount_product-t1.cost_platform_fee)*t1.seller_order_exchange_rate)-t1.cost_logistics-t1.cost_handle_bailun)*t1.bailun_sku_quantity_ordered) as productvalue,(t1.amount_sales*t1.seller_order_exchange_rate*t1.bailun_sku_quantity_ordered) amount_sales,(t1.profit_total*t1.bailun_sku_quantity_ordered) profit_total,t1.bailun_sku_quantity_ordered as platform_sku_quantity_shipped,if((t1.has_delete=1 or t1.bailun_order_status='Canceled'),1,0) has_delete,t1.create_time from dc_base_oms_sku t1 
                        where t1.platform_type = 'FBA' and t1.gmt_modified >= '{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.gmt_modified < '{end.ToString("yyyy-MM-dd HH:mm:ss")}'";

            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and t1.bailun_order_id=@orderno";
                sqlparam.Add("orderno",orderno);
            }

            sql += $"{" limit " + (page - 1) * pagesize + "," + pagesize}";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_oms_sku>(sql, sqlparam, null, true, 2 * 60).AsList();
                return obj;
            }

        }


        #endregion

        #region 平台SKu

        /// <summary>
        /// 获取平台sku销量明细
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_base_oms_platform_sku> ListOrderPlatformSku(int page, int pagesize, DateTime? start, DateTime? end, string platform, int? companyid, ref int total)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select origin_order_id,platform_type,website,order_currency,seller_order_exchange_rate,platform_sku_quantity_ordered,platform_sku_unit_price,item_id,platform_sku from dc_base_oms_platform_sku where has_delete=0 and has_scalp=0 and bailun_order_status!='Canceled' ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (start.HasValue)
            {
                sql += " and paid_time>='" + start.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'";
            }
            if (end.HasValue)
            {
                sql += " and paid_time<'" + end.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'";
            }
            if (!string.IsNullOrEmpty(platform))
            {
                sql += $" and platform_type=@platform";
                sqlparam.Add("platform", platform);
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_oms_platform_sku>(page, pagesize, sql, ref total, sqlparam);

                return obj.AsList();
            }
        }


        /// <summary>
        /// 获取平台sku销量明细
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_base_oms_platform_sku> ListPlatformSkuCount(int page, int pagesize, DateTime? start, DateTime? end, string platform, int? companyid)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select platform_type,website,sum(platform_sku_quantity_ordered) platform_sku_quantity_ordered,item_id,platform_sku from dc_base_oms_platform_sku where has_delete=0 and has_scalp=0 and bailun_order_status!='Canceled' ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (start.HasValue)
            {
                sql += " and paid_time>='" + start.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'";
            }
            if (end.HasValue)
            {
                sql += " and paid_time<'" + end.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'";
            }
            if (!string.IsNullOrEmpty(platform))
            {
                sql += $" and platform_type=@platform";
                sqlparam.Add("platform", platform);
            }

            sql += " group by platform_type,website,platform_sku limit "+(page-1)*pagesize+","+pagesize;

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_oms_platform_sku>(sql,sqlparam);

                return obj.AsList();
            }
        }

        /// <summary>
        /// 获取itemid的销量
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="itemid"></param>
        /// <returns></returns>
        public List<mItemIdOrderCount> GetItemIdOrderCount(string platform, DateTime start, DateTime end, string[] itemid)
        {
            if (itemid.Length > 1000)
            {
                return new List<mItemIdOrderCount>();
            }

            var commonCondition = $" ##.bailun_order_status!='Canceled' and ((##.platform_type!='FBA' and ##.bailun_order_status!='CantHandle') or ##.platform_type='FBA') and ##.has_scalp=0 and ##.paid_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and ##.paid_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}'  and ##.platform_type=@platform ";

            var sql = $@"select Count(t1.bailun_order_id) as count,platform_sku as itemid from dc_base_oms_platform_sku t1 
                        join dc_base_oms_order t2 on t1.bailun_order_id=t2.bailun_order_id and t2.has_innersale=0 and {commonCondition.Replace("##", "t2")}
                        where {commonCondition.Replace("##", "t1")} and platform_sku in ('{string.Join("','", itemid)}')
                        ";

            var sqlparam = new DynamicParameters();
            sqlparam.Add("platform", platform);

            sql += " group by platform_sku";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<mItemIdOrderCount>(sql, sqlparam);

                return obj.AsList();
            }
        }

        #endregion

        #region 人员相关统计

        /// <summary>
        /// 销售账户利润
        /// </summary>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <returns></returns>
        public List<mSalerProfit> ListSalerProfit(DateTime? start, DateTime? end, int? companyid)
        {
            var sql = "select seller_id,seller_account,sum(profit_total) profit_total from dc_base_oms_order where has_scalp=0 and has_innersale=0 and bailun_order_status!='Canceled'";
            var sqlparam = new DynamicParameters();

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;    //增加公司id过滤
            }


            if (start.HasValue)
            {
                sql += " and paid_time>=@start";
                sqlparam.Add("start", start.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else if (end.HasValue)
            {
                sql += " and paid_time<@end";
                sqlparam.Add("end", end.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            sql += " group by seller_id";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<mSalerProfit>(sql, sqlparam).ToList();

                return obj;
            }

        }

        #endregion

        #region 退款

        /// <summary>
        /// 退款记录
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">退款开始时间</param>
        /// <param name="end">退款结束时间</param>
        /// <param name="companyid">公司id</param>
        /// <param name="platform">平台类型</param>
        /// <param name="website">站点</param>
        /// <param name="orderno">平台订单号</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_base_crm_refund> ListOrderReturn(BtTableParameter parameter, DateTime? start, DateTime? end, DateTime? paytimestart, DateTime? paytimeend, int? companyid, string platform, string website, string orderno,int? shippingstatus, ref int total)
        {
            var sqlparam = new DynamicParameters();

            #region 订单表版本

            //var sqlselect = "select t1.platform_type,t1.website,t1.origin_order_id,t1.seller_account,t1.amount_refund,(t1.seller_order_exchange_rate*t1.amount_refund) as refundrmb,t1.refund_time,t1.refund_reference_id from dc_base_oms_order t1 ";
            //var sql = " where t1.amount_refund>0 ";

            //if (companyid.HasValue && companyid.Value > 0)
            //{
            //    sql += " and t1.company_id=@companyid";
            //    sqlparam.Add("companyid", companyid.Value);
            //}

            //if (start.HasValue)
            //{
            //    sql += " and t1.refund_time>=@start";
            //    sqlparam.Add("start", start.Value);
            //}
            //if (end.HasValue)
            //{
            //    sql += " and t1.refund_time<@end";
            //    sqlparam.Add("end", end.Value.AddDays(1));
            //}
            //if (!string.IsNullOrWhiteSpace(platform))
            //{
            //    sql += " and t1.platform_type=@platform";
            //    sqlparam.Add("platform", platform);
            //}
            //if (!string.IsNullOrWhiteSpace(website))
            //{
            //    sql += " and t1.website=@website";
            //    sqlparam.Add("website", website);
            //}
            //if (!string.IsNullOrWhiteSpace(orderno))
            //{
            //    sql += " and t1.origin_order_id=@orderno";
            //    sqlparam.Add("orderno", orderno);
            //}
            //if (paytimestart.HasValue)
            //{
            //    sql += " and t1.paid_time>=@paytimestart";
            //    sqlparam.Add("paytimestart", paytimestart.Value);
            //}
            //if (paytimeend.HasValue)
            //{
            //    sql += " and t1.paid_time<@paytimeend";
            //    sqlparam.Add("paytimeend", paytimeend.Value.AddDays(1));
            //}

            //var sqlcount = "select count(id) from dc_base_oms_order t1 " + sql;

            //if (!string.IsNullOrWhiteSpace(parameter.sort))
            //{
            //    sql += " order by t1." + parameter.sort + " " + parameter.order;
            //}
            //else {
            //    sql += " order by t1.refund_time desc ";
            //}

            //using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            //{
            //    if (cn.State == System.Data.ConnectionState.Closed)
            //    {
            //        cn.Open();
            //    }

            //    var obj = cn.Page<dc_base_oms_order>(parameter.pageIndex, parameter.limit, sqlselect + sql, ref total, sqlparam, sqlcount, 2 * 60);

            //    return obj.AsList();
            //}

            #endregion

            var sql = "select t1.platform_type,t1.bailun_account,t1.website,t1.origin_order_id,t1.amount_refund_rmb,t1.amount_refund_usd,t1.refund_time from dc_base_crm_refund t1 ";

            if (paytimestart.HasValue || paytimeend.HasValue)
            {
                sql += " join (select origin_order_id from dc_base_oms_order where company_id=1 ";

                if (paytimestart.HasValue)
                {
                    sql += " and paid_time>=@paytimestart";
                    sqlparam.Add("paytimestart", paytimestart.Value);
                }
                if (paytimeend.HasValue)
                {
                    sql += " and paid_time<@paytimeend";
                    sqlparam.Add("paytimeend",paytimeend.Value.AddDays(1));
                }

                sql += ") t2 on t1.origin_order_id=t2.origin_order_id";
            }

            sql += " where t1.is_deleted=0 and t1.is_freeze=0 and t1.company_id=" + companyid.Value;

            if (start.HasValue)
            {
                sql += " and t1.refund_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.refund_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value != 0)
            {
                //sql += " and t1.company_id="+companyid.Value;
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and t1.origin_order_id=@orderno";
                sqlparam.Add("orderno", orderno);
            }

            if (shippingstatus.HasValue)
            {
                if (shippingstatus.Value == 1)
                {
                    sql += " and t1.shipping_status in ('TotalShipping','PartShipping')";
                }
                else
                {
                    sql += " and t1.shipping_status in ('UnShipping','') ";
                }
            }


            if (!string.IsNullOrEmpty(parameter.sort))
            {
                sql += " order by t1." + parameter.sort + " " + parameter.order;
            }
            else
            {
                sql += " order by t1.refund_time desc";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_crm_refund>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam, "", 2 * 60);

                return obj.AsList();
            }
        }


        /// <summary>
        /// 退款记录列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">退款开始时间</param>
        /// <param name="end">退款结束时间</param>
        /// <param name="companyid">公司id</param>
        /// <param name="platform">平台类型</param>
        /// <param name="website">站点</param>
        /// <param name="orderno">平台订单号</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_base_crm_refund> ListOrderReturn(DateTime? start, DateTime? end, DateTime? paytimestart, DateTime? paytimeend, int? companyid, string platform, string website, string orderno, int? shippingstatus)
        {
            var sqlparam = new DynamicParameters();

            #region 订单表版本
            //var sql = "select t1.platform_type,t1.website,t1.origin_order_id,t1.seller_account,t1.amount_refund,(t1.seller_order_exchange_rate*t1.amount_refund) as refundrmb,t1.refund_time,t1.refund_reference_id from dc_base_oms_order t1 ";
            //sql += " where t1.amount_refund>0 ";


            //if (companyid.HasValue && companyid.Value > 0)
            //{
            //    sql += " and t1.company_id=@companyid";
            //    sqlparam.Add("companyid", companyid.Value);
            //}

            //if (start.HasValue)
            //{
            //    sql += " and t1.refund_time>=@start";
            //    sqlparam.Add("start", start.Value);
            //}
            //if (end.HasValue)
            //{
            //    sql += " and t1.refund_time<@end";
            //    sqlparam.Add("end", end.Value.AddDays(1));
            //}
            //if (!string.IsNullOrWhiteSpace(platform))
            //{
            //    sql += " and t1.platform_type=@platform";
            //    sqlparam.Add("platform", platform);
            //}
            //if (!string.IsNullOrWhiteSpace(website))
            //{
            //    sql += " and t1.website=@website";
            //    sqlparam.Add("website", website);
            //}
            //if (!string.IsNullOrWhiteSpace(orderno))
            //{
            //    sql += " and t1.origin_order_id=@orderno";
            //    sqlparam.Add("orderno", orderno);
            //}
            //if (paytimestart.HasValue)
            //{
            //    sql += " and t1.paid_time>=@paytimestart";
            //    sqlparam.Add("paytimestart", paytimestart.Value);
            //}
            //if (paytimeend.HasValue)
            //{
            //    sql += " and t1.paid_time<@paytimeend";
            //    sqlparam.Add("paytimeend", paytimeend.Value.AddDays(1));
            //}

            //using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            //{
            //    if (cn.State == System.Data.ConnectionState.Closed)
            //    {
            //        cn.Open();
            //    }

            //    var obj = cn.Query<dc_base_oms_order>(sql, sqlparam, null, true, 3 * 60);

            //    return obj.AsList();
            //}
            #endregion

            var sql = "select t1.platform_type,t1.bailun_account,t1.website,t1.origin_order_id,t1.amount_refund_rmb,t1.amount_refund_usd,t1.refund_time from dc_base_crm_refund t1 ";

            if (paytimestart.HasValue || paytimeend.HasValue)
            {
                sql += " join (select origin_order_id from dc_base_oms_order where company_id=1 ";

                if (paytimestart.HasValue)
                {
                    sql += " and paid_time>=@paytimestart";
                    sqlparam.Add("paytimestart", paytimestart.Value);
                }
                if (paytimeend.HasValue)
                {
                    sql += " and paid_time<@paytimeend";
                    sqlparam.Add("paytimeend", paytimeend.Value.AddDays(1));
                }

                sql += ") t2 on t1.origin_order_id=t2.origin_order_id";
            }

            sql += " where t1.is_deleted=0 and t1.is_freeze=0 and t1.company_id=" + companyid.Value;

            if (start.HasValue)
            {
                sql += " and t1.refund_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.refund_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value != 0)
            {
                //sql += " and t1.company_id="+companyid.Value;
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and t1.origin_order_id=@orderno";
                sqlparam.Add("orderno", orderno);
            }

            if (shippingstatus.HasValue)
            {
                if (shippingstatus.Value == 1)
                {
                    sql += " and t1.shipping_status in ('TotalShipping','PartShipping')";
                }
                else
                {
                    sql += " and t1.shipping_status in ('UnShipping','') ";
                }
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_crm_refund>(sql,sqlparam,null,true,2*60);

                return obj.AsList();
            }
            
        }


        /// <summary>
        /// 退款记录汇总
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public dc_base_crm_refund ListOrderReturnCount(DateTime? start, DateTime? end, DateTime? paytimestart, DateTime? paytimeend, int? companyid, string platform, string website, string orderno, int? shippingstatus)
        {
            var sqlparam = new DynamicParameters();

            #region 订单表版本

            //var sql = "select sum(t1.amount_refund) as amount_refund,sum(t1.seller_order_exchange_rate*t1.amount_refund) as refundrmb from dc_base_oms_order t1 ";
            //sql += " where t1.amount_refund>0 ";

            //if (companyid.HasValue && companyid.Value > 0)
            //{
            //    sql += " and t1.company_id=@companyid";
            //    sqlparam.Add("companyid", companyid.Value);
            //}

            //if (start.HasValue)
            //{
            //    sql += " and t1.refund_time>=@start";
            //    sqlparam.Add("start", start.Value);
            //}
            //if (end.HasValue)
            //{
            //    sql += " and t1.refund_time<@end";
            //    sqlparam.Add("end", end.Value.AddDays(1));
            //}
            //if (!string.IsNullOrWhiteSpace(platform))
            //{
            //    sql += " and t1.platform_type=@platform";
            //    sqlparam.Add("platform", platform);
            //}
            //if (!string.IsNullOrWhiteSpace(website))
            //{
            //    sql += " and t1.website=@website";
            //    sqlparam.Add("website", website);
            //}
            //if (!string.IsNullOrWhiteSpace(orderno))
            //{
            //    sql += " and t1.origin_order_id=@orderno";
            //    sqlparam.Add("orderno", orderno);
            //}
            //if (paytimestart.HasValue)
            //{
            //    sql += " and t1.paid_time>=@paytimestart";
            //    sqlparam.Add("paytimestart", paytimestart.Value);
            //}
            //if (paytimeend.HasValue)
            //{
            //    sql += " and t1.paid_time<@paytimeend";
            //    sqlparam.Add("paytimeend", paytimeend.Value.AddDays(1));
            //}

            //using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            //{
            //    if (cn.State == System.Data.ConnectionState.Closed)
            //    {
            //        cn.Open();
            //    }

            //    var obj = cn.QueryFirstOrDefault<dc_base_oms_order>(sql, sqlparam);

            //    return obj;
            //}
            #endregion

            var sql = "select sum(t1.amount_refund_rmb) amount_refund_rmb,sum(t1.amount_refund_usd) amount_refund_usd from dc_base_crm_refund t1 ";

            if (paytimestart.HasValue || paytimeend.HasValue)
            {
                sql += " join (select origin_order_id from dc_base_oms_order where company_id=1 ";

                if (paytimestart.HasValue)
                {
                    sql += " and paid_time>=@paytimestart";
                    sqlparam.Add("paytimestart", paytimestart.Value);
                }
                if (paytimeend.HasValue)
                {
                    sql += " and paid_time<@paytimeend";
                    sqlparam.Add("paytimeend", paytimeend.Value.AddDays(1));
                }

                sql += ") t2 on t1.origin_order_id=t2.origin_order_id";
            }

            sql += " where t1.is_deleted=0 and t1.is_freeze=0 and t1.company_id="+companyid.Value;

            if (start.HasValue)
            {
                sql += " and t1.refund_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.refund_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value != 0)
            {
                //sql += " and t1.company_id=" + companyid.Value;
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }
            if (!string.IsNullOrEmpty(orderno))
            {
                sql += " and t1.origin_order_id=@orderno";
                sqlparam.Add("orderno", orderno);
            }

            if (shippingstatus.HasValue)
            {
                if (shippingstatus.Value == 1)
                {
                    sql += " and t1.shipping_status in ('TotalShipping','PartShipping')";
                }
                else
                {
                    sql += " and t1.shipping_status in ('UnShipping','') ";
                }
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_crm_refund>(sql,sqlparam,null,2*60);

                return obj;
            }

        }

        /// <summary>
        /// 获取平台退款数据
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="isUSD"></param>
        /// <returns></returns>
        public List<dc_base_oms_order> ListPlatformRefund(DateTime? start, DateTime? end, int? companyid, string platform, string website, bool isUSD,bool containNotShipping, int[] producttype, int? skusource, int? shippingstrategy,int statistictype)
        {
            var str_statistic_col = "t1.platform_type";

            if (statistictype == 1) //sku品类
            {
                str_statistic_col = "t10.bailun_category_id as platform_type";
            }
            else if (statistictype == 2) //sku来源
            {
                str_statistic_col = "t10.source as platform_type";
            }

            var sqlparam = new DynamicParameters();
            var sql = $"select {str_statistic_col},{(isUSD? "sum(t1.amount_refund_usd)" : "sum(t1.amount_refund_rmb)")} as amount_refund from dc_base_crm_refund t1 ";

            if ((producttype!=null && producttype.Count()>0) || skusource.HasValue || shippingstrategy.HasValue || statistictype!=0)
            {
                sql += " join dc_base_sku t10 on t1.bailun_sku=t10.bailun_sku ";

                if (producttype!=null && producttype.Count()>0)
                {
                    sql += " and t10.bailun_category_id in (" + string.Join(",",producttype)+") ";
                }

                if (skusource.HasValue)
                {
                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3海外仓; 4FBA仓
                {
                    sql += " join dc_base_oms_sku t11 on t1.bailun_sku=t11.bailun_sku and t1.origin_order_id=t11.origin_order_id and t1.bailun_account_id=t11.bailun_account_id and t11.has_delete=0 ";

                    if (shippingstrategy.Value == 1)
                    {
                        var listSpecialLogistics = CommonServices.ListLogisticsConfig(1);

                        if (shippingstrategy.Value == 1)
                        {
                            sql += " and t11.logistics_method_code in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                        }
                        else if (shippingstrategy.Value == 2)
                        {
                            sql += " and t11.logistics_method_code not in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                        }
                    }
                    else
                    {
                        sql += " join dc_base_warehouse t20 on t11.warehouse_code = t20.warehouse_code ";

                        if (shippingstrategy.Value == 2)  //中国发货
                        {
                            sql += "  and t20.area_id=18 ";

                        }
                        else if (shippingstrategy.Value == 3)  //海外仓
                        {
                            sql += " and t20.hq_type='第三方仓库' ";
                        }
                        else if (shippingstrategy.Value == 4)  //FBA仓
                        {
                            sql += " and t20.hq_type='FBA仓' ";
                        }

                    }
                }
            }


            if (statistictype == 1) //sku品类
            {

            }
            else if (statistictype == 2) //sku来源
            {
                sql += " and t10.source in (1,2,3,6,7,11) ";
            }

            sql += " where t1.is_deleted=0 and is_freeze=0 ";
            
            if (companyid.HasValue && companyid.Value != 0)
            {
                sql += " and t1.company_id="+companyid.Value;
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);

            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                sql += " and t1.refund_time>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.refund_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (!containNotShipping)
            {
                sql += " and t1.shipping_status in ('TotalShipping','PartShipping') ";
            }


            if (statistictype == 0)
            {
                sql += " group by t1.platform_type";
            }
            else if (statistictype == 1)
            {
                sql += " group by t10.bailun_category_id"; 
            }
            else if (statistictype == 2)
            {
                sql += " group by t10.source";
            }

            
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_oms_order>(sql, sqlparam, null, true, 2 * 60);
                
                return obj.AsList();
            }
        }
        
        #endregion

        #region 广告费

        #region 亚马逊

        /// <summary>
        /// 亚马逊广告费列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_finance_amazon_ad_product> ListAmazonADSku(BtTableParameter parameter, string account, DateTime? start, DateTime? end, int? companyid,int? type, ref int total)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t2.account_name,t1.sku,t1.currency,cost,(cost*exchange_rate) cost_rmb,report_date,type from dc_base_finance_amazon_ad_product t1 join dc_base_company_account t2 on t1.account_id=t2.account_id ";

            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t2.account_name=@account";
                sqlparam.Add("account", account);
            }

            sql += " where 1=1 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=@companyid";
                sqlparam.Add("companyid", companyid);
            }

            if (start.HasValue)
            {
                sql += " and t1.report_date>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.report_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if(type.HasValue)
            {
                sql += " and t1.type="+type.Value;
            }

            if (!string.IsNullOrEmpty(parameter.sort))
            {
                sql += " order by t1." + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_finance_amazon_ad_product>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam);

                return obj.AsList();
            }
        }

        /// <summary>
        /// 亚马逊广告费列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_finance_amazon_ad_product> ListAmazonADSku(string account, DateTime? start, DateTime? end, int? companyid,int? type)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t2.account_name,t1.sku,t1.currency,cost,(cost*exchange_rate) cost_rmb,report_date,asin,t2.site_en,t1.type from dc_base_finance_amazon_ad_product t1 join dc_base_company_account t2 on t1.account_id=t2.account_id ";

            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t2.account_name=@account";
                sqlparam.Add("account", account);
            }

            sql += " where 1=1 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=@companyid";
                sqlparam.Add("companyid", companyid);
            }

            if (start.HasValue)
            {
                sql += " and t1.report_date>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.report_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if(type.HasValue)
            {
                sql += " and t1.type="+type.Value;
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_finance_amazon_ad_product>(sql, sqlparam);

                return obj.AsList();
            }
        }

        /// <summary>
        /// 亚马逊广告费汇总
        /// </summary>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public dc_base_finance_amazon_ad_product ListAmazonADSkuCount(string account, DateTime? start, DateTime? end, int? companyid,bool isUSD, int[] producttype, int? skusource, int? shippingstrategy,string platform,string website, int? type)
        {
            if (platform != null && platform.ToLower() != "fba")
            {
                return new dc_base_finance_amazon_ad_product();
            }

            var sqlparam = new DynamicParameters();
            var sql = $"select sum(cost) cost,sum(cost*{(isUSD?"exchange_rate_usd":"exchange_rate")}) cost_rmb from dc_base_finance_amazon_ad_product t1 join dc_base_company_account t2 on t1.account_id=t2.account_id ";

            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t2.account_name=@account";
                sqlparam.Add("account", account);
            }

            //Add by Allan at 20200320
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue)
            {
                sql = $"select sum(cost) cost,sum(cost*{(isUSD ? "exchange_rate_usd" : "exchange_rate")}) cost_rmb from dc_base_finance_amazon_item t1 join dc_base_company_account t2 on t1.account_id=t2.account_id ";

                sqlparam = new DynamicParameters();

                if (!string.IsNullOrEmpty(account))
                {
                    sql += " and t2.account_name=@account";
                    sqlparam.Add("account", account);
                }

                sql += " join dc_base_sku t10 on t1.bailun_sku=t10.bailun_sku ";

                if (producttype.Count()>0)
                {
                    sql += " and t10.bailun_category_id in (" + string.Join(",",producttype)+") ";
                }

                if (skusource.HasValue)
                {
                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3美国仓
                {

                }

            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " join dc_base_company_account t20 on t20.account_id = t1.account_id and t20.company_id=1 and t20.status=1 and t20.site_en='" + website + "'";
            }

            sql += " where t1.id!=0 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=@companyid";
                sqlparam.Add("companyid", companyid);
            }

            if (start.HasValue)
            {
                sql += " and t1.report_date>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.report_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (type.HasValue)
            {
                sql += " and t1.type=" + type.Value;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_finance_amazon_ad_product>(sql, sqlparam);

                return obj;
            }

        }

        /// <summary>
        /// 亚马逊广告费汇总
        /// </summary>
        /// <param name="account"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public List<dc_base_finance_amazon_ad_product> ListAmazonADSkuCount(string account, DateTime? start, DateTime? end, int? companyid, bool isUSD, int[] producttype, int? skusource, int? shippingstrategy,int statistictype,string platform,string website)
        {
            if (platform!=null && platform.ToLower() != "fba")
            {
                return new List<dc_base_finance_amazon_ad_product>();
            }

            var sqlparam = new DynamicParameters();
            var sql = $"select sum(cost) cost,sum(cost*{(isUSD ? "exchange_rate_usd" : "exchange_rate")}) cost_rmb from dc_base_finance_amazon_ad_product t1 join dc_base_company_account t2 on t1.account_id=t2.account_id ";

            if (!string.IsNullOrEmpty(account))
            {
                sql += " and t2.account_name=@account";
                sqlparam.Add("account", account);
            }

            //Add by Allan at 20200320
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue || statistictype!=0)
            {
                var s = "";

                if (statistictype == 1)
                {
                    s = " t10.bailun_category_id as platform,";
                }
                else if (statistictype == 2)
                {
                    s = " t10.source as platform,";
                }

                sql = $"select {s} sum(cost) cost,sum(cost*{(isUSD ? "exchange_rate_usd" : "exchange_rate")}) cost_rmb from dc_base_finance_amazon_item t1 join dc_base_company_account t2 on t1.account_id=t2.account_id ";

                sqlparam = new DynamicParameters();

                if (!string.IsNullOrEmpty(account))
                {
                    sql += " and t2.account_name=@account";
                    sqlparam.Add("account", account);
                }

                sql += " join dc_base_sku t10 on t1.bailun_sku=t10.bailun_sku ";

                if (producttype.Count() > 0)
                {
                    sql += " and t10.bailun_category_id in (" + string.Join(",", producttype) + ") ";
                }

                if (skusource.HasValue)
                {
                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3美国仓
                {

                }

            }

            if (!string.IsNullOrEmpty(website))
            {
                sql += " join dc_base_company_account t20 on t20.account_id = t1.account_id and t20.company_id=1 and t20.status=1 and t20.site_en='" + website + "'";
            }

            sql += " where t1.id!=0 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=@companyid";
                sqlparam.Add("companyid", companyid);
            }

            if (start.HasValue)
            {
                sql += " and t1.report_date>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.report_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }


            if (statistictype == 1)
            {
                sql += " group by t10.bailun_category_id ";
            }
            else if (statistictype == 2)
            {
                sql += " group by t10.source ";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_finance_amazon_ad_product>(sql, sqlparam).ToList();

                return obj;
            }

        }

        #endregion

        #region Wish

        /// <summary>
        /// Wish广告费列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="companyid">公司id</param>
        /// <param name="account_id">帐号id</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="total">符合条件的总记录数</param>
        /// <param name="isUSD">是否美元</param>
        /// <returns></returns>
        public List<dc_base_finance_wish> ListWishAD(BtTableParameter parameter,int? companyid, string account_name, DateTime? start, DateTime? end, ref int total,bool isUSD)
        {
            var sqlparam = new DynamicParameters();
            var sql = $"select t1.campaign_name,t2.account_name,t1.daily_total_campaign_spend,(t1.daily_total_campaign_spend*{(isUSD? "t1.other_to_usd_exchange_rate":"t1.other_to_cny_exchange_rate")}) daily_total_campaign_spend_rmb,t1.record_time from dc_base_finance_wish t1 join dc_base_company_account t2 on t1.account_id=t2.account_id where 1=1 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id="+companyid.Value;
            }

            if (!string.IsNullOrEmpty(account_name))
            {
                sql += " and t2.account_name=@account_name";
                sqlparam.Add("account_name", account_name);
            }

            if (start.HasValue)
            {
                sql += " and t1.record_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.record_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_finance_wish>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam, "", 2 * 60);
                return obj.AsList();
            }

        }

        /// <summary>
        /// Wish广告费列表
        /// </summary>
        /// <param name="companyid">公司id</param>
        /// <param name="account_id">帐号id</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="total">符合条件的总记录数</param>
        /// <param name="isUSD">是否美元</param>
        /// <returns></returns>
        public List<dc_base_finance_wish> ListWishAD(int? companyid, string account_name, DateTime? start, DateTime? end , bool isUSD)
        {
            var sqlparam = new DynamicParameters();
            var sql = $"select t1.campaign_name,t2.account_name,t1.daily_total_campaign_spend,(t1.daily_total_campaign_spend*{(isUSD ? "t1.other_to_usd_exchange_rate" : "t1.other_to_cny_exchange_rate")}) daily_total_campaign_spend_rmb,t1.record_time from dc_base_finance_wish t1 join dc_base_company_account t2 on t1.account_id=t2.account_id where 1=1 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;
            }

            if (!string.IsNullOrEmpty(account_name))
            {
                sql += " and t2.account_name=@account_name";
                sqlparam.Add("account_name", account_name);
            }

            if (start.HasValue)
            {
                sql += " and t1.record_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.record_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_finance_wish>(sql,sqlparam, null,true,2 * 60);
                return obj.AsList();
            }

        }

        /// <summary>
        /// Wish广告费汇总
        /// </summary>
        /// <param name="companyid">公司id</param>
        /// <param name="account_id">帐号id</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="isUSD">是否美元</param>
        /// <returns></returns>
        public dc_base_finance_wish ListWishADCount(int? companyid, string account_name, DateTime? start, DateTime? end, bool isUSD)
        {
            var sqlparam = new DynamicParameters();
            var sql = $"select sum(t1.daily_total_campaign_spend) daily_total_campaign_spend,sum(t1.daily_total_campaign_spend*{(isUSD ? "t1.other_to_usd_exchange_rate" : "t1.other_to_cny_exchange_rate")}) daily_total_campaign_spend_rmb from dc_base_finance_wish t1 join dc_base_company_account t2 on t1.account_id=t2.account_id  where 1=1 ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t1.company_id=" + companyid.Value;
            }

            if (!string.IsNullOrEmpty(account_name))
            {
                sql += " and t2.account_name=@account_name";
                sqlparam.Add("account_name", account_name);
            }

            if (start.HasValue)
            {
                sql += " and t1.record_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.record_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_finance_wish>(sql, sqlparam,null,2*60);
                return obj;
            }
        }

        #endregion

        #region 速卖通

        /// <summary>
        /// 速卖通广告列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="companyid">公司id</param>
        /// <param name="account">帐号</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="isUSD">是否美元</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_base_finance_aliexpress> ListAliexpressAD(BtTableParameter parameter, int? companyid, string account, DateTime? start, DateTime? end, bool isUSD, ref int total)
        {
            var sqlparam = new DynamicParameters();
            var sql = $" select account_name,product_name,exposure,clickcount,clickrate,cost_fee,(cost_fee*{(isUSD? "to_usd_rate" : "to_rmb_rate")}) cost_fee_rmb,currency,recore_time from dc_base_finance_aliexpress where delstatus=0";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id="+companyid.Value;
            }

            if (!string.IsNullOrEmpty(account))
            {
                sql += " and account_name=@account";
                sqlparam.Add("account", account);
            }

            if (start.HasValue)
            {
                sql += " and recore_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and recore_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_finance_aliexpress>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam, "", 2 * 60).AsList();
                return obj;
            }
        }

        /// <summary>
        /// 速卖通广告列表
        /// </summary>
        /// <param name="companyid">公司id</param>
        /// <param name="account">帐号</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="isUSD">是否美元</param>
        /// <returns></returns>
        public List<dc_base_finance_aliexpress> ListAliexpressAD(int? companyid, string account, DateTime? start, DateTime? end, bool isUSD)
        {
            var sqlparam = new DynamicParameters();
            var sql = $" select account_name,product_name,exposure,clickcount,clickrate,cost_fee,(cost_fee*{(isUSD ? "to_usd_rate" : "to_rmb_rate")}) cost_fee_rmb,currency,recore_time from dc_base_finance_aliexpress where delstatus=0";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;
            }

            if (!string.IsNullOrEmpty(account))
            {
                sql += " and account_name=@account";
                sqlparam.Add("account", account);
            }

            if (start.HasValue)
            {
                sql += " and recore_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and recore_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_finance_aliexpress>(sql, sqlparam,null,true,2*60).AsList();
                return obj;
            }
        }

        /// <summary>
        /// 速卖通广告统计
        /// </summary>
        /// <param name="companyid">公司id</param>
        /// <param name="account">帐号</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="isUSD">是否美元</param>
        /// <returns></returns>
        public dc_base_finance_aliexpress ListAliexpressADCount(int? companyid, string account, DateTime? start, DateTime? end, bool isUSD)
        {
            var sqlparam = new DynamicParameters();
            var sql = $" select sum(cost_fee) cost_fee,sum(cost_fee*{(isUSD ? "to_usd_rate" : "to_rmb_rate")}) cost_fee_rmb from dc_base_finance_aliexpress where delstatus=0";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and company_id=" + companyid.Value;
            }

            if (!string.IsNullOrEmpty(account))
            {
                sql += " and account_name=@account";
                sqlparam.Add("account", account);
            }

            if (start.HasValue)
            {
                sql += " and recore_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and recore_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_finance_aliexpress>(sql, sqlparam, null,2 * 60);
                return obj;
            }
        }

        /// <summary>
        /// 保存速卖通的广告费
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public string SaveAliExpressAD(List<dc_base_finance_aliexpress> list)
        {
            try
            {
                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
                {
                    if (cn.State == System.Data.ConnectionState.Closed)
                    {
                        cn.Open();
                    }

                    foreach (var item in list)
                    {
                        cn.Insert(item);
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
        }


        #endregion

        #endregion

        #region Paypal费

        /// <summary>
        /// paypal费流水
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_base_finance_paypal> ListPaypal(BtTableParameter parameter,DateTime? start,DateTime? end,int? companyid,ref int total)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t1.transaction_id,t1.receipt_id,t1.transaction_type,t1.payment_type,t1.payment_date,t1.gross_amount,t1.payment_status,t1.business,t1.receiver,t1.currency,(t1.gross_amount*t1.other_to_cny_exchange_rate) gross_amount_rmb from dc_base_finance_paypal t1 where 1=1 ";

            if (start.HasValue)
            {
                sql += " and t1.payment_date>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.payment_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value != 0)
            {
                sql += " and t1.saas_company_id=@companyid";
                sqlparam.Add("companyid", companyid.Value);
            }

            if (!string.IsNullOrWhiteSpace(parameter.sort))
            {
                sql += " and t1." + parameter.sort + " " + parameter.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_finance_paypal>(parameter.pageIndex, parameter.limit, sql, ref total, sqlparam, "", 2 * 60);

                return obj.AsList();
            }
        }

        /// <summary>
        /// Paypal费用汇总
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public dc_base_finance_paypal ListPaypalCount(DateTime? start, DateTime? end, int? companyid)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select sum(t1.gross_amount) gross_amount,sum(t1.gross_amount*t1.other_to_cny_exchange_rate) gross_amount_rmb from dc_base_finance_paypal t1 where 1=1 ";

            if (start.HasValue)
            {
                sql += " and t1.payment_date>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.payment_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value != 0)
            {
                sql += " and t1.saas_company_id=@companyid";
                sqlparam.Add("companyid", companyid.Value);
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_finance_paypal>(sql, sqlparam);

                return obj;
            }
        }

        /// <summary>
        /// paypal费流水
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public List<dc_base_finance_paypal> ListPaypal(DateTime? start, DateTime? end, int? companyid)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select t1.transaction_id,t1.receipt_id,t1.transaction_type,t1.payment_type,t1.payment_date,t1.gross_amount,t1.payment_status,t1.business,t1.receiver,t1.currency,(t1.gross_amount*t1.other_to_cny_exchange_rate) gross_amount_rmb from dc_base_finance_paypal t1 where 1=1 ";

            if (start.HasValue)
            {
                sql += " and t1.payment_date>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                sql += " and t1.payment_date<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (companyid.HasValue && companyid.Value != 0)
            {
                sql += " and t1.saas_company_id=@companyid";
                sqlparam.Add("companyid", companyid.Value);
            }


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_finance_paypal>(sql,sqlparam, null,true,2*60);

                return obj.AsList();
            }
        }

        #endregion

        #region 拦截订单

        public List<mInterceptOrderItemid> ListInterceptOrderItemId(int page,int pagesize,DateTime? start, DateTime? end,ref int total,string platform,int? accountid)
        {
            var sqlparam = new DynamicParameters();

            var sql = "select item_id,sum(platform_sku_quantity_ordered) count from dc_base_oms_platform_sku where bailun_payment_status!='Canceled' and has_scalp=1 ";

            if (start.HasValue)
            {
                sql += " and paid_time>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and paid_time<@end";
                sqlparam.Add("end", end.Value);
            }

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and platform_type=@platform";
                sqlparam.Add("platform", platform);
            }

            if(accountid.HasValue)
            {
                sql += " and bailun_account_id=@accountid";
                sqlparam.Add("accountid", accountid.Value);
            }

            //分页记录
            //sql += " limit "+(page-1)*pagesize+","+pagesize;

            sql += " group by item_id ";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<mInterceptOrderItemid>(sql, sqlparam, null,true,2*60).AsList();

                return obj;
            }
        }

        #endregion

        #region 图表

        /// <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="isUSD"></param>
        /// <param name="companyid"></param>
        /// <param name="skucategoryids"></param>
        /// <returns></returns>
        public List<Models.OrderChart.ProformProfitChart> ListOrderProfitGraph(string col,string platform, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, bool isUSD, int? companyid, string skucategoryids)
        {
            var sqlparam = new DynamicParameters();

            if (col == "order_count")
            {
                col = "count(bailun_order_id) as val";
            }
            else
            {
                if (col == "amount_sales")  //销售额需转换汇率
                {
                    col = "sum(" + col + "*"+(!isUSD? "seller_order_exchange_rate" : "order_to_usd_exchange_rate") +") as val";
                }
                else
                {
                    col = "sum(" + col + ") as val";
                }
                
            }

            var sql = $"select {col},DATE_FORMAT(tb.paid_time,'%Y-%m-%d') as date from dc_base_oms_order tb ";

            if (shipstart.HasValue || shipend.HasValue)
            {
                //sql += " join dc_base_oms_pick t1 on tb.bailun_order_id =t1.bailun_order_id ";
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += " join dc_base_oms_sku t3 on tb.bailun_order_id=t3.bailun_order_id ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    var AllCategory = Services.CommonServices.GetCategoryList(0);
                    var listcategory = new List<Models.Common.CategoryDto>();

                    foreach (var item in arr)
                    {
                        listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    }

                    var s = string.Join(",", listcategory.Select(a => a.C_ID));
                    if (!string.IsNullOrEmpty(s))
                    {
                        sql += " and t3.bailun_category_id in (" + s + ") ";
                    }
                }
            }

            sql += "  where tb.bailun_order_status!='Canceled' and ((tb.platform_type!='FBA' and tb.bailun_order_status!='CantHandle') or tb.platform_type='FBA') and tb.has_scalp=0 and tb.has_innersale=0 and tb.bailun_interception_status in ('None','Failed') ";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and tb.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and tb.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }
            if (start.HasValue)
            {
                sql += " and tb.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and tb.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }
            if (shipstart.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time>=@shipstart) or (tb.platform_type!='FBA' and t1.shipping_time>=@shipstart))";
                sqlparam.Add("shipstart", shipstart.Value);
            }
            if (shipend.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time<@shipend) or (tb.platform_type!='FBA' and t1.shipping_time<@shipend))";
                sqlparam.Add("shipend", shipend.Value.AddDays(1));
            }


            sql += "  group by DATE_FORMAT(tb.paid_time,'%Y-%m-%d')";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.OrderChart.ProformProfitChart>(sql, sqlparam, null, true, 2 * 60);

                return obj.AsList();
            }
        }


        /// <summary>
        /// 平台销售统计曲线数据
        /// </summary>
        /// <param name="col"></param>
        /// <param name="platform"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="website"></param>
        /// <param name="account"></param>
        /// <param name="companyid"></param>
        /// <param name="skucategoryids"></param>
        /// <param name="warehoursetype"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public List<Models.OrderChart.ProformProfitChart> ListOrderSalesGraph(string col,string platform,DateTime? start,DateTime? end,string website,string account,int? companyid,string skucategoryids,string warehoursetype,string warehousecode,bool websiteGroup=false)
        {
            var sqlparam = new DynamicParameters();

            if (col == "order_count")
            {
                col = "count(t1.bailun_order_id) as val";
            }
            else
            {
                if (col == "t1.amount_sales")  //销售额需转换汇率
                {
                    col = "sum(" + col + "*t1.seller_order_exchange_rate) as val";
                }
                else
                {
                    col = "sum(" + col + ") as val";
                }

            }

            var sql = $"select {col},DATE_FORMAT(t1.paid_time,'%Y-%m-%d') as date from dc_base_oms_order t1 ";


            if (!string.IsNullOrEmpty(warehoursetype) || !string.IsNullOrEmpty(warehousecode) || !string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += " join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id ";

                if (!string.IsNullOrWhiteSpace(skucategoryids))
                {
                    //sql += " join dc_base_oms_sku t3 on t1.bailun_order_id=t3.bailun_order_id ";

                    var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                    if (arr.Count > 0)
                    {
                        //获取选中分类下所有的分类
                        var AllCategory = Services.CommonServices.GetCategoryList(0);
                        var listcategory = new List<Models.Common.CategoryDto>();

                        foreach (var item in arr)
                        {
                            listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                        }

                        var s = string.Join(",", listcategory.Select(a => a.C_ID));
                        if (!string.IsNullOrEmpty(s))
                        {
                            sql += " and t3.bailun_category_id in (" + s + ") ";
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(warehoursetype))
            {
                sql += " join dc_base_warehouse t2 on t3.warehouse_code=t2.warehouse_code and t2.warehouse_type_ex=@warehoursetype";
                sqlparam.Add("warehoursetype", warehoursetype);
            }
            if (!string.IsNullOrEmpty(warehousecode))
            {
                if (!string.IsNullOrEmpty(warehoursetype))
                {
                    sql += " and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
                else
                {
                    sql += " join dc_base_warehouse t2 on t3.warehouse_code=t2.warehouse_code and t2.warehouse_code=@warehouse_code";
                    sqlparam.Add("warehouse_code", warehousecode);
                }
            }

          
            var fromsql = " where t1.bailun_payment_status!='Canceled' and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.bailun_order_status!='Canceled' and t1.has_scalp=0 and t1.has_innersale=0 and t1.bailun_interception_status in ('None','Failed') ";
            
            if (companyid.HasValue && companyid.Value > 0)
            {
                fromsql += "and t1.company_id = " + companyid.Value; //增加公司id判断
            }

            if (!string.IsNullOrWhiteSpace(account))
            {
                fromsql += " and t1.seller_account=@seller_account";
                sqlparam.Add("seller_account", account);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                fromsql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (!string.IsNullOrEmpty(platform))
            {
                fromsql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if(start.HasValue)
            {
                fromsql += " and paid_time>=@start";
                sqlparam.Add("start", start.Value);
            }

            if (end.HasValue)
            {
                fromsql += " and paid_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }


            if (!websiteGroup)  //按账号+站点+平台+日期 进行分组
            {
                fromsql += " group by t1.seller_account,t1.website,t1.platform_type,DATE_FORMAT(t1.paid_time,'%Y-%m-%d')";
            }
            else   //按站点+平台+日期 进行分组
            {
                fromsql += " group by t1.website,t1.platform_type,DATE_FORMAT(t1.paid_time,'%Y-%m-%d')";
            }
            


            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.OrderChart.ProformProfitChart>(sql + fromsql, sqlparam);

                return obj.ToList();
            }
        }

        #endregion

        #region For Sku:FJH-L-2 profit


        /// <summary>
        /// 获取Sku:FJH-L-2的利润
        /// </summary>
        /// <param name="platform">平台类型</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_sku> ListSkuProfit_FJH_L_2(string platform, string website, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, bool isUSD, int? companyid, string skucategoryids, int[] producttype, int? skusource, int? shippingstrategy, DateTime? createstart = null, DateTime? createend = null)
        {
            var sqlparam = new DynamicParameters();
            var sql = "select tb.platform_type,count(distinct tb.bailun_order_id) order_count,sum(tb.amount_sales*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "* tb.bailun_sku_quantity_ordered) as amount_sales,sum(tb.cost_platform_fee*(if(tb.platform_type='Ebay'," + (isUSD ? "tb.other_to_usd_exchange_rate" : "tb.seller_other_exchange_rate") + "," + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "))*tb.bailun_sku_quantity_ordered) as cost_platform_fee,sum(tb.cost_first*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) as cost_first,sum(tb.cost_logistics*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_tail,sum(tb.cost_handle_bailun*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_handle_bailun,sum(tb.cost_handle_platform*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_handle_platform,sum(tb.amount_refund*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) amount_refund,sum(tb.cost_fba_fee*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) cost_fba_fee,sum(tb.cost_paypal_fee*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) cost_paypal_fee,sum(tb.amount_shipping*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) amount_shipping,sum(tb.cost_promotion*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + "*tb.bailun_sku_quantity_ordered) cost_promotion,sum(tb.cost_product*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) cost_product,sum(tb.profit_total*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) profit_total,(sum(tb.profit_total*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + ")/sum(tb.amount_sales*" + (isUSD ? "tb.order_to_usd_exchange_rate" : "tb.seller_order_exchange_rate") + ")) profit_rate,count((tb.amount_prepaid>0 and tb.bailun_order_status!='Finished') or null) as noshippingcount,sum(tb.amount_prepaid*" + (isUSD ? "tb.cny_to_usd_exchange_rate" : "1") + "*tb.bailun_sku_quantity_ordered) amount_prepaid  from dc_base_oms_sku tb ";

            if (shipstart.HasValue || shipend.HasValue)
            {
                sql += " left join dc_base_oms_pick t1 on tb.bailun_order_id =t1.bailun_order_id ";
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += @" join (select distinct bailun_order_id from dc_base_oms_sku t3
                          join dc_base_sku t4 on t3.bailun_sku=t4.bailun_sku
                        ";

                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        //sql += " and t3.bailun_category_id in (" + s + ") ";
                        sql += " and t4.category_simple_id in (" + s + ")";
                    }
                }

                sql += " where t3.bailun_order_status!='Canceled' and ((t3.platform_type!='FBA' and t3.bailun_order_status!='CantHandle') or t3.platform_type='FBA') and t3.has_scalp=0 and t3.has_innersale=0 and t3.bailun_interception_status in ('None','Failed') and t3.has_delete=0 and t3.bailun_sku='FJH-L-2' ";
                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and t3.company_id=" + companyid.Value;    //增加公司id过滤
                }

                if (!string.IsNullOrWhiteSpace(platform))
                {
                    sql += " and t3.platform_type='" + platform + "'";
                }

                if (!string.IsNullOrWhiteSpace(website))
                {
                    sql += " and t3.website='" + website + "'";
                }
                if (start.HasValue)
                {
                    sql += " and t3.paid_time>='" + start.Value.ToString("yyyy-MM-dd") + "'";
                }
                if (end.HasValue)
                {
                    sql += " and t3.paid_time<'" + end.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
                }

                sql += ") t33 on tb.bailun_order_id=t33.bailun_order_id";

            }
            


            //Add by Allan at 20200320，for 增加sku级别的利润统计
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue)
            {
                sql += $@" join (select t1.bailun_order_id,t2.product_type from dc_base_oms_sku t1 
                                join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku
                                where t1.bailun_order_id in (select t1.bailun_order_id from dc_base_oms_sku t1
                                where t1.bailun_sku='FJH-L-2' and t1.bailun_order_status != 'Canceled' and t1.has_scalp = 0 and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp = 0 and t1.has_innersale = 0  and t1.has_delete=0 and t1.paid_time>='{start.Value.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.paid_time<'{end.Value.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")}'
                                )
                                and t1.bailun_sku!='FJH-L-2'
                                group by t1.bailun_order_id,t2.product_type) t99 
                            on tb.bailun_order_id=t99.bailun_order_id ";


                if (producttype.Count() > 0)
                {
                    sql += " and t99.product_type in (" + string.Join(",", producttype) + ") ";
                }

                if (skusource.HasValue)
                {
                    sql += " join dc_base_sku t10 on tb.bailun_sku=t10.bailun_sku ";

                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3海外仓; 4FBA仓
                {
                    if (shippingstrategy.Value != 1)
                    {
                        sql += " join dc_base_warehouse t20 on tb.warehouse_code = t20.warehouse_code ";

                        if (shippingstrategy.Value == 2)  //中国发货
                        {
                            sql += "  and t20.area_id=18 ";

                        }
                        else if (shippingstrategy.Value == 3)  //海外仓
                        {
                            sql += " and t20.hq_type='第三方仓库' ";
                        }
                        else if (shippingstrategy.Value == 4)  //FBA仓
                        {
                            sql += " and t20.hq_type='FBA仓' ";
                        }

                    }
                }
            }


            sql += "  where tb.bailun_order_status!='Canceled' and ((tb.platform_type!='FBA' and tb.bailun_order_status!='CantHandle') or tb.platform_type='FBA') and tb.has_scalp=0 and tb.has_innersale=0 and tb.bailun_interception_status in ('None','Failed') and tb.bailun_sku='FJH-L-2'";


            if (shippingstrategy.HasValue)  //1专线;2中国发货;3海外仓; 4FBA仓
            {
                var listSpecialLogistics = CommonServices.ListLogisticsConfig(1);

                if (shippingstrategy.Value == 1)
                {
                    sql += " and tb.logistics_method_code in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                }
                else if (shippingstrategy.Value == 2)
                {
                    sql += " and tb.logistics_method_code not in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                }

            }

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and tb.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and tb.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and tb.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                sql += " and tb.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and tb.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }
            if (shipstart.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time>=@shipstart) or (tb.platform_type!='FBA' and t1.shipping_time>=@shipstart))";
                sqlparam.Add("shipstart", shipstart.Value);
            }
            if (shipend.HasValue)
            {
                sql += " and ((tb.platform_type='FBA' and tb.paid_time<@shipend) or (tb.platform_type!='FBA' and t1.shipping_time<@shipend))";
                sqlparam.Add("shipend", shipend.Value.AddDays(1));
            }

            if (createstart.HasValue)
            {
                sql += " and tb.create_time>=@createstart";
                sqlparam.Add("createstart", createstart.Value);
            }
            if (createend.HasValue)
            {
                sql += " and tb.create_time<@createend";
                sqlparam.Add("createend", createend.Value.AddDays(1));
            }


            sql += "  group by tb.platform_type";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Orders.dc_base_oms_sku>(sql, sqlparam, null, true, 2 * 60);

                return obj.AsList();
            }

        }

        

        /// <summary>
        /// 根据发货时间获取Sku:FJH-L-2的利润统计
        /// </summary>
        /// <param name="platform">平台类型</param>
        /// <param name="start">付款开始时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="shipstart">发货开始时间</param>
        /// <param name="shipend">发货结束时间</param>
        /// <returns></returns>
        public List<Models.Orders.dc_base_oms_sku> ListSkuProfit_FJH_L_2_ByShipTime(string platform, string website, DateTime? start, DateTime? end, DateTime? shipstart, DateTime? shipend, bool isUSD, int? companyid, string skucategoryids, int[] producttype, int? skusource, int? shippingstrategy)
        {
            var sqlparam = new DynamicParameters();
            var sql = @"select t2.platform_type,count(DISTINCT t2.bailun_order_id) order_count,sum(t2.amount_sales*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) as amount_sales,sum(t2.cost_platform_fee*(if(t2.platform_type='Ebay'," + (isUSD ? "t2.other_to_usd_exchange_rate" : "t2.seller_other_exchange_rate") + "," + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "))*t1.quantity_shipped) as cost_platform_fee,sum(t2.cost_first*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) as cost_first,sum(t2.cost_logistics*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_tail,sum(t2.cost_handle_bailun*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_handle_bailun,sum(t2.cost_handle_platform*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_handle_platform,sum(t2.amount_refund*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) amount_refund,sum(t2.cost_product*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) cost_product,sum(t2.profit_total*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) profit_total,(sum(t2.profit_total*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped)/sum(t2.amount_sales*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped)) profit_rate,count(t2.amount_prepaid>0 or null) as noshippingcount,sum(t2.amount_prepaid*" + (isUSD ? "t2.cny_to_usd_exchange_rate" : "1") + "*t1.quantity_shipped) amount_prepaid,sum(t2.cost_fba_fee*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) cost_fba_fee,sum(t2.cost_paypal_fee*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) cost_paypal_fee,sum(t2.amount_shipping*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) amount_shipping,sum(t2.cost_promotion*" + (isUSD ? "t2.order_to_usd_exchange_rate" : "t2.seller_order_exchange_rate") + "*t1.quantity_shipped) cost_promotion from (select t0.id,t0.bailun_order_id,t0.quantity_shipped,t0.bailun_sku from dc_base_oms_pick t0 ";

            var tempsql = "";

            if (shippingstrategy.HasValue) //1专线;2中国发货;3海外仓 4 FBA仓
            {
                var listSpecialLogistics = CommonServices.ListLogisticsConfig(1);

                if (shippingstrategy.Value == 1)  //专线
                {
                    tempsql = " and t0.logistics_order_id in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "') ";
                }
                else if (shippingstrategy.Value == 2)  //中国发货
                {
                    sql += " join dc_base_warehouse t2 on t0.warehouse_code=t2.warehouse_code and t2.area_id=18 ";
                    tempsql = " and t0.logistics_order_id  not in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "') ";
                }
                else if (shippingstrategy.Value == 3)  //海外仓
                {
                    sql += " join dc_base_warehouse t2 on t0.warehouse_code=t2.warehouse_code and t2.hq_type='第三方仓库' ";
                }
                else if (shippingstrategy.Value == 4)  //FBA仓
                {
                    sql += " join dc_base_warehouse t2 on t0.warehouse_code=t2.warehouse_code and t2.hq_type='FBA仓' ";
                }
            }

            sql += " where t0.bailun_sku='FJH-L-2' and t0.has_delete=0 and t0.shipping_status = 'TotalShipping'" + tempsql;

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " and t0.company_id=" + companyid.Value;    //增加公司id过滤
            }

            if (shipstart.HasValue)
            {
                sql += " and t0.shipping_time>='" + shipstart.Value.ToString("yyyy-MM-dd") + "'";
            }
            if (shipend.HasValue)
            {
                sql += " and t0.shipping_time<'" + shipend.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }

            sql += " ) t1 ";
            sql += " join dc_base_oms_sku t2 on t1.bailun_order_id = t2.bailun_order_id  and t1.bailun_sku=t2.bailun_sku  and t2.bailun_order_status != 'Canceled' and t2.has_scalp = 0 and ((t2.platform_type!='FBA' and t2.bailun_order_status!='CantHandle') or t2.platform_type='FBA') and t2.has_scalp = 0 and t2.has_innersale = 0  and t2.has_delete=0 and t2.bailun_sku='FJH-L-2' ";

            //Add by Allan at 20200320，for 增加sku级别的利润统计
            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue)
            {
                sql += $@" join (select t1.bailun_order_id,t2.product_type from dc_base_oms_sku t1 
                                join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku
                                where t1.bailun_order_id in (select t1.bailun_order_id from dc_base_oms_pick t1
                                where t1.bailun_sku='FJH-L-2' and t1.bailun_order_status != 'Canceled' and t1.has_scalp = 0 and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA') and t1.has_scalp = 0 and t1.has_innersale = 0  and t1.has_delete=0 and t1.shipping_time>='{start.Value.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.shipping_time<'{end.Value.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")}'
                                )
                                and t1.bailun_sku!='FJH-L-2'
                                group by t1.bailun_order_id,t2.product_type) t99 
                            on t2.bailun_order_id=t99.bailun_order_id ";


                if (producttype.Count() > 0)
                {
                    sql += " and t99.product_type in (" + string.Join(",", producttype) + ") ";
                }

                if (skusource.HasValue)
                {
                    sql += " join dc_base_sku t10 on t2.bailun_sku=t10.bailun_sku ";

                    sql += " and t10.source=" + skusource;
                }
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t2.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);
            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and t2.website=@website";
                sqlparam.Add("website", website);

            }

            if (start.HasValue)
            {
                sql += " and t2.paid_time>=@paid_time_start";
                sqlparam.Add("paid_time_start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t2.paid_time<@paid_time_end";
                sqlparam.Add("paid_time_end", end.Value.AddDays(1));
            }

            if (!string.IsNullOrWhiteSpace(skucategoryids))
            {
                sql += " join dc_base_sku t4 on t2.bailun_sku=t4.bailun_sku ";
                var arr = skucategoryids.Split('|').Where(a => !string.IsNullOrEmpty(a)).ToList();
                if (arr.Count > 0)
                {
                    //获取选中分类下所有的分类
                    //var AllCategory = Services.CommonServices.GetCategoryList(0);
                    //var listcategory = new List<Models.Common.CategoryDto>();

                    //foreach (var item in arr)
                    //{
                    //    listcategory.AddRange(Services.CommonServices.GetCategoryListAll(AllCategory, int.Parse(item)));
                    //}

                    var s = string.Join(",", arr);
                    if (!string.IsNullOrEmpty(s))
                    {
                        //sql += " and t4.bailun_category_id in (" + s + ") ";
                        sql += " and t4.category_simple_id in (" + s + ") ";
                    }
                }
            }

            var strwhere = " ";

            strwhere += "  group by t2.platform_type";



            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Orders.dc_base_oms_sku>(sql + strwhere, sqlparam, null, true, 10 * 60);

                return obj.AsList();
            }
        }


        /// <summary>
        /// 获取Sku:FJH-L-2的退款数据
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="isUSD"></param>
        /// <returns></returns>
        public List<dc_base_oms_order> ListSku_FJH_L_2_Refund(DateTime? start, DateTime? end, int? companyid, string platform, string website, bool isUSD, bool containNotShipping, int[] producttype, int? skusource, int? shippingstrategy)
        {
            var sqlparam = new DynamicParameters();
            var sql = $"select t1.platform_type,{(isUSD ? "sum(t1.amount_refund_usd)" : "sum(t1.amount_refund_rmb)")} as amount_refund from dc_base_crm_refund t1 ";

            if ((producttype != null && producttype.Count() > 0) || skusource.HasValue || shippingstrategy.HasValue)
            {
                sql += $@" join (select t1.transaction_id as origin_order_id,t2.product_type from dc_base_oms_sku t1 join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku where (t1.platform_type='Ebay' and t1.transaction_id in (select t1.origin_order_id from dc_base_crm_refund t1 where t1.bailun_sku='FJH-L-2' and t1.shipping_status='TotalShipping' and t1.is_deleted=0 and is_freeze=0 and t1.refund_time>='{start.Value.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.refund_time<'{end.Value.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")}' )) and t1.bailun_sku!='FJH-L-2' group by t1.bailun_order_id,t2.product_type
                            union all 
                            select t1.origin_order_id,t2.product_type from dc_base_oms_sku t1 join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku where (t1.platform_type!='Ebay' and t1.origin_order_id in (select t1.origin_order_id from dc_base_crm_refund t1 where t1.bailun_sku='FJH-L-2' and t1.shipping_status='TotalShipping' and t1.is_deleted=0 and is_freeze=0 and t1.refund_time>='{start.Value.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.refund_time<'{end.Value.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")}' )) and t1.bailun_sku!='FJH-L-2' group by t1.bailun_order_id,t2.product_type) t99 
                            on t1.origin_order_id=t99.origin_order_id ";
                

                if (producttype.Count() > 0)
                {
                    sql += " and t99.product_type in (" + string.Join(",", producttype) + ") ";
                }
                
                if (skusource.HasValue)
                {
                    sql += " join dc_base_sku t10 on t1.bailun_sku=t10.bailun_sku ";
                    sql += " and t10.source=" + skusource;
                }

                if (shippingstrategy.HasValue)  //1专线;2中国发货;3海外仓; 4FBA仓
                {
                    sql += " join dc_base_oms_sku t11 on t1.bailun_sku=t11.bailun_sku and t1.origin_order_id=t11.origin_order_id and t1.bailun_account_id=t11.bailun_account_id and t11.has_delete=0 ";

                    if (shippingstrategy.Value == 1)
                    {
                        var listSpecialLogistics = CommonServices.ListLogisticsConfig(1);

                        if (shippingstrategy.Value == 1)
                        {
                            sql += " and t11.logistics_method_code in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                        }
                        else if (shippingstrategy.Value == 2)
                        {
                            sql += " and t11.logistics_method_code not in ('" + string.Join("','", listSpecialLogistics.Select(a => a.code)) + "')";
                        }
                    }
                    else
                    {
                        sql += " join dc_base_warehouse t20 on t11.warehouse_code = t20.warehouse_code ";

                        if (shippingstrategy.Value == 2)  //中国发货
                        {
                            sql += "  and t20.area_id=18 ";

                        }
                        else if (shippingstrategy.Value == 3)  //海外仓
                        {
                            sql += " and t20.hq_type='第三方仓库' ";
                        }
                        else if (shippingstrategy.Value == 4)  //FBA仓
                        {
                            sql += " and t20.hq_type='FBA仓' ";
                        }

                    }
                }
            }

            sql += " where t1.shipping_status='TotalShipping' and t1.is_deleted=0 and is_freeze=0 and t1.bailun_sku='FJH-L-2' ";

            if (companyid.HasValue && companyid.Value != 0)
            {
                sql += " and t1.company_id=" + companyid.Value;
            }

            if (!string.IsNullOrWhiteSpace(platform))
            {
                sql += " and t1.platform_type=@platform_type";
                sqlparam.Add("platform_type", platform);

            }

            if (!string.IsNullOrWhiteSpace(website))
            {
                sql += " and t1.website=@website";
                sqlparam.Add("website", website);
            }

            if (start.HasValue)
            {
                sql += " and t1.refund_time>=@start";
                sqlparam.Add("start", start.Value);
            }
            if (end.HasValue)
            {
                sql += " and t1.refund_time<@end";
                sqlparam.Add("end", end.Value.AddDays(1));
            }

            if (!containNotShipping)
            {
                sql += " and t1.shipping_status!='UnShipping'";
            }

            sql += " group by t1.platform_type";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_oms_order>(sql, sqlparam, null, true, 2 * 60);

                return obj.AsList();
            }
        }



        #endregion


        #region 头程费

        /// <summary>
        /// 获取头程费配置数据
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehousecode">仓库编码</param>
        /// <param name="bailunsku">sku编码</param>
        /// <param name="total">符合条件的记录数</param>
        /// <returns></returns>
        public List<dc_mid_cost_first> ListCostFirst(BtTableParameter request,string warehousetype,string warehousecode,string bailunsku,ref int total)
        {
            var sqlparam = new DynamicParameters();

            var sql = $@"select t1.*,t1.cost_first*1000/t2.weight as cost_per1000,t3.warehouse_name from dc_mid_cost_first t1
                        join dc_base_sku t2 on t1.bailun_sku=t2.bailun_sku ";

            if (!string.IsNullOrWhiteSpace(bailunsku))
            {
                sql += " and t2.bailun_sku=@sku ";
                sqlparam.Add("sku", bailunsku);
            }

            sql += " join dc_base_warehouse t3 on t1.warehouse_code=t3.warehouse_code";
            
            if (!string.IsNullOrWhiteSpace(warehousetype))
            {
                sql += " and t3.hq_type=@warehousetype";
                sqlparam.Add("warehousetype", warehousetype);
            }

            if (!string.IsNullOrWhiteSpace(warehousecode))
            {
                sql += " and t3.warehouse_code=@warehouse_code";
                sqlparam.Add("warehouse_code", warehousecode);
            }

            if (!string.IsNullOrEmpty(request.sort))
            {
                sql += " order by t1."+request.sort+" "+request.order;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_mid_cost_first>(request.pageIndex, request.limit, sql, ref total, sqlparam);

                return obj.ToList();
            }

        }

        /// <summary>
        /// 获取头程费
        /// </summary>
        /// <param name="request"></param>
        /// <param name="bailun_sku"></param>
        /// <param name="warehousecode"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<dc_base_cost_first_finish> ListCostFirstJson(BtTableParameter request, string transfer_order_id, string bailun_sku,string warehousetype, string warehousecode, int? type,ref int total)
        {
            var sql = "select t1.*,t2.warehouse_name from dc_base_cost_first_finish t1 join dc_base_warehouse t2 on t1.warehouse_code=t2.warehouse_code where 1=1 ";
            var sqlparam = new DynamicParameters();

            if(!string.IsNullOrEmpty(warehousetype))
            {
                sql += " and t2.hq_type=@warehousetype";
                sqlparam.Add("warehousetype",warehousetype);
            }

            if(!string.IsNullOrEmpty(bailun_sku))
            {
                sql += " and t1.bailun_sku=@bailun_sku";
                sqlparam.Add("bailun_sku", bailun_sku);
            }

            if(!string.IsNullOrEmpty(warehousecode))
            {
                sql += " and t1.warehouse_code = @warehousecode";
                sqlparam.Add("warehousecode", warehousecode);
            }

            if(!string.IsNullOrEmpty(transfer_order_id))
            {
                sql += " and t1.transfer_order_id = @transfer_order_id";
                sqlparam.Add("transfer_order_id", transfer_order_id);
            }

            if(type.HasValue)
            {
                sql += " and t1.exception_type=@type";
                sqlparam.Add("type",type);
            }

            if(!string.IsNullOrEmpty(request.sort))
            {
                sql += " order by "+request.sort+" "+request.order;
            }
            else
            {
                sql += " order by operation_time desc";
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_base_cost_first_finish>(request.pageIndex, request.limit, sql, ref total, sqlparam);

                return obj.ToList();
            }

        }


        #endregion

        #region itemno 利润率


        /// <summary>
        /// 获取itemno的广告利润率
        /// </summary>
        /// <param name="itemid"></param>
        /// <param name="day"></param>
        /// <returns></returns>
        public List<mItemNoProfitRate> ListItemNoProfitRate(List<string> itemid, DateTime day)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }


                var sql = $@"select t1.day,t1.item_id,t1.rate_order_ad,t1.rate_order,t1.rate_all,t2.rate_order_ad as rate_order_ad_1day,t2.rate_order as rate_order_1day,t2.rate_all as rate_all_1day from dc_daily_item_profit_rate t1 
                    left join dc_daily_item_oneday_profit_rate t2 on t1.item_id=t2.item_id and t1.day=t2.day
                     where t1.day='{day.ToString("yyyy-MM-dd")}'";

                if(itemid.Count>0)
                {
                    sql+= $@" and t1.item_id in ('{string.Join("','", itemid)}')";
                }

                return cn.Query<mItemNoProfitRate>(sql).ToList();
            }

        }

        /// <summary>
        /// 获取itemno利润的订单明细
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="itemid"></param>
        /// <param name="day"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<dc_mid_itemno_profit_order> ListItemNoOrder(BtTableParameter parameter, string itemid, DateTime day,ref int total)
        {
            var sql = $@"select * from dc_mid_itemno_profit_order where item_id='{itemid}' and day='{day.ToString("yyyy-MM-dd")}'";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                if(parameter.limit==0)
                {
                    var obj = cn.Page<dc_mid_itemno_profit_order>(parameter.pageIndex, parameter.limit, sql, ref total);

                    return obj.ToList();
                }
                else
                {
                    return cn.Query<dc_mid_itemno_profit_order>(sql,null,null,true,6*60).ToList();
                }
            }

        }

        /// <summary>
        /// 获取itemno利润的订单汇总
        /// </summary>
        /// <param name="itemid"></param>
        /// <param name="day"></param>
        /// <returns></returns>
        public dc_mid_itemno_profit_order ListItemNoOrderCount(string itemid, DateTime day)
        {
            var sql = $@"select sum(amount_sales) as amount_sales,sum(cost_product) cost_product,sum(cost_platform_fee) cost_platform_fee,sum(cost_paypal_fee) cost_paypal_fee,sum(cost_fba_fee) cost_fba_fee,sum(cost_first) cost_first,sum(cost_logistics) cost_logistics,sum(cost_handle_platform) cost_handle_platform,sum(cost_handle_bailun) cost_handle_bailun,sum(losswithdraw) losswithdraw from dc_mid_itemno_profit_order where item_id='{itemid}' and day='{day.ToString("yyyy-MM-dd")}'";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_mid_itemno_profit_order>(sql);

                return obj;
            }

        }

        #endregion




        #region API Service

        /// <summary>
        /// 获取时间段订单的利润
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        public dc_base_oms_order GetProfitTotal(DateTime start,DateTime end)
        {
            var sql = $"select Count(id) id,sum(amount_sales*seller_order_exchange_rate) amount_sales,sum(profit_total) profit_total,sum(profit_total)/sum(amount_sales*seller_order_exchange_rate) as profit_rate from dc_base_oms_order where create_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and create_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}'";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_oms_order>(sql, null, null, 2 * 60);

                return obj;
            }

        }

        /// <summary>
        /// 获取平台itemid的销量
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="start">付款时间时间</param>
        /// <param name="end">付款结束时间</param>
        /// <param name="platform">平台类型</param>
        /// <returns></returns>
        public List<mPlatformItemIdSaleCount> ListPlatformItemIdCount(int page,int pagesize,DateTime start, DateTime end, string platform)
        {
            var sql = $@"select t1.platform_type,t1.item_id,sum(t1.platform_sku_quantity_ordered) platform_sku_quantity_ordered from dc_base_oms_platform_sku t1 where t1.bailun_order_status!='Canceled' and t1.has_cancle=0 and t1.has_delete=0 and t1.has_scalp=0 and ((t1.platform_type!='FBA' and t1.bailun_order_status!='CantHandle') or t1.platform_type='FBA')
                        ";
            if (!string.IsNullOrEmpty(platform))
            {
                if (platform.ToUpper() != "FBA")
                {
                    sql += $" and t1.paid_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.paid_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.platform_type='{platform}'";
                }
                else
                {
                    sql += $" and t1.create_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.create_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.platform_type='{platform}'";
                }
            }

            sql += " group by t1.platform_type,t1.item_id";

            sql += " limit "+(page-1)*pagesize+","+pagesize;

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<mPlatformItemIdSaleCount>(sql, null, null, true,2*60).ToList();

                return obj;
            }
        }

        /// <summary>
        /// 获取时间段内sku的退款数量
        /// </summary>
        /// <param name="sku">sku编码</param>
        /// <param name="start">退款开始时间</param>
        /// <param name="end">退款结束时间</param>
        /// <returns></returns>
        public List<Models.Api.mSkuSaleAndRefund> ListSkuRefund(string sku, DateTime start, DateTime end,string platform)
        {
            var sql = $@"select t1.bailun_sku,sum(t1.bailun_sku_quantity_refund) as refundcount,t1.website,t1.platform_type,t1.bailun_account_id from dc_base_crm_refund t1
                        where t1.refund_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.refund_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}' and t1.is_deleted=0 and t1.is_freeze=0 and t1.company_id=1
                        ";

            if (!string.IsNullOrEmpty(sku))
            {
                sql += " and t1.bailun_sku='"+sku+"'";
            }

            if (!string.IsNullOrEmpty(platform))
            {
                sql += " and t1.platform_type='" + platform+"'";
            }

            sql += " group by t1.platform_type,t1.website,t1.platform_type,t1.bailun_account_id";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Api.mSkuSaleAndRefund>(sql, null, null, true, 2 * 60);

                return obj.ToList();
            }
        }

        #endregion



    }

}

