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

namespace AutoTurnOver.Services
{
    public class ApiServices
    {
        /// <summary>
        /// 获取一二级的百伦分类数据
        /// </summary>
        /// <returns></returns>
        public static List<CategoryDto> GetCategoryAll()
        {
            List<CategoryDto> clsit = new List<CategoryDto>();
            clsit.AddRange(GetCategoryList(1));
            clsit.AddRange(GetCategoryList(2));
            return clsit;
        }

        public static List<CategoryDto> GetCategoryList(int level = 1)
        {
            if (level == 0)
            {
                List<CategoryDto> datas = new List<CategoryDto>();
                var tempLevel = 1;
                while (true)
                {
                    var tempDatas = GetCategoryList(tempLevel);
                    if (tempDatas != null && tempDatas.Count >= 1 && level <= 4)
                    {
                        datas.AddRange(tempDatas);
                    }
                    else
                    {
                        return datas;
                    }
                    tempLevel++;

                }
            }
            string appId = "SystemAims";
            string appKey = "YmFpbHVuQWltcw==";
            string url = "http://api.sku.bailuntec.com/api/BailunCateData/GetAllCategoryList";

            List<CategoryDto> result = new List<CategoryDto>();

            ApiEntrance model = new ApiEntrance();
            model.code = appId;
            model.data = level.ToString();

            string sign = Security.md5Encrypt(appKey + model.code + Security.md5Encrypt(model.key + model.data));
            string resultStr = HttpHelper.Request(url + $"?sign={sign}&appId={appId}&level={level}", RequestType.GET);
            ApiResult apiResult = resultStr.ToObj<ApiResult>();
            if (apiResult.result_code == 1)
            {
                result = WebUtility.UrlDecode(apiResult.data).ToObj<List<CategoryDto>>().Where(s => s.C_LEVEL == level).ToList();
            }
            return result;

        }

        /// <summary>
        /// 根据ID查询分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static CategoryDto GetCategoryById(int id)
        {
            var all = GetCategoryAll();
            return all.SingleOrDefault(s => s.C_ID == id);
        }

        /// <summary>
        /// 查询相关的子节点
        /// </summary>
        /// <param name="all"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static List<CategoryDto> GetClientNodesByIds(List<int> ids)
        {
            if (ids == null || ids.Count <= 0)
            {
                return new List<CategoryDto>();
            }
            List<CategoryDto> datas = new List<CategoryDto>();
            var all = GetCategoryList(0);
            foreach (var item in ids)
            {
                datas.AddRange(GetClientNodesById(all, item));
            }
            return datas;
        }

        /// <summary>
        /// 查询相关的子节点
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static List<CategoryDto> GetClientNodesById(List<CategoryDto> all, int id)
        {

            // 查询所有数据
            if (all == null)
            {
                all = GetCategoryList(0);
            }
            List<CategoryDto> clients = all.Where(s => s.C_ID == id).ToList();
            var cNodes = all.Where(s => s.C_PARENTID == id).ToList();
            if (cNodes != null || cNodes.Count >= 1)
            {
                foreach (var item in cNodes)
                {
                    clients.AddRange(GetClientNodesById(all, item.C_ID));
                }
            }
            return clients;


        }

        /// <summary>
        /// 推送采购计划
        /// </summary>
        public static BuyOutputResult PushBuyPlan(mPlanToPurchaseDto data)
        {
            //查询采购建议明细 
            string url = ConfigHelper.GetValue("PushBuyPlan");
            string resultStr = HttpHelper.Request(url, RequestType.POST, "obj=" + WebUtility.UrlDecode(data.ToJson()), timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<BuyOutputResult>();
            if (result == null)
            {
                throw new Exception("采购系统异常： 推送失败");
            }
            if (!result.IsSuccessed)
            {
                throw new Exception("采购系统异常： " + result.Message);
            }
            return result;
        }

        /// <summary>
        /// 账号列表
        /// </summary>
        public static List<AccountDto> AccountList()
        {
            //查询采购建议明细 
            return RedisHelper.Get(RedisConsts.Pams_GetAccountToken, () =>
            {
                string url = ConfigHelper.GetValue("Pams_GetAccountToken");
                string resultStr = HttpHelper.Request(url, RequestType.GET, "", timeout: 1000 * 60 * 60 * 24);
                var result = resultStr.ToObj<PamsResultDto<List<AccountDto>>>();
                if (result == null)
                {
                    throw new Exception("账号系统异常： 未获取到数据");
                }
                if (!result.Success)
                {
                    throw new Exception("账号系统异常： " + result.Message);
                }
                return result.Data;
            });
        }

        public static List<AccountDto> AccountList(string name)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(name)) return AccountList();
                return AccountList().Where(s =>
                   (s.OmsAccount ?? "").Contains(name, StringComparison.OrdinalIgnoreCase)
                    ||
                     (s.EmailAccount ?? "").Contains(name, StringComparison.OrdinalIgnoreCase)
                     ||
                      (s.Account ?? "").Contains(name, StringComparison.OrdinalIgnoreCase)
                ).ToList();
            }
            catch (Exception ex)
            {
                report.AddError(new dc_task_error_log
                {
                    date = DateTime.Now,
                    message = ex.Message,
                    stack_trace = ex.StackTrace,
                    task_name = "account_api"
                });
                throw;
            }
           
            
            
        }


        /// <summary>
        /// 查询crm case 数据
        /// </summary>
        public static List<crm_case_order_dto> CrmCaseOrder(List<string> order_no_list)
        {
            if (order_no_list == null || order_no_list.Count <= 0)
            {
                return new List<crm_case_order_dto>();
            }

            string url = ConfigHelper.GetValue("Crm_Case_Order");
            string resultStr = HttpHelper.Request(url, RequestType.POST, "order_no_list=" + string.Join(",", order_no_list), timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<crm_api_result_dto<List<crm_case_order_dto>>>();
            if (result == null)
            {
                throw new Exception("crm系统： 获取case 数据失败");
            }
            if (!result.success)
            {
                throw new Exception("crm系统： " + result.message);
            }
            return result.data;
        }

        public static List<crm_message_dto> CrmMessage(List<string> order_no_list)
        {
            if (order_no_list == null || order_no_list.Count <= 0)
            {
                return new List<crm_message_dto>();
            }

            string url = ConfigHelper.GetValue("Crm_Message");
            string resultStr = HttpHelper.Request(url, RequestType.POST, "order_no_list=" + string.Join(",", order_no_list), timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<crm_api_result_dto<List<crm_message_dto>>>();
            if (result == null)
            {
                throw new Exception("crm系统： 获取客户来信 数据失败");
            }
            if (!result.success)
            {
                throw new Exception("crm系统： " + result.message);
            }
            return result.data;
        }

        public static List<crm_message_reply_dto> CrmMessageReply(List<string> order_no_list)
        {
            if (order_no_list == null || order_no_list.Count <= 0)
            {
                return new List<crm_message_reply_dto>();
            }

            string url = ConfigHelper.GetValue("Crm_Message_Reply");
            string resultStr = HttpHelper.Request(url, RequestType.POST, "order_no_list=" + string.Join(",", order_no_list), timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<crm_api_result_dto<List<crm_message_reply_dto>>>();
            if (result == null)
            {
                throw new Exception("crm系统： 获取出信数据失败");
            }
            if (!result.success)
            {
                throw new Exception("crm系统： " + result.message);
            }
            return result.data;
        }

        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> ShipLogisticsList(string name)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(name)) return ShipLogisticsList();
                return ShipLogisticsList().Where(s =>
                   (s.Line_Code ?? "").Contains(name, StringComparison.OrdinalIgnoreCase)
                    ||
                   (s.Line_Name ?? "").Contains(name, StringComparison.OrdinalIgnoreCase)
                ).ToList();
            }
            catch (Exception ex)
            {
                report.AddError(new dc_task_error_log
                {
                    date = DateTime.Now,
                    message = ex.Message,
                    stack_trace = ex.StackTrace,
                    task_name = "ahipLogistics_api"
                });
                throw;
            }



        }

        /// <summary>
        /// 平台列表
        /// </summary>
        public static List<PlatformDto> PlatformList()
        {
            string url = ConfigHelper.GetValue("Pams_PlatformList");
            string resultStr = HttpHelper.Request(url, RequestType.GET, "", timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<PamsResultDto<List<PlatformDto>>>();
            if (result == null)
            {
                throw new Exception("账号系统异常： 未获取到平台数据");
            }
            if (!result.Success)
            {
                throw new Exception("账号系统异常： " + result.Message);
            }
            return result.Data;
        }

        /// <summary>
        /// 查询出信模板
        /// </summary>
        /// <param name="order_no_list"></param>
        /// <returns></returns>
        public static List<crm_message_custom_template_dto> MessageCustomTemplateList()
        {
            
            string url = ConfigHelper.GetValue("Crm_Message_Custom_Template");
            string resultStr = HttpHelper.Request(url, RequestType.POST, "", timeout: 1000 * 60 * 60 * 24);
            var result = resultStr.ToObj<crm_api_result_dto<List<crm_message_custom_template_dto>>>();
            if (result == null)
            {
                throw new Exception("crm系统： 获取case 数据失败");
            }
            if (!result.success)
            {
                throw new Exception("crm系统： " + result.message);
            }
            return result.data;
        }

        /// <summary>
        /// 出信
        /// </summary>
        public static void SendMessage(ApiSendMessageInputDto data)
        {
            //查询采购建议明细 
            string url = ConfigHelper.GetValue("CRM_SendMessage");
            string resultStr = HttpHelper.Request(url, RequestType.POST, data.ToJson(), timeout: 1000 * 60 * 60 * 24,entype:"application/json");
            var result = resultStr.ToObj<crm_api_result_null_dto>();
            if (result == null)
            {
                throw new Exception("CRM系统异常： 推送失败");
            }
            if (!result.success)
            {
                throw new Exception("crm系统异常： " + result.message);
            }
            return;
        }

    }
}
