using Fw.Utility.UnifyResponse;
using Hotline.Caching.Interfaces;
using Hotline.Orders;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Tools;
using Hotline.Snapshot;
using Hotline.Snapshot.IRepository;
using Hotline.Tools;
using Mapster;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Renci.SshNet;
using System.Net.Http.Headers;
using System.Text;
using TianQue.Sdk.Models;
using XF.Domain.Dependency;
using FileInfo = TianQue.Sdk.Models.FileInfo;

namespace TianQue.Sdk;

public class TiqnQueService : IGuiderSystemService, IScopeDependency
{
    private readonly ILogger<TQHttpClient> _logger;
    private readonly ISystemSettingCacheManager _sysSetting;
    private readonly IHttpClientFactory _httpClientFactory;

    public TiqnQueService(ILogger<TQHttpClient> logger, ISystemSettingCacheManager sysSetting, IHttpClientFactory httpClientFactory)
    {
        _logger = logger;
        _sysSetting = sysSetting;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// 推送工单到网格员系统
    /// </summary>
    /// <param name="order"></param>
    /// <param name="orderSnapshot"></param>
    /// <param name="tokenDto"></param>
    /// <returns></returns>
    public async Task<ApiResponse<GuiderSystemOutDto>> PostOrder(Order order, OrderSnapshot orderSnapshot, ThirdTokenDto tokenDto)
    {
        var baseUrl = _sysSetting.TianQuanPostAcceptInfoApi;

        //var isDbueg = baseUrl.Contains("test");
        //if (isDbueg)
        //{
        //    httpClient = new TQHttpClient(tokenDto.Secret, tokenDto.AppId, "171.94.154.2", 22, "root", "ZGbyy@2024!", _logger);
        //}
        //else
        //{
        //    httpClient = new TQHttpClient(tokenDto.Secret, tokenDto.AppId, _logger);
        //}
        var acceptInfo = order.Adapt<AcceptInfo>();
        acceptInfo.ReplyCode = order.No!; // 唯一标识
        acceptInfo.TypeName = order.AcceptType!; // 诉求类型名称
        acceptInfo.OccurDate = order.CreationTime; // 事发时间
        acceptInfo.DetailAddress = order.FullAddress!; // 详细地址
        acceptInfo.Topic = order.Title!; // 线索主题
        acceptInfo.DetailContent = order.Content!; // 详细内容
        acceptInfo.Lon = order.Longitude.ToString()!; // 经度
        acceptInfo.Lat = order.Latitude.ToString()!; // 纬度
        acceptInfo.RootCategoryInfo = ""; // order.HotspotName!; // 热点分类(大类)
        acceptInfo.CategoryInfo = "";// order.HotspotSpliceName!; // 热点分类(小类)
        acceptInfo.DeadLine = orderSnapshot.DeadLine!.Value; // 截止时间

        var tianqueRequestMode = _sysSetting.TianQueRequestMode;
        TQHttpClient httpClient;
        switch (tianqueRequestMode)
        {
            case ETianqueRequestMode.TestEnvTestUrl:
                httpClient = new TQHttpClient(tokenDto.Secret, tokenDto.AppId, "171.94.154.2", 22, "root", "ZGbyy@2024!", _httpClientFactory, _logger);
                acceptInfo.Prod = false;
                break;
            case ETianqueRequestMode.ProEnvTestUrl:
                httpClient = new TQHttpClient(tokenDto.Secret, tokenDto.AppId, _httpClientFactory, _logger);
                acceptInfo.Prod = false;
                break;
            case ETianqueRequestMode.ProEnvProUrl:
                httpClient = new TQHttpClient(tokenDto.Secret, tokenDto.AppId, _httpClientFactory, _logger);
                acceptInfo.Prod = true;
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }

        //if (isDbueg)
        //{
        //    acceptInfo.Prod = false; // 正式/测试
        //}
        //else
        //{
        //    acceptInfo.Prod = true; // 正式/测试
        //}

        // 反映人信息
        acceptInfo.PersonList = new List<PersonInfo>
        {
            new() {
                ReflectPhone = order.Contact!, // 电话
                ReflectUserName = order.FromName!, // 姓名
            }
        };
        if (order.FileJson != null)
        {
            acceptInfo.Files = new List<FileInfo>();
            foreach (var item in order.FileJson)
            {
                acceptInfo.Files.Add(new FileInfo
                {
                    FileContent = item.Path,
                    FileName = item.FileName + "." + item.FileType
                });
            }
        }
        acceptInfo.ValidateObject();
        var result = await httpClient.PostAsync<ApiReponse<AcceptInfoSuccessDto>>(new Uri(baseUrl), acceptInfo);
        return new ApiResponse<GuiderSystemOutDto>
        {
            Code = result.Success ? 0 : 1,
            Message = result.Msg,
            Result = new GuiderSystemOutDto
            {
                GuiderSystemId = result.Data?.AppealNumber,
                JsonData = result.Data?.ToJson()
            }
        };
    }
}
