using dodohold.core;
using Sayaka.Common;
using System.Text.RegularExpressions;

namespace molilian.core
{
    public class PddTransferUrlResult
    {
        public string multiGroupShortUrl { get; set; } = string.Empty;
        public string multiGroupUrl { get; set; } = string.Empty;
        public string shortUrl { get; set; } = string.Empty;
        public string url { get; set; } = string.Empty;
    }

    public class PddTransferUrlResponse
    {
        public int errorCode { get; set; }
        public string errorMsg { get; set; } = string.Empty;
        public bool success { get; set; } = false;
        public PddTransferUrlResult result { get; set; } = new();
    }

    public class PddCreatePromotionUrlResult
    {
        public string multiGroupShortUrl { get; set; } = string.Empty;
        public string multiGroupUrl { get; set; } = string.Empty;
        public string shortUrl { get; set; } = string.Empty;
        public string url { get; set; } = string.Empty;
    }

    public class PddCreatePromotionUrlResponse
    {
        public int errorCode { get; set; }
        public string errorMsg { get; set; } = string.Empty;
        public bool success { get; set; } = false;
        public PddCreatePromotionUrlResult result { get; set; } = new();
    }

    public partial class PddUnionPlus
    {
        public async Task<PddDataDTO> transferUrl(PddDataDTO result, string sourceUrl, CancellationToken cancellationToken = default)
        {
            var ts = DateTime.Now.Convert2UnixTimestamp(true);
            string cookies = _account.cookies.Trim();

            string useragent = ProviderFakeUserAgent.RandomComputer;
            string url = "https://jinbao.pinduoduo.com/network/api/promotion/transferUrl";

            //{"pid":"13848803_189356569","sourceUrl":"https://p.pinduoduo.com/1OAsct0r"}

            var args = new
            {
                _account.pid,
                sourceUrl = sourceUrl.UrlDecode(),
            };
            string data = args.Convert2Json();

            WebClientUtility client = new WebClientUtility();
            client.Proxy = _proxy;
#if DEBUG
            client.Proxy = null;
#endif
            client.SetContentType("application/json");
            client.AddHeaders("Referer", "https://jinbao.pinduoduo.com/promotion/url-promotion");
            client.AddHeaders("Origin", "https://jinbao.pinduoduo.com");
            client.UserAgent = useragent;
            client.AddHeaders("Cookie", cookies);
            client.Post(data);
            var response = await client.RequestAsync(url, "POST", cancellationToken);

            string body = response.Body();
            var root = body.Convert2Object<PddTransferUrlResponse>();
            string message = string.Empty;

            if (!root.success)
            {
                message = $"{root.errorCode}:{root.errorMsg}";
                result.success = false;
                result.message = "转链失败";
                result.reason = message;
                _ = new LoggerLibrary("PddUnion", "transferUrl").Info(body).SaveAsync();
                return result;
            }

            if (string.IsNullOrEmpty(root.result?.multiGroupShortUrl))
            {
                result.success = false;
                result.message = "转链失败";
                result.reason = "无法转链";
                //_ = new LoggerLibrary("PddUnion", "transferUrl").Info(body).SaveAsync();
                return result;
            }

            if (!string.IsNullOrEmpty(root.result?.url))
            {
                result.itemId = root.result?.url.GetContentPart("goods_id=", "&");
            }

            result.success = true;
            result.message = "OK";
            result.link_type = LinkTypeEnum.goods;
            result.shortLinkurl = root.result?.multiGroupShortUrl;
            result.content = result.shortLinkurl;
            result.deeplink_url = GetDeeplink(result.shortLinkurl);


            return result;
        }


        public async Task<PddDataDTO> createPromotionUrl(PddDataDTO result, string sourceUrl, CancellationToken cancellationToken = default)
        {
            var ts = DateTime.Now.Convert2UnixTimestamp(true);
            string cookies = _account.cookies.Trim();

            string useragent = ProviderFakeUserAgent.RandomComputer;
            string url = "https://jinbao.pinduoduo.com/network/api/promotion/createPromotionUrl";

            //{"pid":"13848803_189356569","sourceUrl":"https://p.pinduoduo.com/1OAsct0r"}

            string goodsId = sourceUrl;
            var args = new
            {
                _account.pid,
                goodsId,
                generateOpenCoupon = true
            };

            /*
{
	"mediaId": "9092702778",
	"pid": "13848803_189356569",
	"goodsId": "123",
	"generateOpenCoupon": true
}             
             */
            string data = args.Convert2Json();

            WebClientUtility client = new WebClientUtility();
            client.Proxy = _proxy;
#if DEBUG
            client.Proxy = null;
#endif
            client.SetContentType("application/json");
            client.AddHeaders("Referer", "https://jinbao.pinduoduo.com/promotion/url-promotion");
            client.AddHeaders("Origin", "https://jinbao.pinduoduo.com");
            client.UserAgent = useragent;
            client.AddHeaders("Cookie", cookies);
            client.Post(data);
            var response = await client.RequestAsync(url, "POST", cancellationToken);

            string body = response.Body();
            var root = body.Convert2Object<PddCreatePromotionUrlResponse>();
            string message = string.Empty;

            if (!root.success)
            {
                message = $"{root.errorCode}:{root.errorMsg}";
                result.success = false;
                result.message = "转链失败";
                result.reason = message;
                _ = new LoggerLibrary("PddUnion", "transferUrl").Info(body).SaveAsync();
                return result;
            }

            if (string.IsNullOrEmpty(root.result?.multiGroupShortUrl))
            {
                result.success = false;
                result.message = "转链失败";
                result.reason = "无法转链";
                //_ = new LoggerLibrary("PddUnion", "transferUrl").Info(body).SaveAsync();
                return result;
            }

            //goods_id=636365867069&pid=13848803_189356569&goods_sign=E9z2NkASdqlKuWDVwvfdqnADgCEqTQSt_JuMe2WC0G&zs_duo_id=25194414&cpsSign=CC_240807_13848803_189356569_fdbbdfa499058644becc9f8b3b7acaaf&_x_ddjb_act=

            if (!string.IsNullOrEmpty(root.result?.url))
            {
                result.itemId = root.result?.url.GetContentPart("goods_id=", "&");
            }

            result.success = true;
            result.message = "OK";
            result.link_type = LinkTypeEnum.goods;
            result.shortLinkurl = root.result?.multiGroupShortUrl;
            result.content = result.shortLinkurl;
            result.deeplink_url = GetDeeplink(result.shortLinkurl);


            return result;
        }

    }
}
