using System;
using Android.Content;
using Com.Widget.Jlcountrycode;
using Com.Widget.Jlcountrycode.Sortselect;
using System.Collections.Generic;
using Java.Util;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Net.Http;
namespace JLCountrycode
{
public class CountryCodeView
{
///
/// 接口类的返回信息
///
private static CountryCodeView m_Current = null;
///
/// 接口类的返回信息
///
public static CountryCodeView Current
{
get
{
if (m_Current == null)
{
m_Current = new CountryCodeView();
}
return m_Current;
}
}
///
/// 根据手机当前的IP获取国家信息
///
///
public async Task GetCountryByIP()
{
string country = "Unknown";
try
{
using (HttpClient client = new HttpClient())
{
// 使用 ipinfo.io 获取位置信息
HttpResponseMessage response = await client.GetAsync("https://ipinfo.io/json");
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
JObject jsonObject = JObject.Parse(json);
// 从返回的 JSON 中提取国家信息
country = jsonObject["country"].ToString();
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error fetching IP info: {ex.Message}");
}
return country;
}
///
/// 国家区号选择
///
///
public void Show(Action action)
{
JLCountryCodeActivity.OnCountryCodeCallback = new OnCountryCodeCallback(action);
Shared.Application.Activity.StartActivity(new Intent(Shared.Application.Activity, typeof(JLCountryCodeActivity)));
}
///
/// 自定义传入字典数据 选择
///
///
///
///
public void ShowSortSelection(string titleStr, Dictionary> dic, Action action)
{
try
{
SortSelectionUtils.Instance.OnSortSelectCallback = new OnSSCallback(action);
SortSelectionUtils.Instance.SortSelectTitle = titleStr;
SortSelectionUtils.Instance.MSortSelectList = ConvertToHashMap(dic);
Shared.Application.Activity.StartActivity(new Intent(Shared.Application.Activity, typeof(JLSortSelectionActivity)));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
///
/// Dictionary 转 Android HashMap
///
///
///
Dictionary ConvertToHashMap(Dictionary> dict)
{
Dictionary newDictionary = new Dictionary();
try
{
foreach (string key in dict.Keys)
{
var value = dict[key];
var arrayList = new ArrayList();
arrayList.AddAll(value.ToArray());
newDictionary.Add(key, arrayList);
}
}
catch (Exception Ex)
{
//Logger.LogException(Ex);
}
return newDictionary;
}
}
///
/// OnCountryCodeCallback
///
public class OnCountryCodeCallback : Java.Lang.Object, Com.Widget.Jlcountrycode.Contact.IOnCountryCodeCallback
{
Action mAction;
public OnCountryCodeCallback(Action action)
{
mAction = action;
}
public void OnSelectCountryCallback(string countryName, string code)
{
mAction?.Invoke(countryName, code);
}
}
///
/// OnSortSelectCallback
///
public class OnSSCallback : Java.Lang.Object, IOnSortSelectCallback
{
Action mAction;
public OnSSCallback(Action action)
{
mAction = action;
}
public void OnSortSelectCallback(string countryName)
{
mAction?.Invoke(countryName);
}
}
}