using AutoTurnOver.Models;
using AutoTurnOver.Models.ApiDto;
using AutoTurnOver.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.Threading;

namespace AutoTurnOver.DB
{
    public class ApiUtility
    {
        /// <summary>
        /// 批量修改sku默认发货仓
        /// </summary>
        public static void SaveDefaultWares(List<SaveDefaultWaresRequestDto> datas)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("SaveDefaultWares");
                string resultStr = HttpHelper.Request(url, RequestType.POST, datas.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<SaveDefaultWaresResponseDto>();
                if (result == null)
                {
                    throw new Exception("skums 系统异常： 推送失败");
                }
                if (result.statusCode != 200)
                {
                    throw new Exception("skums 系统异常： " + result.message);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("skums 系统异常： " + ex.Message);
            }

            return;
        }

        public static List<LmsShipLogisticsDto> ShipLogisticsList()
        {
            string url = ConfigHelper.GetValue("Lms_GetLogistics");
            string resultStr = HttpHelper.Request(url, RequestType.GET, "", timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<LmsResultDto<List<LmsShipLogisticsDto>>>();
            if (result == null)
            {
                throw new Exception("lms系统异常： 未获取到数据");
            }
            if (!result.Success)
            {
                throw new Exception("lms系统异常： " + result.ErrorMessage);
            }
            return result.Data;
        }

        public static List<LmsShipLogisticsDto> ShipLogisticsListHead()
        {
            string url = ConfigHelper.GetValue("Lms_GetLogistics");
            string resultStr = HttpHelper.Request(url + "?startPoint=3", RequestType.GET, "", timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<LmsResultDto<List<LmsShipLogisticsDto>>>();
            if (result == null)
            {
                throw new Exception("lms系统异常： 未获取到数据");
            }
            if (!result.Success)
            {
                throw new Exception("lms系统异常： " + result.ErrorMessage);
            }
            return result.Data;

            ////查询采购建议明细 
            //return RedisHelper.Get(RedisConsts.Lms_GetLogisticsHead, () =>
            //{

            //});
        }

        public static List<LmsShipLogisticsDto> RealTimeShipLogisticsList(LmsShipLogisticsRequstDto requstData = null)
        {
            string url = ConfigHelper.GetValue("Lms_GetLogistics");
            var parameters = $"";
            if (requstData != null)
            {
                parameters = $"?has_history_order={requstData.has_history_order}&transport_type={requstData.transport_type}&RecordStatus={requstData.RecordStatus}&startPoint={requstData.startPoint}&platform={requstData.platform}&Line_Code={requstData.Line_Code}&country_code={requstData.country_code}&endCountries={requstData.endCountries}&character_skus={requstData.character_skus}&has_min_freight_unit_price={requstData.has_min_freight_unit_price}";
            }
            string resultStr = HttpHelper.Request(url + parameters, RequestType.GET, "", timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<LmsResultDto<List<LmsShipLogisticsDto>>>();
            if (result == null)
            {
                throw new Exception("lms系统异常： 未获取到数据");
            }
            if (!result.Success)
            {
                throw new Exception("lms系统异常： " + result.ErrorMessage);
            }
            return result.Data;
        }
        public static List<LmsShipLogisticsDto> RealTimeShipLogisticsCompanyList()
        {
            return RealTimeShipLogisticsList().GroupBy(s => new { s.Company_Code }).Select(s => new LmsShipLogisticsDto { Company_Code = s.Key.Company_Code, Company_Name = s.Max(v => v.Company_Name) }).ToList();
        }

        /// <summary>
        /// 抓取sku 刊登状态
        /// </summary>
        /// <returns></returns>
        public static List<api_pps_sku_status_response_dto.sku_dto> GetPPSSkuStatus(api_pps_sku_status_request_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("PPSSkuStatus");
                string resultStr = HttpHelper.Request(url, RequestType.POST, data.sku.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_pps_sku_status_response_dto>();
                if (result == null)
                {
                    return new List<api_pps_sku_status_response_dto.sku_dto>() { };
                }
                else
                {
                    return result.result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("pps sku 刊登状态接口异常： " + ex.Message);
                throw new Exception("pps sku 刊登状态接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 获取平台费率
        /// </summary>
        /// <returns></returns>
        public static api_platform_fee_result_dto.result_dto GetPlatformFee(api_platform_fee_input_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("PostPlatCategoryRate");
                string resultStr = HttpHelper.Request(url, RequestType.POST, data.datas.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_platform_fee_result_dto>();
                if (result == null)
                {
                    return new api_platform_fee_result_dto.result_dto() { };
                }
                else
                {
                    return result.result[0];
                }
            }
            catch (Exception ex)
            {
                return new api_platform_fee_result_dto.result_dto() { };
                //throw new Exception("平台费 接口异常： " + ex.Message);
                //throw new Exception("平台费 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 获取平台分类
        /// </summary>
        /// <returns></returns>
        public static List<api_plat_category_dto> GetPlatformCategory(api_platform_category_input_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("api_plat_category");
                string resultStr = HttpHelper.Request(url + $"?plat={data.plat}&site={data.site}", RequestType.GET, timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_platform_category_result_dto>();
                if (result == null)
                {
                    return new List<api_plat_category_dto>() { };
                }
                else
                {
                    return result.result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("平台分类 接口异常： " + ex.Message);
                throw new Exception("平台分类 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 获取预估物流费用
        /// </summary>
        /// <returns></returns>
        public static List<api_logistic_query_result_dto.line_dto> GetFilterLogisticsAssignLineList(api_logistic_query_input_dto data)
        {
            try
            {
                var parameter_str = $"?LineCodes={data.LineCodes}";
                parameter_str += $"&endCountries={data.endCountries}";
                parameter_str += $"&Long={data.Long}";
                parameter_str += $"&skus={data.skus}";
                parameter_str += $"&lms_character_skus={data.lms_character_skus}";
                parameter_str += $"&width={data.width}";
                parameter_str += $"&high={data.high}";
                parameter_str += $"&weightKg={data.weightKg}";
                parameter_str += $"&startPoint={data.startPoint}";
                //parameter_str += $"&warehouseNo={data.warehouseNo}";
                //parameter_str += $"orderPriceCNY={data.orderPriceCNY}";
                parameter_str += $"&platform={data.platform}";
                parameter_str += $"&Site={data.Site}";

                //查询采购建议明细 
                string url = ConfigHelper.GetValue("ApiLogisticsGetFilterLogisticsAssignLine");
                string resultStr = HttpHelper.Request(url + parameter_str, RequestType.GET, timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_logistic_query_result_dto>();
                if (result == null || result.Data == null || result.Data.successLines == null || result.Data.successLines.Count <= 0)
                {
                    throw new Exception("未查询到物流费用");
                }
                else
                {
                    return result.Data.successLines;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(" lms 接口异常： " + ex.Message);
                throw new Exception(" lms 接口异常： " + ex.StackTrace);
            }
        }
        /// <summary>
        /// 获取预估物流费用
        /// </summary>
        /// <returns></returns>
        public static api_logistic_query_result_dto.line_dto GetFilterLogisticsAssignLine(api_logistic_query_input_dto data)
        {
            return GetFilterLogisticsAssignLineList(data)[0];
        }

        /// <summary>
        /// 获取调拨单真实费用
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static List<api_transfer_cost_real_dto.data_dto.items_dto> GetTransferCost(api_transfer_cost_real_input_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("transfer_cost_real");
                string resultStr = HttpHelper.Request(url, RequestType.POST, data.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_transfer_cost_real_dto>();
                if (result == null)
                {
                    throw new Exception("未获取响应数据");
                }
                else
                {
                    if (!result.isSuccess)
                    {
                        throw new Exception(result.message);
                    }
                    return result.data.items;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("调拨费用同步接口 异常： " + ex.Message);
                throw new Exception("调拨费用同步接口 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 抓取供应商放假时间
        /// </summary>
        /// <returns></returns>
        public static List<SupplierHolidayTimeDtoOutPut> getSupplierHolidayTimes()
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("distribution_sys:getSupplierHolidayTimes");
                string resultStr = HttpHelper.Request(url, RequestType.GET);
                var result = resultStr.ToObj<api_SupplierHolidayTimeDtoOutPut>();
                if (result == null)
                {
                    return new List<SupplierHolidayTimeDtoOutPut>();
                }
                else
                {
                    return result.result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("pps 供应商节假日接口异常： " + ex.Message);
                throw new Exception("pps 供应商节假日接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 抓取供应商列表
        /// </summary>
        /// <returns></returns>
        public static List<api_supplier_dto.data_dto> getSupplierList(int page, DateTime start, DateTime end)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("supplier_sys:list");
                string resultStr = HttpHelper.Request(url + $"?page={page}&start={start}&end={end}", RequestType.POST);
                var result = resultStr.ToObj<api_supplier_dto>();
                if (result == null)
                {
                    return new List<api_supplier_dto.data_dto>();
                }
                else
                {
                    return result.data;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("供应商 list 接口异常： " + ex.Message);
                throw new Exception("供应商 list 接口异常： " + ex.StackTrace);
            }
        }
        /// <summary>
        /// 抓取物流商列表
        /// </summary>
        /// <returns></returns>
        public static List<dc_base_lms_channel> getChannelList()
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("lms-sys:channel");
                string resultStr = HttpHelper.Request(url, RequestType.GET, timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_channel_dto>();
                if (result == null)
                {
                    return new List<dc_base_lms_channel>();
                }
                else
                {
                    return result.data;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("lms list 接口异常： " + ex.Message);
                throw new Exception("lms list 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 提货单推送无库系统
        /// </summary>
        /// <returns></returns>
        public static void ApiPushSupplierUpSkuInfo(List<api_push_SupplierAimsUpSkuInfoDto> datas)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("distribution_sys:InsertAimsUpSkuInfo");
                string resultStr = HttpHelper.Request(url, RequestType.POST, datas.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_distribution_return_order_push_response_dto>();
                if (result == null)
                {
                    throw new Exception("无库系统接口未响应");
                }
                else
                {
                    if (result.statusCode != 200)
                    {
                        throw new Exception(result.message);
                    }
                    else
                    {
                        if (result.result == null)
                        {
                            throw new Exception("无库系统接口未响应");
                        }
                        else
                        {
                            if (!result.result.isSucceeded)
                            {
                                throw new Exception(result.result.message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("无库系统 退货单推送接口异常： " + ex.Message);
                throw new Exception("无库系统 退货单推送接口异常： " + ex.StackTrace);
            }
        }
        /// <summary>
        /// 退货单推送无库系统
        /// </summary>
        /// <returns></returns>
        public static void PushSupplierReturnSkuInfo(List<api_distribution_return_order_push_input_dto> datas)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("SupplierReturnSkuInfo");
                string resultStr = HttpHelper.Request(url, RequestType.POST, datas.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_distribution_return_order_push_response_dto>();
                if (result == null)
                {
                    throw new Exception("无库系统接口未响应");
                }
                else
                {
                    if (result.statusCode != 200)
                    {
                        throw new Exception(result.message);
                    }
                    else
                    {
                        if (result.result == null)
                        {
                            throw new Exception("无库系统接口未响应");
                        }
                        else
                        {
                            if (!result.result.isSucceeded)
                            {
                                throw new Exception(result.result.message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("无库系统 退货单推送接口异常： " + ex.Message);
                throw new Exception("无库系统 退货单推送接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 退货单推送Oms系统
        /// </summary>
        /// <returns></returns>
        public static void PushOmsReturnSkuInfo(List<api_oms_return_order_push_input_dto> datas)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("OmsReturnSkuInfo");
                string resultStr = HttpHelper.Request(url, RequestType.POST, datas.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_oms_return_order_push_response_dto>();
                if (result == null)
                {
                    throw new Exception("Oms系统接口未响应");
                }
                else
                {
                    if (!result.success)
                    {
                        throw new Exception(result.error);
                    }
                    else
                    {
                        if (result.result == null)
                        {
                            throw new Exception("Oms系统接口未响应");
                        }
                        else
                        {

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Oms系统 退货单推送接口异常： " + ex.Message);
                throw new Exception("Oms系统 退货单推送接口异常： " + ex.StackTrace);
            }
        }



        /// <summary>
        /// 获取lms 的调拨单时效
        /// </summary>
        /// <returns></returns>
        public static List<api_lms_order_transfer_sku_dto> GetLmsOrderTransfer(api_lms_order_transfer_sku_requst_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("api_lms_order_transfer_sku");
                string resultStr = HttpHelper.Request(url, RequestType.POST, data.ToJson(), entype: "application/json; charset=utf-8", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<List<api_lms_order_transfer_sku_dto>>();
                if (result == null)
                {
                    return new List<api_lms_order_transfer_sku_dto>() { };
                }
                else
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                return new List<api_lms_order_transfer_sku_dto>();
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.Message);
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.StackTrace);
            }
        }
        /// <summary>
        /// 获取lms 的调拨单时效
        /// </summary>
        /// <returns></returns>
        public static List<api_avg_order_transfer_dto> GetLmsAvgOrderTransferList(api_lms_order_transfer_sku_requst_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("api_lms_avg_order_transfer_list");
                string resultStr = HttpHelper.Request(url, RequestType.POST, data.ToJson(), entype: "application/json; charset=utf-8", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<List<api_avg_order_transfer_dto>>();
                if (result == null)
                {
                    return new List<api_avg_order_transfer_dto>() { };
                }
                else
                {
                    // 2018 年后的单 &  海运单运输时效不能低于32天
                    return result.Where(s=>s.bale_time.Year>=2018).Where(s=> s.transport_type!="海运" || s.calculation_sign_days>32).ToList();
                }
            }
            catch (Exception ex)
            {
                return new List<api_avg_order_transfer_dto>();
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.Message);
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.StackTrace);
            }
        }
        /// <summary>
        /// 获取lms 的运输类型评价时效
        /// </summary>
        /// <returns></returns>
        public static List<api_transport_count_order_transfer_dto> GetLmsTransportCountList(api_transport_count_order_transfer_query_dto data)
        {
            var _connection = MyMySqlConnection._connection_read_only;
            List<api_transport_count_order_transfer_dto> datas = new List<api_transport_count_order_transfer_dto>() { new api_transport_count_order_transfer_dto { } };
            List<temp_dc_base_trans_expectarrivaltime_temp> transDatas = new List<temp_dc_base_trans_expectarrivaltime_temp>();

            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("bailun_sku", data.bailun_sku);
            parameters.Add("warehouse_code", data.targetwareno);

            // 查询真实的调拨在途
            var orders = _connection.Query<temp_dc_base_trans_expectarrivaltime_temp>(@"select 
ifnull(t2.`code`,'') as 'main_code',
ifnull(t8.expectarrivaltime,t2.expectarrivaltime) as 'expectarrivaltime',
t1.sku as 'bailun_sku',
t2.targetwareno as 'warehouse_code',
t1.deliverycount - t1.storagecount as 'count',
ifnull(t2.`code`,'') as 'transfer_order_id',
ifnull(t2.purchasecode,'') as 'purchase_id',
(case when t9.transport_type is null or t9.transport_type not in (1,2,3) then t2.transporttype when t9.transport_type=1 then '铁路运输' when t9.transport_type=2 then '海运' when t9.transport_type=3 then '空运' when t2.transporttype in ('铁路运输','海运','空运')  then t2.transporttype else '未知' end   ) as 'transport_type_str'
from dc_base_transfer_info_skus as t1 
left join dc_base_transfer_info as t2 on t1.dataid =t2.dataid
left join dc_base_warehouse as t3 on t2.targetwareno = t3.warehouse_code
left join ( select data_id,sku,expectarrivaltime from  dc_lms_order_transfer_current_node GROUP BY data_id,sku ) as t8 on t2.dataid = t8.data_id and t1.sku = t8.sku
left join dc_base_lms_channel as t9 on t2.channelname = t9.`name`
where t2.isdeleted=0 and t2.stateid not in (5,11,12) 
and t1.deliverycount > t1.storagecount
and t2.isexception = 0
and t3.hq_type in ('fba仓','第三方仓库') and t2.expectarrivaltime >='1991-01-01' and t1.sku=@bailun_sku and t2.targetwareno=@warehouse_code ", parameters).ToList();
            if (orders != null && orders.Count >= 1)
            {
                transDatas.AddRange(orders);
            }
            // 计算调拨临时数据
            var temp_orders = _connection.Query<temp_dc_base_trans_expectarrivaltime_temp>(@"select 
t1.code as 'main_code',
t1.purchase_code as 'purchase_id', 
t1.sku as 'bailun_sku',
t1.target_ware_no as 'warehouse_code' ,
(case when t1.create_state=0 then  t1.product_num else t1.temp_delivery_count end) as 'count',
'' as 'transfer_order_id',
'1991-01-01' as 'expectarrivaltime',
t1.transport_type_str
from dc_base_trans_temp_schedule as t1 
left join dc_base_warehouse as t2 on t1.target_ware_no = t2.warehouse_code
where  t1.is_delete=0 and t1.is_temp_data=1 and t1.is_exception=0 and t2.hq_type in ('fba仓') and t1.create_state in (0,1)
and t1.sku=@bailun_sku and t1.target_ware_no=@warehouse_code
", parameters).ToList();
            if (temp_orders != null && temp_orders.Count >= 1)
            {
                transDatas.AddRange(temp_orders);
            }
            // 查询计划单
            var plan_orders = _connection.Query<temp_dc_base_trans_expectarrivaltime_temp>(@"select 
t1.transfer_plan_order_id as 'main_code',
'' as 'purchase_id',
t1.bailun_sku as 'bailun_sku',
t1.warehouse_code as 'warehouse_code',
t1.count as 'count',
'' as 'transfer_order_id',
'1991-01-01' as 'expectarrivaltime',
t1.transport_type as 'transport_type_str'
from dc_base_transfer_plan as t1
left join dc_base_warehouse as t2 on t1.warehouse_code = t2.warehouse_code
where  t1.`status`=1 and t2.hq_type not IN ('国内仓','fba仓') and t1.deleted=0
and t1.bailun_sku=@bailun_sku and t1.warehouse_code=@warehouse_code
", parameters).ToList();
            if (plan_orders != null && plan_orders.Count >= 1)
            {
                transDatas.AddRange(plan_orders);
            }

            transDatas = transDatas.Where(s => s.count > 0).ToList();
            datas[0].order_count = transDatas.Select(s => s.main_code).Distinct().Count();
            datas[0].product_count = transDatas.Sum(s => s.count);
            datas[0].order_count_1 = transDatas.Where(s => s.transport_type_str == "铁路运输").Select(s => s.main_code).Distinct().Count();
            datas[0].product_count_1 = transDatas.Where(s => s.transport_type_str == "铁路运输").Sum(s => s.count);
            datas[0].order_count_2 = transDatas.Where(s => s.transport_type_str == "海运").Select(s => s.main_code).Distinct().Count();
            datas[0].product_count_2 = transDatas.Where(s => s.transport_type_str == "海运").Sum(s => s.count);
            datas[0].order_count_3 = transDatas.Where(s => s.transport_type_str == "空运").Select(s => s.main_code).Distinct().Count();
            datas[0].product_count_3 = transDatas.Where(s => s.transport_type_str == "空运").Sum(s => s.count);

            // 在库库存分析
            var stock = _connection.QueryFirstOrDefault<int?>(" select usable_stock from dc_base_stock as t1 where t1.bailun_sku=@bailun_sku and t1.warehouse_code=@warehouse_code  ", parameters)??0;
            if (stock > 0)
            {
                var logs = _connection.Query<order_transfer_status_log>(" select * from order_transfer_status_log as t1 where  t1.bailun_sku=@bailun_sku and t1.warehouse_code=@warehouse_code and is_delete=0 ", parameters).ToList();
                if (logs != null && logs.Count >= 1)
                {
                    // 按实际排降序取够库存
                    var stock_orders = new List<temp_dc_base_trans_expectarrivaltime_temp>();
                    foreach (var item in logs.OrderByDescending(s => s.date))
                    {
                        
                        if (stock > 0)
                        {
                            var use_stock = stock > item.count ? item.count : stock;
                            if (use_stock > 0)
                            {
                                stock -= use_stock;
                                // 查询相关调拨单
                                var transport_type_str = _connection.QueryFirstOrDefault<string>(@"select
(case when t9.transport_type=1 then '铁路运输' when t9.transport_type=2 then '海运' when t9.transport_type=3 then '空运' when t1.transporttype in ('铁路运输','海运','空运')  then t1.transporttype else '未知' end  ) as 'transport_type_str'
from dc_base_transfer_info as t1
left join dc_base_lms_channel as t9 on t1.channelname = t9.`name`
where t1.`code`=@code limit 1
", new { code  = item.system_order_no});
                                stock_orders.Add(new temp_dc_base_trans_expectarrivaltime_temp { count = use_stock , main_code  = item.system_order_no,transport_type_str = transport_type_str });
                            }
                           
                        }
                       
                    }

                    stock_orders = stock_orders.Where(s => s.count > 0).ToList();
                    datas[0].order_count += stock_orders.Select(s => s.main_code).Distinct().Count();
                    datas[0].product_count += stock_orders.Sum(s => s.count);
                    datas[0].order_count_1 += stock_orders.Where(s => s.transport_type_str == "铁路运输").Select(s => s.main_code).Distinct().Count();
                    datas[0].product_count_1 += stock_orders.Where(s => s.transport_type_str == "铁路运输").Sum(s => s.count);
                    datas[0].order_count_2 += stock_orders.Where(s => s.transport_type_str == "海运").Select(s => s.main_code).Distinct().Count();
                    datas[0].product_count_2 += stock_orders.Where(s => s.transport_type_str == "海运").Sum(s => s.count);
                    datas[0].order_count_3 += stock_orders.Where(s => s.transport_type_str == "空运").Select(s => s.main_code).Distinct().Count();
                    datas[0].product_count_3 += stock_orders.Where(s => s.transport_type_str == "空运").Sum(s => s.count);
                }
            }
            

            return datas;
        }
        /// <summary>
        /// 获取lms 的调拨单时效
        /// </summary>
        /// <returns></returns>
        public static List<api_avg_days_dto> GetLmsOrderTransferAvg(api_lms_order_transfer_sku_requst_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("api_lms_order_transfer_sku_avg");
                string resultStr = HttpHelper.Request(url, RequestType.POST, data.ToJson(), entype: "application/json; charset=utf-8", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<List<api_avg_days_dto>>();
                if (result == null)
                {
                    return new List<api_avg_days_dto>() { };
                }
                else
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                return new List<api_avg_days_dto>();
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.Message);
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 抓取财务主体
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static List<api_finance_body_dto.data_dto> GetFinanceBody()
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("api_finance_body");
                string resultStr = HttpHelper.Request(url, RequestType.POST, new { modify_time_start = new DateTime(2001, 1, 1), modify_time_end = DateTime.Now.AddDays(1) }.ToJson(), entype: "application/json; charset=utf-8", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_finance_body_dto>();
                if (result == null)
                {
                    throw new Exception("付款主体抓取异常");
                }
                else if (result.Success == false)
                {
                    throw new Exception("付款主体抓取异常:" + result.Message);
                }
                else
                {
                    return result.Data;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("财务系统 付款主体抓取异常 接口异常： " + ex.Message);
                throw new Exception("财务系统 付款主体抓取异常 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 获取调拨单临时数据
        /// </summary>
        /// <returns></returns>
        public static List<api_temp_schedule_response_dto.item_dto> GetTransOrderTempSchedule(DateTime btime, DateTime etime, int page)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("api_trans_temp_schedule");
                string resultStr = HttpHelper.Request(url, RequestType.POST, new
                {
                    Data = new
                    {
                        Code = "",
                        StartTime = btime.ToString("yyyy-MM-dd HH:mm:ss"),
                        EndTime = etime.ToString("yyyy-MM-dd HH:mm:ss"),
                        Page = new
                        {
                            page = page,
                            rows = 100
                        }
                    }
                }.ToJson(), entype: "application/json; charset=utf-8", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_temp_schedule_response_dto>();
                if (result == null)
                {
                    return new List<api_temp_schedule_response_dto.item_dto> { };
                }
                else
                {
                    return result.data.items;
                }
            }
            catch (Exception ex)
            {
                return new List<api_temp_schedule_response_dto.item_dto>();
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.Message);
                //throw new Exception("lms 调拨单时效 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 查询review
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static List<api_pps_review_response_dto.result_dto.data_dto> GetReview(api_pps_review_request_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("pps-sys:review");
                string resultStr = HttpHelper.Request(url, RequestType.POST, data.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_pps_review_response_dto>();
                if (result == null)
                {
                    return new List<api_pps_review_response_dto.result_dto.data_dto>();
                }
                else
                {
                    return result.result.reviewList;
                }
            }
            catch (Exception ex)
            {
                return new List<api_pps_review_response_dto.result_dto.data_dto>();
                //throw new Exception("平台费 接口异常： " + ex.Message);
                //throw new Exception("平台费 接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 抓取生产系统订单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static List<api_prod_order_response_dto.data_dto> GetProdOrder(api_prod_order_request_dto data)
        {
            try
            {
                //查询采购建议明细 
                string url = ConfigHelper.GetValue("prod-sys:order");
                string resultStr = HttpHelper.Request(url + $"?page={data.page}&rows={data.rows}&btime={data.btime}&etime={data.etime}", RequestType.GET, "application/json", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_prod_order_response_dto>();
                if (result == null)
                {
                    return new List<api_prod_order_response_dto.data_dto>() { };
                }
                else
                {
                    return result.data;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("生产系统接口异常： " + ex.Message);
                throw new Exception("生产系统接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 抓取生产系统订单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static List<api_order_transfer_current_node_dto.data_dto> GetLmsTransferOrderNode(int page, int rows, DateTime btime, DateTime etime)
        {
            try
            {
                string url = ConfigHelper.GetValue("lms-sys:transfer-node");
                string resultStr = HttpHelper.Request(url + $"?page={page}&rows={rows}&btime={btime}&etime={etime}", RequestType.GET, timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<api_order_transfer_current_node_dto>();
                if (result == null)
                {
                    return new List<api_order_transfer_current_node_dto.data_dto>() { };
                }
                else
                {
                    return result.data;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("lms系统接口异常： " + ex.Message);
                throw new Exception("lms系统接口异常： " + ex.StackTrace);
            }
        }

        /// <summary>
        /// 抓取百伦的调拨日志数据
        /// </summary>
        /// <returns></returns>
        public static List<api_order_transfer_status_log_dto.data_dto> GetOrderBailunTransferLog(DateTime btime, int type = 5)
        {
            var url = ConfigHelper.GetValue("Order:Bailun_TransferLog");
            var response_json = HttpHelper.Request(url, RequestType.POST, new
            {
                CreationTime = btime,
                State = type
            }.ToJson(), "application/json", timeout: 1000 * 60 * 60 * 24);
            return response_json.ToObj<api_order_transfer_status_log_dto>().data;
        }

        /// <summary>
        /// 查询pps的跟卖sku
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public static List<api_dc_base_pps_sell_product_dto.data_dto> GetPPSSellProduct(int page,int rows)
        {
            var url = ConfigHelper.GetValue("pps-sys:pps_sell_product");
            var response_json = HttpHelper.Request(url+ $"?PageIndex={page}&PageNumber={rows}", RequestType.POST, "", timeout: 1000 * 60 * 60 * 24);
            var datas = response_json.ToObj<api_dc_base_pps_sell_product_dto>().data;

            return datas;
        }


        public static List<api_bailun_sku_character_response_dto.data_dto> GetSkuCharacterBailun(List<string> skus, int count = 0)
        {
            try
            {
                var url = ConfigHelper.GetValue("Sku:character");
                var response_json = HttpHelper.Request(url, RequestType.POST, skus.ToJson(), entype: "application/json", timeout: 1000 * 60 * 30);
                return response_json.ToObj<api_bailun_sku_character_response_dto>().result;
            }
            catch (Exception ex)
            {
                if (count <= 20)
                {
                    Thread.Sleep(10 * 1000);
                    count++;
                    return GetSkuCharacterBailun(skus, count);
                }
                throw new Exception($" 抓取 sku 数据异常：重试次数{count} 参数【{skus.ToJson()}】,message: 【{ex.Message}】,【{ex.StackTrace}】 ");
            }
        }


        /// <summary>
        /// 抓取所有产品特性
        /// </summary>
        /// <returns></returns>
        public static List<api_bailun_character_response_dto.data_dto> GetCharacterBailun()
        {
            var url = ConfigHelper.GetValue("Sku:character_list");
            var response_json = HttpHelper.Request(url, RequestType.GET, timeout: 1000 * 60 * 30);
            return response_json.ToObj<api_bailun_character_response_dto>().result;
        }

        /// <summary>
        /// 获取pds销量
        /// </summary>
        /// <param name="skus"></param>
        /// <returns></returns>
        public static List<PdsProviderProductSalesDto> GetPdsProviderProductSales(List<string> skus)
        {
            try
            {
                var url = ConfigHelper.GetValue("PdsProductsales");
                var response_json = HttpHelper.Request(url, RequestType.POST, skus.ToJson(), entype: "application/json", timeout: 1000 * 60 * 30);
                return response_json.ToObj<List<PdsProviderProductSalesDto>>();
            }
            catch (Exception)
            {
                return new List<PdsProviderProductSalesDto>();
            }
        }
    }
}
