using OASystem.Domain.ViewModels.JuHeExchangeRate;
using OASystem.Domain.ViewModels.SmallFun;
using System.Text.Json;

namespace OASystem.API.OAMethodLib.GoogleMapAPI
{
    /// <summary>
    /// 谷歌地图API
    /// </summary>
    public static class GoogleMapTools
    {
        private static string _appKey = "AIzaSyBdLf8u8DinXQWVPLEkdrxOJpClXSqEnho"; //谷歌地图AppKey
        private static readonly HttpClient _httpClient = new HttpClient { BaseAddress = new Uri("https://maps.googleapis.com") };

        /// <summary>
        /// googleMapApi 获取距离And时间
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="destination"></param>
        /// <returns></returns>
        public static async Task<Result> GetForeignAndTime(string origin, string destination) 
        {
            var result = new Result() { Code = -2, Msg = "未知错误" };
            if (string.IsNullOrEmpty(origin) || string.IsNullOrEmpty(destination))
            {
                result.Msg= "起始地或目的地为空";
                return result;
            }

            string url = string.Format(@"/maps/api/directions/json?origin={0}&destination={1}&key={2}", origin, destination,_appKey);

            var req = await _httpClient.GetAsync(url);

            if (req.IsSuccessStatusCode) {
                var strResponse = await req.Content.ReadAsStringAsync();
                var resultData = System.Text.Json.JsonSerializer.Deserialize<GoogleMapResultView>(strResponse,
                        new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });

                if (resultData.Status == "OK") 
                {
                    if (resultData.Routes == null)
                    {
                        result.Msg = resultData.Status;
                        return result;
                    }

                    var data =  JsonConvert.DeserializeObject<dynamic>( resultData.Routes.ToJson());

                    var dataView = new DistanceAndTimeView {
                        DistanceText = data[0]["legs"][0]["distance"]["text"].ToString(),
                        DistanceValue = data[0]["legs"][0]["distance"]["value"],
                        DurationText = data[0]["legs"][0]["duration"]["text"].ToString(),
                        DurationValue = data[0]["legs"][0]["duration"]["value"],
                    };


                    result.Code = 0;
                    result.Data = dataView;
                }
                else
                {
                    result.Msg = resultData.Status;
                }

            }
            else
            {
                result.Msg = "GoogleMapApi接口网络异常链接超时";
            }
            return result;
        }
    }
}
