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 Dataoke;
using Google.Protobuf.WellKnownTypes;
using System.Diagnostics;
using System.Text.Json;
using TencentCloud.Tcm.V20210413.Models;
using System.Security.Cryptography;
using System.Data;
using System.Threading.Channels;


namespace molilian.core
{
    public partial class TkOrderTrackingCore
    {
        public static void SaveLinkSummary(TkDataDTO item)
        {
            //清洗数据
            item.content = null;
            item.rawContent = null;
            item.rawContent2 = null;

            TkDataDTO newData = new()
            {
                channel = item.channel,
                ip = item.ip,
                oaid = item.oaid,
                itemId = item.itemId,
                itemName = item.itemName,
                taoToken = item.taoToken,
                shortLinkurl = item.shortLinkurl,
                deeplink_url = item.deeplink_url,
                create_time = item.create_time,
            };

            var config = TkConfigCore.Get();
            var ttl = config.fake_click_ttl * 3600;
            string cacheKey = $":cache:order_summary:{item.accountId}:{item.itemId}";
            RedisHelper.Set(cacheKey, newData, ttl);

            cacheKey = $":cache:order_summary:{item.accountId}:{item.itemName}";
            RedisHelper.Set(cacheKey, newData, ttl);
        }

        public static TkDataDTO GetLinkSummary(int accountId, string itemId, string itemTitle)
        {
            var result = EndPointCore.ProcessEndPointNodes<TkDataDTO>(node =>
            {
                if (!node.is_public_api) return null;
                if (string.IsNullOrEmpty(node.redis_server)) return null;

                var redis = RedisClientManager.GetRedisClient(node.redis_server);
                if (!string.IsNullOrEmpty(itemId))
                {
                    string cacheKey = $":cache:order_summary:{accountId}:{itemId}";
                    var result = redis.Get<TkDataDTO>(cacheKey);
                    if (result != null) return result;
                }
                if (!string.IsNullOrEmpty(itemId))
                {
                    string cacheKey = $":cache:order_summary:{accountId}:{itemTitle}";
                    var result = redis.Get<TkDataDTO>(cacheKey);
                    if (result != null) return result;
                }
                return null;
            });
            return result.Count > 0 ? result[0] : null;
        }

        public static async void RemoveLinkSummary(int accountId, string itemId)
        {
            string cacheKey = $":cache:order_summary:{accountId}:{itemId}";
            await EndPointCore.ProcessEndPointNodesAsync(node =>
            {
                if (!node.is_public_api) return Task.CompletedTask;
                if (string.IsNullOrEmpty(node.redis_server)) return Task.CompletedTask;


                var redis = RedisClientManager.GetRedisClient(node.redis_server);
                redis.Del(cacheKey);
                return Task.CompletedTask;
            });
        }

        public static bool MatchOrder(TkPoolDTO account, TkOrderDetailDTO item, IDbConnection conn)
        {
            if (item.tbPaidTime < DateTime.Now.AddDays(-1)) return false;

            var summary = GetLinkSummary(item.accountId, item.itemId, item.itemTitle);
            if (summary == null) return false;


            var config = TkConfigCore.Get();
            Random rand = new();
            int click_num = rand.Next(config.fake_click_min, config.fake_click_max + 1);

            if (account.fake_click_min != 0 && account.fake_click_max != 0)
                click_num = rand.Next(account.fake_click_min, account.fake_click_max + 1);

            DateTime paidTime = item.tbPaidTime;
            if (paidTime < summary.create_time) return false;

            int minutes = paidTime.Minute / 10 * 10;
            DateTime rounded = new(paidTime.Year, paidTime.Month, paidTime.Day, paidTime.Hour, minutes, 0);
            string batchId = rounded.ToString("yyyyMMddHHmm");

            string accountName = item.accountName;

            string shortLinkUrl = summary.shortLinkurl;
            string deeplinkUrl = summary.deeplink_url;
            switch (account.fake_click_link_type)
            {
                case FakeClickLinkType.Deeplink:
                    shortLinkUrl = string.Empty;
                    break;
                case FakeClickLinkType.H5:
                    deeplinkUrl = string.Empty;
                    break;
            }

            DateTime expTime = item.tbPaidTime.Hour >= 21 ? item.tbPaidTime.AddHours(3) : item.tbPaidTime.Date.AddDays(1);
            var data = new TkOrderTrackingDTO()
            {
                channel = summary.channel,
                accountId = item.accountId,
                accountName = accountName,
                batchId = batchId,
                ip = summary.ip,
                oaid = summary.oaid,
                itemId = summary.itemId,
                itemName = summary.itemName,
                taoToken = summary.taoToken,
                shortLinkUrl = shortLinkUrl,
                deeplinkUrl = deeplinkUrl,

                tradeId = item.tradeId,
                tradeParentId = item.tradeParentId,

                create_time = summary.create_time,
                click_time = item.clickTime,
                paid_time = item.tbPaidTime,

                exp_time = expTime,
                click_num = click_num,
            };

            conn.Replace(data);
            RemoveLinkSummary(item.accountId, item.itemTitle);
            return true;
        }
    }
}
