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

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()
        {
            //查询采购建议明细 
            return RedisHelper.Get(RedisConsts.Lms_GetLogistics, () =>
            {
                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()
        {
            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> 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 api_logistic_query_result_dto.line_dto GetFilterLogisticsAssignLine(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 += $"&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[0];
                }
            }
            catch (Exception ex)
            {
                throw new Exception(" lms 接口异常： " + ex.Message);
                throw new Exception(" lms 接口异常： " + ex.StackTrace);
            }
        }

        /// <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 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>
        /// 抓取财务主体
        /// </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);
            }
        }
    }
}
