using System.Text;
using dodohold.core;
using System.Text.RegularExpressions;
using System.Net;
using System.Security.Cryptography;
using TencentCloud.Ecm.V20190719.Models;

namespace molilian.core
{
    public partial class AlimamaPlus
    {

        public async Task<TkActivityDTO> TkActivityAsync(TkActivityDTO result, CancellationToken cancellationToken = default)
        {
            TkDataDTO data = new();

            //format=json&sign_method=md5&adzone_id=116102700359&target_item=%7B%22item_id_list%22%3A+%5B%22top%3ApJZdQkbf2C6Zrxn0KxT5aAIptm-kPVnNrKI8PQmnQxXFk2%22%5D%7D&page_id_list=20150318020016140



            var plus = new AliyunPlus(_account.appkey, _account.appSecret);

            long.TryParse(_account.open_pid.Split('_')[^1], out long adzone);

            var response = await plus.TaobaoTbkDgGeneralLinkConvert(adzone, result.page_id, [result.item_id]);
            if (response == null)
            {
                _ = new LoggerLibrary("endpoint", "aliyun")
                    .Info(result.item_id, result.page_id)
                    .Info("response null")
                    .SaveAsync();
                result.channel = TkChannelEnum.tb;
                result.success = false;
                result.message = "fail";
                result.reason = "接口异常";
                return result;
            }
            Topsdk.Top.Defaultability.Domain.TaobaoTbkDgGeneralLinkConvertEventUrlList urlList = response?.Data?.EventUrlList?[0];

            //-----
            result.channel = data.channel;
            result.success = data.success;
            result.reason = data.reason;
            result.message = data.success ? "OK" : data.message;

            string cps_short_url = urlList?.LinkInfoDto?.CpsShortUrl;
            if (result.success && urlList != null && urlList.Code == null)
            {
                result.deeplink_url = GetDeeplink(cps_short_url);

                //todo 补充其他基础信息

                result = await aliyun_same(result.raw_item_id, result, cancellationToken);

                //if (data.couponAmount == 0)
                //{
                //    result.success = false;
                //    result.message = "没有优惠券";
                //    result.reason = "";
                //    result.deeplink_url = string.Empty;
                //}
                //else
                //{
                //    result.deeplink_url = data.deeplink_url;
                //    result.couponAmount = data.couponAmount;
                //    //result.couponEffectiveStartTime = data.couponEffectiveStartTime;
                //    //result.couponEffectiveEndTime = data.couponEffectiveEndTime;
                //    //result.itemId = data.itemId;
                //    //result.pic = data.pic;
                //}
            }
            return result;
        }

        public async Task<TkActivityDTO> aliyun_same(string item_id, TkActivityDTO result, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(item_id))
            {
                _ = new LoggerLibrary("endpoint", "aliyun")
                    .Info(item_id, "response null")
                    .SaveAsync();
                result.channel = TkChannelEnum.tb;
                result.success = false;
                result.message = "放弃转链";
                result.reason = "无效商品id";
                return result;
            }

            var plus = new AliyunPlus(_account.appkey2, _account.appSecret2);
            var response = await plus.GetProductInfoByIds(item_id, _account.open_pid2);
            if (response == null)
            {
                _ = new LoggerLibrary("endpoint", "aliyun")
                    .Info(item_id, "response null")
                    .SaveAsync();
                result.channel = TkChannelEnum.tb;
                result.success = false;
                result.message = "fail";
                result.reason = "接口异常";
                return result;
            }

            result.success = (bool)response.Body.Success;
            if (!result.success)
            {
                result.message = "fail";
                result.reason = $"{response.Body.Code}:{response.Body.Message}";

                _ = new LoggerLibrary("endpoint", "aliyun")
                    .Info(item_id, result.reason)
                    .SaveAsync();

                result.channel = TkChannelEnum.tb;
                result.success = false;
                return result;
            }

            if (response.Body.Data.Auctions.Count == 0)
            {
                _ = new LoggerLibrary("endpoint", "aliyun")
                    .Info(item_id, "response null")
                    .SaveAsync();
                result.channel = TkChannelEnum.tb;
                result.success = false;
                result.message = "result empty";
                result.reason = string.Empty;
                return result;
            }


            var data = response.Body.Data.Auctions[0].Result;
            result.maxCommission = decimal.TryParse(data.MaxCommission?.MaxCommissionRate?.ToString(), out var maxCommission) ? maxCommission : 0;
            result.zkFinalPrice = decimal.TryParse(data.ZkFinalPrice?.ToString(), out var zkFinalPrice) ? zkFinalPrice : 0;
            result.reservePrice = decimal.TryParse(data.ReservePrice?.ToString(), out var reservePrice) ? reservePrice : 0;
            result.title = data.Title?.ToString() ?? string.Empty;

            string picUrl = data.PicUrl?.ToString();
            if (!string.IsNullOrEmpty(picUrl) && picUrl.StartsWith("//")) picUrl = $"https:{picUrl}";
            result.picUrl = result.picUrl;

            result.shortTitle = data.ShortTitle?.ToString() ?? string.Empty;
            result.priceAfterCoupon = decimal.TryParse(data.PriceAfterCoupon?.ToString(), out var priceAfterCoupon) ? priceAfterCoupon : 0;
            result.commissionRate = decimal.TryParse(data.CommissionRate?.ToString(), out var commissionRate) ? commissionRate : 0;
            result.couponAmount = decimal.TryParse(data.CouponAmount?.ToString(), out var couponAmount) ? couponAmount : 0;

            result.estimatedCommission = result.priceAfterCoupon * result.commissionRate * 0.0001m;

            return result;
        }


    }
}
