using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dodohold.core;
using Spire.Pdf.Exporting.XPS.Schema;
using System.Xml.Linq;
using System.Net;
using TencentCloud.Mrs.V20200910.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Spire.Pdf.Graphics;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Channels;
using TencentCloud.Weilingwith.V20230427.Models;
using System.Threading;


namespace molilian.core
{
    public partial class UnionCouponCore
    {

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

        public static async Task<ActionResult> UnionCouponAsync(string content, string dplink, string channel, string ip, string oaid)
        {
            return channel switch
            {
                "jd" => await JdCouponAsync(content, dplink, ip, oaid),
                "tb" => await TaobaoCouponAsync(content, dplink, ip, oaid),
                _ => await UnionCpsCore.CpsCouponAsync(channel, ip, oaid),
            };
        }

        public static async Task<APIResult> TaobaoCouponAsync(string content, string dplink, string ip = "", string oaid = "")
        {
            AlimamaPlus alimama = null;
            content = content.UrlDecode();
            dplink = dplink.UrlDecode();
            UnionCouponDTO result = new()
            {
                channel = TkChannelEnum.tb,
                rawContent = content,
                rawContent2 = dplink,
                end_point = _end_point,
                ip = ip,
                oaid = oaid
            };

            content = AlimamaPlus.FakeItemUrl(content, dplink);

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

            try
            {
                string reason;
                if (AlimamaPlus.FilterRiskLink(ip, oaid, content, out reason) ||
                    AlimamaPlus.ShouldIgnoreRequest(ip, oaid, out reason))
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = reason;
                    _ = TkLogCore.CouponLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.message,
                        result.reason,
                        channel = result.channel.ToString(),
                    });
                }

                var account = TkPoolCore.GetOne(TkPoolCore.TkAction.coupon);
                if (account == null)
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "没有匹配账号";
                    _ = TkLogCore.CouponLogAsync(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.UnionCoupon2Async(content, 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(content)
                        .Info(ex.Message, ex.StackTrace)
                        .SaveAsync();

                    NotifyCore.Notify(new NifyMessage
                    {
                        message = $"【转链异常TB】\n{content}\n\n{ex.Message}\n{ex.StackTrace}",
                        priority = NifyMessagePriority.high,
                        tags = ["red_circle"]
                    });
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "转链接口异常";
                }
            }
            _ = TkLogCore.CouponLogAsync(result, alimama);
            if (!result.success)
            {
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                    channel = result?.channel.ToString(),
                });
            }
            int couponAmount = (int)result.couponAmount * 100;
            return new APIResult(new
            {
                result.success,
                result.message,
                channel = result?.channel.ToString(),
                result?.itemId,
                couponAmount,
                result?.deeplink_url,
                result?.pic,
                result?.couponEffectiveStartTime,
                result?.couponEffectiveEndTime,
            });
        }

        public static async Task<APIResult> JdCouponAsync(string content, string dplink, string ip, string oaid)
        {
            content = content.UrlDecode();
            dplink = dplink.UrlDecode();
            UnionCouponDTO result = new()
            {
                channel = TkChannelEnum.jd,
                rawContent = content,
                rawContent2 = dplink,
                end_point = _end_point,
            };
            if (string.IsNullOrEmpty(content))
            {
                content = dplink.Replace("taobao://", "https://");
            }
            if (string.IsNullOrEmpty(content))
            {
                result.success = false;
                result.message = "放弃转链";
                result.reason = "无效的参数";
                result.rawContent = content;
                _ = TkLogCore.CouponLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.reason,
                    result.message,
                    channel = result.channel.ToString(),
                });
            }

            try
            {
                var config = TkConfigCore.Get();
                if (JdUnionPlus.ShouldIgnoreRequest(config, ip, oaid, out string reason))
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = reason;
                    _ = TkLogCore.CouponLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.reason,
                        result.message,
                        channel = result.channel.ToString(),
                    });
                }

                var api = DataokeCore.GetOne();
                if (api == null)
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "没有匹配账号";
                    result.rawContent = content;
                    _ = TkLogCore.CouponLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.reason,
                        result.message,
                        channel = result.channel.ToString(),
                    });
                }

                var account = JdPoolCore.GetOne();
                if (account == null)
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "没有匹配账号";
                    _ = TkLogCore.CouponLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.reason,
                        result.message,
                        channel = result.channel.ToString(),
                    });
                }
                result = await JdUnionPlus.JdCouponAsync(account, api, content, result);
                if (result.success && result.couponAmount == 0)
                {
                    result.success = false;
                    result.message = "没有优惠券";
                    result.reason = "";
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("was canceled"))
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "请求超时";
                }
                else
                {
                    _ = new LoggerLibrary("unionCoupon", "jd_error")
                        .Info(ip, oaid)
                        .Info(content)
                        .Info(ex.Message, ex.StackTrace)
                        .SaveAsync();
                    NotifyCore.Notify(new NifyMessage
                    {
                        message = $"【转链异常JD】\n{content}\n\n{ex.Message}\n{ex.StackTrace}",
                        priority = NifyMessagePriority.high,
                        tags = ["red_circle"]
                    });
                    result.success = false;
                    result.message = "内部错误";
                    result.reason = "转链接口异常";
                }
            }
            _ = TkLogCore.CouponLogAsync(result);
            if (!result.success)
            {
                return new APIResult(new
                {
                    result.success,
                    result.reason,
                    result.message,
                    channel = result?.channel.ToString(),
                });
            }
            int couponAmount = (int)(result.couponAmount * 100);
            return new APIResult(new
            {
                result.success,
                result.message,
                channel = result?.channel.ToString(),
                result?.itemId,
                couponAmount,
                result?.deeplink_url,
                result?.pic,
                result?.couponEffectiveStartTime,
                result?.couponEffectiveEndTime,
            });
        }

    }

}
