using Newtonsoft.Json;
using NLog;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Wicture.DbRESTFul;

namespace JiaZhiQuan.Common.JuheAPI.PhoneNumber
{
    /// <summary>
    /// 手机号归属地查询
    /// </summary>
    /// <param name="db"></param>
    /// <param name="phone"></param>
    /// <returns>Item1: 是不是要保存到ES，Item2: 地址，Item3: 省，Item4: 市</returns>
    public class JuheMobileAddressUtils
    {
        const string JUHE_PHONE_KEY = "641cf7b85574a965e6eb3d4864e18da3";
        public static async Task<(bool, string, string, string)> GetMobileAddressAsync(string mobile, HttpClient client)
        {
            try
            {
                var res = await client.GetStringAsync($"http://apis.juhe.cn/mobile/get?phone={mobile}&key={JUHE_PHONE_KEY}");
                var obj = JsonConvert.DeserializeObject<JuheResponseModel<JuheMobileAddressResultDetails>>(res);
                if (obj.ResultCode == "200" && obj.ErrorCode == 0)
                {
                    string company = string.IsNullOrEmpty(obj.Result.Company) ? "未知" : obj.Result.Company,
                           province = string.IsNullOrEmpty(obj.Result.Province) ? "未知" : obj.Result.Province,
                           city = string.IsNullOrEmpty(obj.Result.City) ? "未知" : obj.Result.City;
                    string addr = $"【{company}】-【{province}-{city}】";
                    return (true, addr, province, city);
                }
                // 查询无结果
                else if (obj.ResultCode == "200" && obj.ErrorCode == 201103)
                {
                    return (true, "未知", "未知", "未知");
                }
                else
                {
                    LoggerManager.Logger.Error($"调用聚合手机号归属地API失败，请求结果：" + res);
                    return (false, "未知", "未知", "未知");
                }
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.Error(ex, $"调用聚合手机号归属地API报错：" + ex.Message);
                return (false, "未知", "未知", "未知");
            }
        }
    }

    public class JuheMobileAddressResultDetails
    {
        public string Province { get; set; }
        public string City { get; set; }
        public string AreaCode { get; set; }
        public string Zip { get; set; }
        public string Company { get; set; }
        public string Card { get; set; }
    }

}
