using dodohold.core;
using Google.Protobuf.WellKnownTypes;
using Org.BouncyCastle.Ocsp;
using Quartz;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using TencentCloud.Trtc.V20190722.Models;


namespace molilian.core
{
    public partial class DeepleaperPlus
    {
        private const string SERVER_URL = "https://qianxun.deepleaper.com/v1";
        private string _accessKey;
        private string _secretKey;

        WebProxy? _proxy;
        string _proxyName;
        public DeepleaperPlus(string nodeName = "", string accessKey = "", string secretKey = "")
        {
            if (!string.IsNullOrEmpty(nodeName))
            {
                _proxyName = ProxyNodesCore.GetSelectOne(nodeName);
                _proxy = ProxyNodesCore.GetOne(_proxyName);
            }

            accessKey = "qx-stvlJ2u6M7xsY6az";
            secretKey = "MDQ1ZTliZDczODdhNDkzZDk4N2U1YmVjMmNkNDE4NjRscENHWnZ2UA==";
            _accessKey = accessKey;
            _secretKey = secretKey;
        }

        private static string GenerateSign(string secretKey, long ts)
        {
            try
            {
                string message = ts.ToString();

                using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey)))
                {
                    byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
                    return Convert.ToBase64String(hashBytes);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("生成签名失败", ex);
            }
        }

        public async Task<TkDataDTO> UnionParseAsync(TkDataDTO result)
        {
            long ts = DateTime.Now.Convert2UnixTimestamp(true);

            var args = new
            {
                version = "1.0",
                endpoint = new
                {
                    device = new
                    {
                        oaid = result.oaid,
                        location = new
                        {
                            locationSystem = "BD09LL",
                            latitude = "",
                            longitude = ""
                        }
                    },
                },
                header = new
                {
                    type = "IntentRequest",
                    timestamp = $"{ts}"
                },
                inquire = new
                {
                    inquireId = $"shopping-shareCodeTkl-{ts}",
                    intent = new
                    {
                        apiKey = "shopping-shareCodeTkl",
                        slots = new
                        {
                            shareCodeTkl = new
                            {
                                name = "shareCodeTkl",
                                values = new[] {
                                        new
                                        {
                                            real = result.content
                                        }
                                    }
                            }
                        }
                    }
                }
            };
            string post = args.Convert2Json();
            string sign = GenerateSign(_secretKey, ts);
            var client = new WebClientUtility();
            client.AddHeaders("accessKey", _accessKey);
            client.AddHeaders("ts", $"{ts}");
            client.AddHeaders("sign", sign);
            client.SetContentType("application/json");
            client.Post(post);
#if DEBUG
#else
            client.Proxy = _proxy;
#endif
            var response = await client.RequestAsync(SERVER_URL);

            var body = response.Body();
            result.remote_response = body;
            var root = body.Convert2JsonElement();


            var now = DateTime.Now;
            var ts2 = now - result.create_time;
            result.elapsedTime2 = (int)ts2.TotalMilliseconds;


            int error = root.Read<int>("errorCode", 0);
            bool success = error == 0 || error == 200;
            string message = root.Read("errorMessage", string.Empty);
            result.success = false;
            //if (message.Contains("该url暂不支持解析"))
            //{
            //    message = "该url暂不支持解析";
            //}

            //	"message": "淘宝口令解析服务异常: Cannot deserialize value of type `java.lang.Integer` from String \"该卖家ID暂不支持\": not a valid `java.lang.Integer` value\n at [Source: UNKNOWN; byte offset: #UNKNOWN] (through reference chain: com.deepleaper.qianxun.model.taobao.QXTbGeneralLinkParseResponse[\"data\"]->com.deepleaper.qianxun.model.taobao.QXTbGeneralLinkParseResponse$Result[\"material_url_list\"]->java.util.ArrayList[0]->com.deepleaper.qianxun.model.taobao.QXTbGeneralLinkParseResponse$Material[\"msg\"])",

            result.reason = message;
            result.message = "fail";
            if (!success) return result;
            try
            {
                var shoppingInfoItems = root.ElementRead("reply").ElementRead("commands")[0].ElementRead("body").ElementRead("templateContent").ElementRead("items")[0].ElementRead("shoppingInfoItems");

                result.itemName = shoppingInfoItems[0].PathRead<string>("name");
                result.pic = shoppingInfoItems[0].PathRead<string>("mainImage.large.url");
                result.shopTitle = shoppingInfoItems[0].PathRead<string>("storeName");
                result.couponAmount = shoppingInfoItems[0].PathRead<int>("couponInfo[0].amount.url");
                result.shortLinkurl = shoppingInfoItems[0].PathRead<string>("detailUrl.webURL");
                result.deeplink_url = shoppingInfoItems[0].PathRead<string>("detailUrl.deepLink.url");
                result.with_middle_page = shoppingInfoItems[0].PathRead<int>("detailUrl.type");
                result.reason = shoppingInfoItems[0].PathRead<string>("detailUrl.subMsg");
                if (result.with_middle_page == 1)
                {
                    result.message = "success";
                    result.commercial = true;
                }
                else
                {
                    result.message = "转链失败";
                }
                result.channel = TkChannelEnum.tb;
                result.success = success;
                //result.content = content;
                return result;
            }
            catch (Exception ex)
            {
                result.reason = "undefined";
                result.message = "fail";
                return result;
            }
        }


    }

}
