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

namespace molilian.core
{



    public partial class PddUnionPlus
    {
        static string _baseUrl = "https://gw-api.pinduoduo.com/api/router";


        public class ErrorResponse
        {
            public string error_msg { get; set; }
            public string sub_msg { get; set; }
            public string sub_code { get; set; }
            public int error_code { get; set; }
            public string request_id { get; set; }
        }


        public class GoodsZsUnitGenerateResponse
        {
            public string multi_group_mobile_short_url { get; set; }
            public string multi_group_url { get; set; }
            public string mobile_url { get; set; }
            public string multi_group_short_url { get; set; }
            public string mobile_short_url { get; set; }
            public string multi_group_mobile_url { get; set; }
            public string request_id { get; set; }
            public string url { get; set; }
            public string short_url { get; set; }
        }
        public class UnionGeneratelinkDTO
        {
            public GoodsZsUnitGenerateResponse goods_zs_unit_generate_response { get; set; }
            public ErrorResponse error_response { get; set; }
        }


        public static Dictionary<string, string> GenerateSignature(PddPoolDTO account, Dictionary<string, string> args)
        {
            if (args.ContainsKey("sign")) args.Remove("sign");
            // 对参数进行ASCII升序排序
            var sortedArgs = args.OrderBy(kv => kv.Key).ToDictionary(kv => kv.Key, kv => kv.Value);

            // 拼接排序后的参数
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var kv in sortedArgs)
            {
                stringBuilder.Append(kv.Key).Append(kv.Value);
            }

            // 在头部和尾部分别拼接client_secret
            string signString = account.app_secret + stringBuilder.ToString() + account.app_secret;
            signString = signString.MD5(false, false);

            if (!args.TryAdd("sign", signString))
            {
                args["sign"] = signString;
            }
            return args;
        }


        /// <summary>
        /// 多多进宝转链接口
        /// </summary>
        /// <param name="result"></param>
        /// <param name="sourceUrl"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<PddDataDTO> UnionGeneratelink(PddDataDTO result, string sourceUrl, CancellationToken cancellationToken = default)
        {
            var ts = DateTime.Now.Convert2UnixTimestamp(true);
            var args = new Dictionary<string, string>
            {
                { "type", "pdd.ddk.goods.zs.unit.url.gen" },
                { "data_type", "JSON" },
                { "client_id", _account.app_key },
                { "pid", _account.pid },
                { "source_url", sourceUrl },
                { "timestamp", ts.ToString() }
            };
            args = GenerateSignature(_account, args);

            var query = HttpUtility.ParseQueryString(string.Empty);
            foreach (var kvp in args) query[kvp.Key] = kvp.Value;
            string urlWithQuery = $"{_baseUrl}?{query}";


            WebClientUtility client = new();
            client.Proxy = _proxy;
#if DEBUG
            client.Proxy = null;
#endif
            client.SetContentType("application/json");
            var response = await client.RequestAsync(urlWithQuery, "GET", cancellationToken);

            string body = response.Body();
            var root = body.Convert2Object<UnionGeneratelinkDTO>();
            string message = string.Empty;
            _ = new LoggerLibrary("PddUnion", "debug ").Info(urlWithQuery, body).SaveAsync();

            if (root.error_response != null || root.goods_zs_unit_generate_response == null)
            {
                message = $"{root.error_response.sub_code}:{root.error_response.sub_msg}";
                result.success = false;
                result.message = "转链失败";
                result.reason = message;
                _ = new LoggerLibrary("PddUnion", "UnionGeneratelink").Info(urlWithQuery, body).SaveAsync();
                return result;
            }

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

            result.itemId = root.goods_zs_unit_generate_response.url.GetContentPart("goods_id=", "&");

            result.success = true;
            result.message = "OK";
            result.link_type = LinkTypeEnum.goods;
            result.shortLinkurl = root.goods_zs_unit_generate_response.short_url;
            result.content = result.shortLinkurl;
            result.deeplink_url = GetDeeplink(result.shortLinkurl);
            return result;
        }
    }
}
