using JiaZhiQuan.Common.Messaging.Models;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace JiaZhiQuan.Common.Utils
{
    public static class DeviceInfoUtils
    {
        /// <summary>
        /// 解析Device信息
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns>item1：系统，item2：APP版本，item3：机型，item4：市场来源</returns>
        public static (string, string, string, string) ExtractDevice(string deviceInfo, string channel)
        {
            string os = string.Empty,         // 来源系统
                   appVersion = string.Empty, // APP版本
                   phoneModel = string.Empty, // 机型
                   market = string.Empty;
            if (deviceInfo.Contains(UserInvite.ActiveChannel.Android.ToString()) && deviceInfo.Contains("soft_version"))
            {
                os = UserInvite.ActiveChannel.Android.ToString();
                AndroidDeviceInfo android = JsonConvert.DeserializeObject<AndroidDeviceInfo>(deviceInfo);
                // 版本号是v3.19.3_31这样的格式，数据库只保存3.19
                int startIndex = android.soft_version.IndexOf('v') + 1;
                int endIndex = android.soft_version.IndexOf('_');
                if (startIndex != -1 && endIndex != -1)
                {
                    appVersion = android.soft_version.Substring(startIndex, endIndex - startIndex);
                }
                phoneModel = android.brand;
                market = channel switch
                {
                    "xiaomi" => "小米市场",
                    "huawei" => "华为市场",
                    "yingyongbao" => "应用宝",
                    "baidu" => "百度市场",
                    "vivo" => "Vivo市场",
                    "oppo" => "Oppo市场",
                    "web" => "WEB (Android)",
                    _ => ""
                };
            }
            else if (deviceInfo.Contains("iPhone") && deviceInfo.Contains("appVersoft_versionsion"))
            {
                os = UserInvite.ActiveChannel.iOS.ToString();
                iOSDeviceInfo ios = JsonConvert.DeserializeObject<iOSDeviceInfo>(deviceInfo);
                // 版本号是3.0.1
                appVersion = ios.appVersoft_versionsion;
                phoneModel = ios.os;
                market = "App Store";
            }
            return (os, appVersion, phoneModel, market);
        }
    }
}
