using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dodohold.core;
using Dataoke;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Ocsp;
using System.Diagnostics;
using TencentCloud.Fmu.V20191213.Models;
using Microsoft.VisualBasic;
using System.Text.Json;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Security.Cryptography;
using System.Security.Policy;
using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.Components;
using Org.BouncyCastle.Pqc.Crypto.Ntru;
using Newtonsoft.Json;
using Sayaka.Common;
using System.Net;


namespace molilian.core
{
    public partial class JdUnionPlus
    {
        public async Task<JdDataDTO> GetPromotionBySiteAsync(JdDataDTO result, string shortLinkurl, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(_account.site_id))
            {
                return await GetPromotionByAffAsync(result, shortLinkurl, cancellationToken);
            }

            string method = "jd.union.open.promotion.common.get";
            string version = "1.0";
            var data = new
            {
                promotionCodeReq = new
                {
                    siteId = _account.site_id,
                    materialId = shortLinkurl,
                    command = 1,
                    chainType = 2,
                }
            };
            var body = await RequestAsync(method, version, data.Convert2Json(), cancellationToken);
            var root = body.Convert2Object<JdUnionResponse>();

            if (root != null && root.jd_union_open_promotion_common_get_responce != null)
            {


                var _promotion_data = root.jd_union_open_promotion_common_get_responce.getResult;
                var promotion_data = _promotion_data.Convert2Object<JdData>();
                string code = root.jd_union_open_promotion_common_get_responce.code;
                if ("0".Equals(code))
                {
                    if (promotion_data.code == 200)
                    {
                        var url = promotion_data.data.clickURL;

                        result.success = true;
                        result.message = "OK";
                        result.shortLinkurl = url;
                        result.content = result.shortLinkurl;
                        result.deeplink_url = GetDeeplink(result.shortLinkurl);

                        return result;
                    }
                }
                result.reason = root.jd_union_open_promotion_common_get_responce.message;
                if (string.IsNullOrEmpty(result.reason)) result.reason = promotion_data.message;
            }
            else
            {
                result.reason = "网络错误";
            }

            result.success = false;
            result.message = "转链失败";
            result.shortLinkurl = shortLinkurl;
            result.deeplink_url = GetDeeplink(result.shortLinkurl);

            _ = new LoggerLibrary("JdUnion", "promotion_get_error").Info(body).SaveAsync();
            return result;
        }

        public async Task<JdDataDTO> GetPromotionByAffAsync(JdDataDTO result, string shortLinkurl, CancellationToken cancellationToken = default)
        {

            string method = "jd.union.open.promotion.bysubunionid.get";
            string version = "1.0";
            var data = new
            {
                promotionCodeReq = new
                {
                    materialId = shortLinkurl,
                    command = 1,
                    chainType = 2,
                }
            };
            var body = await RequestAsync(method, version, data.Convert2Json(), cancellationToken);
            var root = body.Convert2Object<JdUnionResponse>();
            //{"jd_union_open_promotion_bysubunionid_get_responce":{"code":"0","getResult":"{\"code\":200,\"data\":{\"shortURL\":\"https://u.jd.com/esCrWn4\"},\"message\":\"success\",\"requestId\":\"o_0b64a07b_lyiusnpg_74220789\"}"}}

            if (root != null && root.jd_union_open_promotion_bysubunionid_get_responce != null)
            {
                string code = root.jd_union_open_promotion_bysubunionid_get_responce.code;
                var _promotion_data = root.jd_union_open_promotion_bysubunionid_get_responce.getResult;
                var promotion_data = _promotion_data.Convert2Object<JdData>();
                if ("0".Equals(code))
                {
                    if (promotion_data.code == 200)
                    {
                        var url = promotion_data.data.shortURL;

                        result.success = true;
                        result.message = "OK";
                        result.shortLinkurl = url;
                        result.content = result.shortLinkurl;
                        result.deeplink_url = GetDeeplink(result.shortLinkurl);

                        return result;
                    }
                }
                result.reason = root.jd_union_open_promotion_bysubunionid_get_responce.message;
                if (string.IsNullOrEmpty(result.reason)) result.reason = promotion_data.message;
            }
            else
            {
                result.reason = "网络错误";
            }

            result.success = false;
            result.message = "转链失败";
            result.shortLinkurl = shortLinkurl;
            result.deeplink_url = GetDeeplink(result.shortLinkurl);
            _ = new LoggerLibrary("JdUnion", "bysubunionid_get_error").Info(body).SaveAsync();
            return result;
        }
        public async Task<JdDataDTO> GetPromotionByCrawlerAsync(JdDataDTO result, string wareUrl, CancellationToken cancellationToken = default)
        {
            string[] parts = wareUrl.Split(new string[] { ".html" }, StringSplitOptions.None);
            if (parts.Length > 1)
            {
                wareUrl = parts[0] + ".html";
            }


            var ts = DateTime.Now.Convert2UnixTimestamp(true);
            string cookies = _account.cookies;
            //cookies = "pinId=lDSKR4P756s; __jdu=797222838; unpl=JF8EAM1nNSttXxtVVxtSSEFASw9QWwpbTh4KP28NAwlaTAvEt16MoRnbUfHBdCarU9683KT3AsB67n92UtFSEXtdVV9fD0oeBm5vNWRdXU8ABh5VSUAXJV06KgF6SUxXbxN6CCU2S1UEGgYfExlOX11bEAl7FANfZjVSVV5IVwYSABIiEXtdXFptCEoWAmtjBF1YWkJRNSsHGxMRTltWX1oBexYzbWYEUV1fQ10AGjJZfMnF8oHV_d_CidTxw9Df9oz_3EgdCh0RE0hUVldtCXsU; shshshfpa=02d19590-d1e4-c91f-76d9-50b5b48caeae-1696955111; shshshfpx=02d19590-d1e4-c91f-76d9-50b5b48caeae-1696955111; TrackID=1P1YIoOSuMvq9KVQS8e4qaKAWslU3bHIlXwpUNeXUOPY_dPOhYcH5fl6XgaIzKppd5zTuGg52Ql9Ht7h1LNA62ZkhO1G3xwkTKekmP3nhjjmnOr5rzvlohhH3EkChqHLB; thor=D3FCA70DCE7542F87C212B790D3JDaxNfPy83okP3kLScwCkGiuMcyC4Pcyn8202E9E708F27CB58F480D2CC3FE67C9253747FE21007250E37AE528C577139FEEC81E6EE68034351A54BE200FF3JDaxNfPy83okP3kLScwCkGiuMcyC4Pcyn7n92UtFE03B1646F11A6B796AEE7DE71C760EDFF210BD03D24599A6CFF007C0D40BA49D; pin=23117; unick=jd2311kga; _tp=D8kjVbHzTJzgqxcxaN3m1w%3D%3D; _pst=23117; ipLoc-djd=24-2144-3909-58335; 3AB9D23F7A4B3C9B=IPF6PUOISQRNPNXNQVLJJVKQVBTAvEt16MoRnbUfHBdCarU9683JDaxNfPy83okP3kLScwCkGiuMcyC4PcynYGLMEE; flash=2_YNg0msef1iArLpGWQBwhJos62BkQWLuFuDD-HGOLK2KKuPtQ08qYx9js2jlEHwoRT7AVTOjRo8iR1-PT6ZsT8ZDnqdgMfbeoSNMJvJa8qphobenATQ0WXPYP62_XgiF1J7II6jY1qovmiIDadA7rd5tHyAVpTzEsqpI6xVJ9b6D*; __jda=209449046.797222838.1720272224.1720293360.1721239059.3; __jdc=209449046; __jdv=209449046|baidu|-|organic|notset|1721239059356; 3AB9D23F7A4B3CSS=jdd03IPF6PUOISQRNPNXNQVLJJVKQVBTAvEt16MoRnbUfHBdCarU9683JDaxNfPy83okP3kLScwCkGiuMcyC4PcynvEt16MoRnbUfHBdCarU9683KT3AsB67n92UtFUX; _gia_d=1; shshshfpb=BApXcdm_fwvVAJzuAI6Mnq8QQOcIPSh90B9TUVj599xJ1MlKCa4O2; __jdb=209449046.5.797222838|3.1721239059; RT=\"z=1&dm=jd.com&si=zpw2ttxi9&ss=lyq5alej&sl=6&tt=3x4&ld=z4s&nu=3d2f85352c70c73af100bf1449967844&cl=x78\"\r\n\r\n;";

            string uuid = cookies.GetContentPart("__jdu=", ";");
            string __jda = cookies.GetContentPart("__jda=", ";");
            if (__jda.Split('.').Length > 1)
            {
                uuid = __jda.Split('.')[1];
            }

            string useragent = _account.user_agent;
            if (string.IsNullOrEmpty(useragent)) useragent = ProviderFakeUserAgent.RandomComputer;
            string url = $"https://api.m.jd.com/api?functionId=unionPromoteLinkService&" +
                $"appid=unionpc&_={ts}&loginType=3&uuid={uuid}";

            var args = new
            {
                funName = "getCode",
                param = new
                {
                    couponLink = "",
                    isPinGou = 0,
                    materialId = result.itemId,
                    materialType = 1,
                    planId = 3479956501,
                    promotionType = 15,
                    receiveType = "cps",
                    wareUrl = wareUrl,
                    isSmartGraphics = 0,
                    command = 1,
                    ext1 = "618|pc|".UrlEncode()
                },
                lientPageId = "jingfen_pc"
            };
            string data = args.Convert2Json().UrlEncode();

            WebClientUtility client = new WebClientUtility();
            client.Proxy = _proxy;
#if DEBUG
            client.Proxy = null;
#endif
            client.SetContentType("application/x-www-form-urlencoded");
            client.AddHeaders("X-Referer-Page", "https://union.jd.com/proManager/index");
            client.AddHeaders("X-Rp-Client", "h5_1.0.0");
            client.AddHeaders("Referer", "https://union.jd.com/");
            client.AddHeaders("Origin", "https://union.jd.com");
            client.UserAgent = useragent;
            client.AddHeaders("Cookie", cookies);
            client.Post($"body={data}");
            var response = await client.RequestAsync(url, "POST", cancellationToken);

            string body = response.Body();
            var root = body.Convert2JsonElement();
            int code = root.Read<int>("code");
            string message = root.Read<string>("message");
            string shortCode = root.PathRead<string>("data.shortCode");

            if (code == 200)
            {
                result.success = true;
                result.message = "OK";
                result.shortLinkurl = shortCode;
                result.content = result.shortLinkurl;
                result.deeplink_url = GetDeeplink(result.shortLinkurl);
            }
            else
            {
                if (string.IsNullOrEmpty(body)) message = "网络异常";
                result.success = false;
                result.message = "转链失败";
                result.reason = message;
                result.shortLinkurl = wareUrl;
                result.deeplink_url = GetDeeplink(result.shortLinkurl);
                _ = new LoggerLibrary("JdUnion", "GetPromotionByCrawlerAsync").Info(body).SaveAsync();
            }
            return result;
        }

    }


    public class JdData
    {
        public int code { get; set; }
        public string message { get; set; }
        public string requestId { get; set; }
        public JdClickData data { get; set; }
    }

    public class JdClickData
    {
        public string shortURL { get; set; }
        public string clickURL { get; set; }
        public string jCommand { get; set; }
    }



    public class JdUnionResponse
    {
        public JdUnionOpenPromotionCommonGetResponce jd_union_open_promotion_common_get_responce { get; set; }
        public JdUnionOpenPromotionCommonGetResponce jd_union_open_promotion_bysubunionid_get_responce { get; set; }

    }

    public class JdUnionOpenPromotionCommonGetResponce
    {
        public string code { get; set; }
        public string getResult { get; set; }
        public string message { get; set; }
        public string requestId { get; set; }
    }


}
