using dodohold.core;

namespace molilian.core
{


    public partial class KsUnionPlus
    {

        public class BaseResponse
        {
            public int result { get; set; }
            public string msg { get; set; }
            public string error_msg { get; set; }
            public string code { get; set; }
            public string requestId { get; set; }
            public string sub_msg { get; set; }
            public string sub_code { get; set; }
        }

        public class GetItemIdResponse : BaseResponse
        {
            public ParseInfoDTO data { get; set; } = new ParseInfoDTO { };
        }

        public class ParseCpsUrlResponse : BaseResponse
        {
            public DistributeCpsPidLinkDTO data { get; set; } = new DistributeCpsPidLinkDTO { };
        }


        public class DistributeCpsPidLinkDTO
        {
            public string linkCode { get; set; } = string.Empty;
            public string linkUrl { get; set; } = string.Empty;
            public string kwaiUrl { get; set; } = string.Empty;
            public string cpsPid { get; set; } = string.Empty;
            public string nebulaKwaiUrl { get; set; } = string.Empty;
            public string shortContent { get; set; } = string.Empty;
            public string longContent { get; set; } = string.Empty;
            public string commandContent { get; set; } = string.Empty;
            public string shareToken { get; set; } = string.Empty;
            public string minaShortLink { get; set; } = string.Empty;
            public bool hasSecondActivity { get; set; } = true;
        }


        public class ParseInfoDTO
        {
            public long itemId { get; set; }
        }



        public async Task<KsDataDTO> UnionGeneratelink(KsDataDTO result, string content, CancellationToken cancellationToken = default)
        {
            long item_id = getItemId(content);
            var data = parseCpsUrl(item_id);

            /*
             {"result":100001,"msg":"业务处理失败","error_msg":"分销商品不存在或已下架","code":"807000","requestId":"724092832538976441","sub_msg":"分销商品不存在或已下架","sub_code":"100001"}
            */

            if (data.result != 1)
            {
                result.success = false;
                result.message = "转链失败";
                result.reason = data.error_msg;
                result.deeplink_url = GetDeeplink(content, LinkTypeEnum.goods);
                return result;
            }
            result.link_type = LinkTypeEnum.goods;
            result.shortLinkurl = data.data.linkUrl;
            result.deeplink_url = data.data.kwaiUrl;
            return result;
        }

        public long getItemId(string content)
        {
            //todo 写死 
            var _ticket = new dodohold.core.kwaixiaodian.AccessTokenDTO();
            _ticket.access_token = "ChFvYXV0aC5hY2Nlc3NUb2tlbhIwbmKPStYeS1x-ZvbjXU5Di0DQpSKhBSpJr8Zni_S0ltA0di1ryALJD4K_4tF1ovA6GhLiICkHPKJFr7JGeErh7m5jzagiIJ5kqUgNpOvl9uBTg4gE4DiEc84Mu8ssnaAInrHmwbmtKAUwAQ";


            string action = "open.distribution.cps.kwaimoney.link.parse";
            var data = new { cpsLink = content };
            var body = plus.Request(_ticket, action, data.Convert2Json(), "POST");

            var result = body.Convert2Object<GetItemIdResponse>();
            return result.data.itemId;
        }


        public ParseCpsUrlResponse parseCpsUrl(long itemId)
        {
            //todo 写死 
            var _ticket = new dodohold.core.kwaixiaodian.AccessTokenDTO();
            _ticket.access_token = "ChFvYXV0aC5hY2Nlc3NUb2tlbhIwbmKPStYeS1x-ZvbjXU5Di0DQpSKhBSpJr8Zni_S0ltA0di1ryALJD4K_4tF1ovA6GhLiICkHPKJFr7JGeErh7m5jzagiIJ5kqUgNpOvl9uBTg4gE4DiEc84Mu8ssnaAInrHmwbmtKAUwAQ";


            string action = "open.distribution.cps.kwaimoney.link.create";
            var ts = DateTime.Now.Convert2UnixTimestamp();
            string comments = ts.ToString();
            int linkType = 101;
            var data = new
            {
                linkType,
                linkCarrierId = itemId,
                comments,
                cpsPid = _account.pid,
                genPoster = false,
            };
            var body = plus.Request(_ticket, action, data.Convert2Json(), "POST");
            var result = body.Convert2Object<ParseCpsUrlResponse>();

            return result;
        }

        //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(KsPoolDTO 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<KsDataDTO> UnionGeneratelink(KsDataDTO result, string sourceUrl, CancellationToken cancellationToken = default)
        //        {
        //            var ts = DateTime.Now.Convert2UnixTimestamp(true);
        //            var args = new Dictionary<string, string>
        //            {
        //                { "type", "ks.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("KsUnion", "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("KsUnion", "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("KsUnion", "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;
        //        }
    }
}
