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;
using static dodohold.core.ZTOExpress.CreateOrderArgs;


namespace molilian.core
{
    public partial class UnionCPSCore
    {

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

        public static async Task<ActionResult> GetLinkAsync(string channel, string ip, string oaid)
        {
            return channel switch
            {
                "eleme" => await EleAsync(ip, oaid),
                "meituan" => await MeituanAsync(ip, oaid),
                _ => await InvalidChannelAsync(ip, oaid),
            };
        }

        private static async Task<APIResult> InvalidChannelAsync(string ip, string oaid)
        {
            UnionCpsDTO result = new()
            {
                channel = CpsChannelEnum.invalid,
                end_point = _end_point,
                ip = ip,
                oaid = oaid
            };

            result.success = false;
            result.message = "无效渠道";
            _ = TkLogCore.CpsLogAsync(result);
            return new APIResult(new
            {
                result.success,
                result.message,
                channel = result.channel.ToString(),
            });
        }

        public static bool ShouldIgnoreRequest(TkConfigDTO config, CpsChannelEnum channel, string ip, string oaid, out string reason)
        {
            reason = string.Empty;
            try
            {
                // IP和流量控制
                string ignorePercentageCity = config.cpsIgnorePercentageCity;
                string? ipInfo = IP2RegionPlus.Search(ip);
                if (AlimamaPlus.IgnoreRegionIncluded(ignorePercentageCity, ipInfo, out string regionInfo))
                {
                    reason = $"地区控制：{regionInfo}";
                    return true;
                }

                int limit_num = config.cps_limit_per_ip_24h;
                if (limit_num > 0)
                {
                    int num = TkLogCore.getClientRequestTotalByIp(channel, ip);
                    if (num > limit_num)
                    {
                        reason = "IP控制";
                        return true;
                    }
                    num = TkLogCore.getClientRequestTotalByOAID(channel, oaid);
                    if (num > limit_num)
                    {
                        reason = "OAID控制";
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                reason = "配置异常";
            }
            return false;
        }
        public static async Task<APIResult> EleAsync(string ip, string oaid)
        {
            UnionCpsDTO result = new()
            {
                channel = CpsChannelEnum.eleme,
                end_point = _end_point,
                ip = ip,
                oaid = oaid
            };


            var config = TkConfigCore.Get();

            //============================== 放弃转链-地区过滤 ==============================
            if (ShouldIgnoreRequest(config, result.channel, ip, oaid, out string reason))
            {
                result.success = false;
                result.message = "流量控制";
                result.reason = reason;
                _ = TkLogCore.CpsLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                    channel = result.channel.ToString(),
                });
            }

            result.deeplink_url = "eleme://web?action=ali.open.nav&module=h5&packageName=me.ele&bc_fl_src=locallife_wtzt_0-0-ADGROUPID-__REQID__-2&url=https%3A%2F%2Ffc.ele.me%2Fa%2FMWJhZDM1OTY5ZTg5MTFlYzllYWEwMDE2M2UxM2FkMTE%3D%3Fscene%3D8d6c64c7f62c48ea83e88383530edd2b%26o2i_1st_clk%3D__CLICK_ID__&fastmode=1";
            result.success = true;
            result.message = "OK";

            _ = TkLogCore.CpsLogAsync(result);
            return new APIResult(new
            {
                result.success,
                result.message,
                result.deeplink_url,
                channel = result.channel.ToString(),
            });
        }

        public static async Task<APIResult> MeituanAsync(string ip, string oaid)
        {
            UnionCpsDTO result = new()
            {
                channel = CpsChannelEnum.meituan,
                end_point = _end_point,
                ip = ip,
                oaid = oaid
            };


            var config = TkConfigCore.Get();

            //============================== 放弃转链-地区过滤 ==============================
            if (ShouldIgnoreRequest(config, result.channel, ip, oaid, out string reason))
            {
                result.success = false;
                result.message = "流量控制";
                result.reason = reason;
                _ = TkLogCore.CpsLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                    channel = result.channel.ToString(),
                });
            }

            result.deeplink_url = "imeituan://www.meituan.com/web?lch=cps:waimai:3:0f860c7cc90569fb14bc1fc4a4d8c057:001:33:445029&url=https%3A%2F%2Fclick.meituan.com%2Ft%3Ft%3D1%26c%3D2%26p%3DnvaI7r5zjmJB";
            result.success = true;
            result.message = "OK";

            _ = TkLogCore.CpsLogAsync(result);
            return new APIResult(new
            {
                result.success,
                result.message,
                result.deeplink_url,
                channel = result.channel.ToString(),
            });
        }

    }

}
