using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
using System.Diagnostics;
using System.Text.Json;
using TencentCloud.Tcm.V20210413.Models;


namespace molilian.core
{
    public partial class AlimamaPlus
    {
        public async Task<TkDataDTO> endpoint_tbk_dg(string content, TkDataDTO result, CancellationToken cancellationToken = default)
        {
            string item_id = content.GetContentPart("item.htm?id=", "");
            if (string.IsNullOrEmpty(item_id))
            {
                _ = new LoggerLibrary("endpoint", "tbk_dg")
                    .Info(content, "response null")
                    .SaveAsync();
                result.channel = TkChannelEnum.tb;
                result.link_type = LinkTypeEnum.unknown;
                result.success = false;
                result.message = "放弃转链";
                result.reason = "无效商品id";
                return result;
            }

            string oaid = result.oaid;
            if (string.IsNullOrEmpty(oaid)) { oaid = DateTime.Now.Convert2UnixTimestamp().ToString().MD5(); }
            TaobaoOpenPlus taobao = new(_account.appkey, _account.appSecret, _account.open_pid, false, null);
            var response = taobao.SmartAssistantLinkConvertRequest(content, oaid);

            if (response == null)
            {
                _ = new LoggerLibrary("endpoint", "tbk_dg")
                    .Info(content, "response null")
                    .SaveAsync();
                result.channel = TkChannelEnum.tb;
                result.link_type = LinkTypeEnum.unknown;
                result.success = false;
                result.message = "fail";
                result.reason = "接口异常";
                return result;
            }
            result.success = !response.IsError;
            if (!result.success)
            {
                result.message = "转链失败";
                result.reason = $"{response.SubErrMsg}";

                _ = new LoggerLibrary("endpoint", "tbk_dg")
                    .Info(content, result.reason)
                    .SaveAsync();

                result.channel = TkChannelEnum.tb;
                result.link_type = LinkTypeEnum.unknown;
                result.success = false;
                return result;
            }

            string deeplink = response?.Data?.PageDeeplink;
            result.deeplink_url = deeplink;
            string h5Url = deeplink.GetContentPart("h5Url=", "&").UrlDecode();
            result.shortLinkurl = h5Url;
            return result;
        }

    }

}
