using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using Spire.Xls.Charts;
using TencentCloud.Bsca.V20210811.Models;

namespace molilian.core
{
    public partial class TkActivityCore
    {

        private static string _end_point;
        static TkActivityCore()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }


        public static async Task<ActionResult> ParseAsync(string page_id, string prefix, string item_id, string strategy_id, string ip, string oaid)
        {
            AlimamaPlus alimama = null;

            TkActivityDTO result = new()
            {
                channel = TkChannelEnum.tb,
                page_id = page_id,
                raw_item_id = item_id,
                item_id = $"{prefix}:{item_id}",
                end_point = _end_point,
                ip = ip,
                oaid = oaid
            };


            if (string.IsNullOrEmpty(page_id) || string.IsNullOrEmpty(item_id))
            {
                result.success = false;
                result.message = "放弃转链";
                result.reason = "无效的参数";
                _ = TkLogCore.TkActivityLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.reason,
                    result.message,
                    channel = result.channel.ToString(),
                });
            }

            try
            {
                string reason;
                UnionParseRequest request = new()
                {
                    Ip = ip,
                    Oaid = oaid,
                    RiskStrategy = string.Empty,
                    LaunchScene = 0,
                };
                if (AlimamaPlus.ShouldIgnoreRequest(request, out reason))
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = reason;
                    _ = TkLogCore.TkActivityLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.message,
                        result.reason,
                        channel = result.channel.ToString(),
                    });
                }

                var account = await TkPoolCore.GetOneAsync(TkPoolCore.TkAction.activity, false, string.Empty, 0, string.Empty, strategy_id);
                if (account == null)
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "没有匹配账号";
                    _ = TkLogCore.TkActivityLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.message,
                        result.reason,
                        channel = result.channel.ToString(),
                    });
                }
                result.accountId = account.id;
                result.accountName = account.name;
                alimama = new AlimamaPlus(account);
                result = await alimama.TkActivityAsync(result);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("was canceled"))
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "请求超时";
                }
                else
                {
                    _ = new LoggerLibrary("unionCoupon", "tb_error")
                        .Info(ip, oaid)
                        .Info(page_id, result.item_id)
                        .Info(ex.Message, ex.StackTrace)
                        .SaveAsync();

                    NotifyCore.Notify(new NifyMessage
                    {
                        message = $"【转链异常TB】\n{page_id}\t{result.item_id}\n\n{ex.Message}\n{ex.StackTrace}",
                        priority = NifyMessagePriority.high,
                        tags = ["red_circle"]
                    });
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "转链接口异常";
                }
            }
            _ = TkLogCore.TkActivityLogAsync(result);
            if (!result.success)
            {
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                    channel = result?.channel.ToString(),
                });
            }
            return new APIResult(new
            {
                result.success,
                result.message,
                channel = result?.channel.ToString(),
                result.deeplink_url,
                input_item_id = item_id,
                input_page_id = page_id,
                result.estimatedCommission,
                result.maxCommission,
                price = result.reservePrice,
                result.reservePrice,
                result.title,
                result.picUrl,
                result.shortTitle,
                result.priceAfterCoupon,
                result.commissionRate,
                result.couponAmount,
                exposeTracks = $"https://api.molilian.com/tracks/track?track_id=11&unique_id={item_id}",
                clickTracks = $"https://api.molilian.com/tracks/track?track_id=12&unique_id={item_id}"
            });
        }
    }
}
