using JiaZhiQuan.Common.JuheAPI.PhoneNumber;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using System;
using Wicture.DbRESTFul;

namespace JiaZhiQuan.Common.JuheAPI.IpAddress
{
    /// <summary>
    /// IP归属地查询
    /// </summary>
    public class JuheIpAddressUtils
    {
        const string JUHE_IP_KEY = "fe8483723642e2ec7df225caf4ae7889";

        /// <summary>
        /// 调用聚合API查询IP信息
        /// <return>Item1：是不是需要保存结果到ES，Item2：拼接的地址信息，Item3：省，Item4：市</return>
        /// </summary>
        public static async Task<(bool, string, string, string)> GetIpAddressAsync(string ip, HttpClient client)
        {
            try
            {
                var res = await client.GetStringAsync($"http://apis.juhe.cn/ip/ipNewV3?ip={ip}&key={JUHE_IP_KEY}");
                var obj = JsonConvert.DeserializeObject<JuheResponseModel<JuheMobileAddressResultDetails>>(res);
                if (obj.ResultCode == "200" && obj.ErrorCode == 0)
                {
                    string province = string.IsNullOrEmpty(obj.Result.Province) ? "未知" : obj.Result.Province,
                           city = string.IsNullOrEmpty(obj.Result.City) ? "未知" : obj.Result.City;
                    string addr = !province.Equals(city) ? $"{province}{city}" : province;
                    return (true, addr, province, city);
                }
                // 查询无结果
                else if (obj.ResultCode == "200" && (obj.ErrorCode == 200103 || obj.ErrorCode == 200105))
                {
                    return (true, "未知", "未知", "未知");
                }
                else
                {
                    LoggerManager.Logger.Error($"调用聚合IP归属地API失败，请求结果：" + res);
                    return (false, "未知", "未知", "未知");
                }
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.Error(ex, $"调用聚合IP归属地API报错：" + ex.Message);
                return (false, "未知", "未知", "未知");
            }
        }
    }
    public class JuheMobileAddressResultDetails
    {
        public string Country { get; set; }
        public string Province { get; set; }
        public string City { get; set; }
        public string District { get; set; }
        public string Isp { get; set; }
    }
}
