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.Xml.Linq;
using Mysqlx.Crud;
using ZstdSharp.Unsafe;
using YunhuiKit;
using COSXML.Network;
using System.Threading.Channels;
using TencentCloud.Apm.V20210622.Models;
using static QRCoder.PayloadGenerator;
using TencentCloud.Tcm.V20210413.Models;
using TencentCloud.Tione.V20211111.Models;
using TencentCloud.Cdn.V20180606.Models;
using static molilian.core.ApiReportCore;
using molilian.core.PushDataReport;
using Org.BouncyCastle.Asn1.Ocsp;
using TencentCloud.Cms.V20190321.Models;


namespace molilian.core
{

    public partial class PushDataReportCore
    {
        private PushDataReportPush plus;
        public PushDataReportCore()
        {
            plus = new PushDataReportPush();
        }
        public bool FillReportData(DateTime date)
        {
            return true;
        }

        public async Task<int> FillData(DateTime reportDatetime)
        {
            int count = 0;
            count += await FillToolData(reportDatetime);
            count += await FillParseData(reportDatetime);
            count += await FillDeeplinkData(reportDatetime);
            count += await FillCpsCouponData(reportDatetime);
            return count;
        }
        public async Task<int> FillParseData(DateTime reportDatetime)
        {
            var conn = DBContext.GetOpenConnection();
            try
            {
                var platform_list = new List<DeeplinkParseRuleDTO>()
                {
                    new() { channel_id = 0,  push_channel_id = 1, channel_name = "tb" },
                    new() { channel_id = 0,  push_channel_id = 1, channel_name = "tbdp" },
                    new() { channel_id = 1, push_channel_id = 13, channel_name = "jd" },
                    new() { channel_id = 3,  push_channel_id = 9, channel_name = "pdd" }
                };

                int count = 0;
                foreach (var p in platform_list)
                {
                    int platform = p.channel_id;
                    string channel_name = p.channel_name;


                    int data_type = 1; //转链数据
                    int sub_type = 100000;
                    if ("tbdp".Equals(channel_name))
                    {
                        data_type = 3;
                        sub_type = 300002;
                    }
                    string filter = "`is_show`=@is_show AND data_type=@data_type AND platform=@platform AND report_date=@report_date";

                    string orderBy = "report_date DESC";

                    var list = new DBContext.Table("api_call_report_dailys")
                                .Where(filter, new { is_show = true, platform, data_type, report_date = reportDatetime.Date })
                                .Order(orderBy)
                                .Select<RecordDTO>().ToList();

                    foreach (var data in list)
                    {
                        //描述：0:全分销类型;-1:各分销类型，1:goods 2: live 3:video 4: profile 5: unknown

                        //int[] distributiontype_list = [1, 2, 3, 4, 5, 6, 7];

                        //foreach (var distribution in distributiontype_list)
                        {
                            int distribution = 0;

                            filter = " report_date=@report_date AND platform=@platform AND distribution=@distribution AND type=@data_type AND sub_type=@sub_type";
                            var exist = new DBContext.Table("push_data_report")
                                        .Get<PushDataReportDTO>(filter, new { report_date = reportDatetime.Date, platform = p.push_channel_id, distribution, data_type, sub_type });
                            if (exist != null && exist.status == 1) continue;



                            var item = new PushDataReportDTO();
                            item.report_date = reportDatetime.Date;
                            item.platform = p.push_channel_id;
                            item.platform_name = p.channel_name;
                            item.type = data_type;
                            item.sub_type = sub_type;
                            item.distribution = distribution;
                            item.req_count = data.total_count;
                            item.dp_transition_succ_count = data.success_count;

                            // pdd 商业化链接不回传oppo
                            if (p.push_channel_id == 9)
                            {
                                item.dp_transition_succ_count = 0;
                                item.transition_succ_count = 0;
                            }
                            item.click_count = data.uclk_pv;
                            item.click_user_count = data.uclk_uv;
                            item.order_count = data.eff_ord_num;
                            item.order_user_count = data.pay_ord_uv;
                            item.Gmv = data.eff_ord_amt;
                            item.income = data.eff_tk_disp_tfee;
                            conn.Replace<PushDataReportDTO>(item);
                            count++;
                        }
                    }
                }
                return count;
            }
            catch (Exception ex)
            {
                //暂时不记录日志
                return 0;
            }
        }

        public async Task<int> FillToolData(DateTime reportDatetime)
        {
            var conn = DBContext.GetOpenConnection();
            try
            {
                var list = new List<DeeplinkParseRuleDTO>()
                {
                    new() { push_channel_id = 7, channel_name = "bdpan" },
                    new() { push_channel_id = 8, channel_name = "wemeet" }
                };

                int count = 0;
                foreach (var deeplink in list)
                {
                    string accountName = $"{deeplink.channel_name}";
                    int all_total = await TkLogCore.GetTotalAsync($":parse_total:{deeplink.channel_name}:{reportDatetime:yyyyMMdd}");
                    int success_total = await TkLogCore.GetTotalAsync($":parse_total:{deeplink.channel_name}:success:{reportDatetime:yyyyMMdd}");

                    var item = new PushDataReportDTO();
                    item.report_date = reportDatetime.Date;
                    item.platform = deeplink.push_channel_id;
                    item.platform_name = deeplink.channel_name;
                    item.req_count = all_total;
                    item.dp_transition_succ_count = success_total;
                    conn.Replace<PushDataReportDTO>(item);
                    count++;
                }
                return count;
            }
            catch (Exception ex)
            {
                //暂时不记录日志
                return 0;
            }
        }
        public async Task<int> FillCpsCouponData(DateTime report_date)
        {

            var list = DeeplinkParseRuleCore.List();
            var conn = DBContext.GetOpenConnection();
            try
            {

                //  107 美团
                //  110 饿了么
                //tb/jd/eleme/meituan

                Dictionary<int, string> channels = [];
                channels.Add(107, "meituan");
                channels.Add(110, "eleme");

                int count = 0;
                foreach (var kv in channels)
                {

                    int platform = kv.Key;
                    string platform_name = kv.Value;
                    int type = 2;
                    int sub_type = 100001;

                    string cacheKey = $":cps_total:{kv.Value}:{report_date:yyyyMMdd}";
                    int req_count = await TkLogCore.GetTotalAsync(cacheKey);
                    if (req_count == 0) continue;

                    var update = new DBContext.Table("push_data_report");
                    update.Add("req_count", req_count);
                    update.Add("update_time", DateTime.Now);
                    update.Add("status", 3);

                    string filter = "report_date=@report_date AND platform=@platform AND type=@type AND sub_type=@sub_type";

                    var item = new DBContext.Table(conn, "push_data_report")
                        .Get<PushDataReportDTO>(filter, new { report_date, platform, type, sub_type });
                    if (item == null)
                    {
                        update.Add("create_time", DateTime.Now);
                        update.Add("report_date", report_date);
                        update.Add("platform", platform);
                        update.Add("platform_name", platform_name);
                        update.Add("type", type);
                        update.Add("sub_type", sub_type);
                        update.Create();
                        count++;
                    }
                    else
                    {
                        if (item.req_count < req_count)
                        {
                            var result = update.Where("id=@id", new { item.id }).Update();
                            count++;
                        }
                    }
                }
                return count;
            }
            catch (Exception ex)
            {
                //暂时不记录日志
                return 0;
            }
        }


        public async Task<int> FillDeeplinkData(DateTime reportDatetime)
        {

            var list = DeeplinkParseRuleCore.List();
            var conn = DBContext.GetOpenConnection();
            try
            {
                int count = 0;
                foreach (var deeplink in list)
                {
                    if (deeplink.push_channel_id == 0) continue;

                    //先跳过百度网盘的数据处理
                    if (deeplink.channel_id == 102) continue;

                    string[] flags = ["none", "home", "success", "fail"];
                    int all_total = 0;
                    int success_total = 0;
                    foreach (var dp_flag in flags)
                    {
                        string accountName = $"dp_{dp_flag}:{deeplink.channel_name}";
                        all_total += await TkLogCore.GetTotalAsync($":parse_total:{accountName}:{reportDatetime:yyyyMMdd}");
                        if ("success".Equals(dp_flag))
                        {
                            success_total = await TkLogCore.GetTotalAsync($":parse_total:{accountName}:success:{reportDatetime:yyyyMMdd}");
                        }
                    }

                    var item = new PushDataReportDTO();
                    item.report_date = reportDatetime.Date;
                    item.platform = deeplink.push_channel_id;
                    item.platform_name = deeplink.channel_name;
                    item.req_count = all_total;
                    item.dp_transition_succ_count = success_total;
                    conn.Replace<PushDataReportDTO>(item);
                    count++;
                }
                return count;
            }
            catch (Exception ex)
            {
                //暂时不记录日志
                return 0;
            }
        }

        public async Task<int> PushReportData(DateTime report_date, bool repush = false, CancellationToken cancellationToken = default)
        {
            string filter = "report_date=@report_date";
#if DEBUG
            filter += " AND sub_type=100000 AND platform IN (1,9,13)";
#endif
            if (!repush)
            {
                filter += " AND status=@status";
            }

            var list = new DBContext.Table("push_data_report")
                .Where(filter, new { report_date = report_date.Date, status = 0 })
                .Select<PushDataReportDTO>();

            int count = 0;
            foreach (var item in list)
            {
                //2026-06-05 淘宝 只生成不推送
                if (item.sub_type == 100000 && item.platform == 1) continue;

                count++;
                item.request_id = Guid.NewGuid().ToString();
                var response = await plus.PushReportData(item, cancellationToken);

                bool status = response.code == 200;
                if (!status)
                {
                    item.request_id = $"{item.request_id}:{response.message}";
                }

                new DBContext.Table("push_data_report")
                    .Add("status", status)
                    .Add("request_id", item.request_id)
                    .Add("last_push_time", DateTime.Now)
                    .Where("id=@id", new { item.id })
                    .Update();
            }
            return count;
        }

        public int NotifyNotPushed(CancellationToken cancellationToken = default)
        {
            DateTime report_date = DateTime.Now.Date.AddDays(-1);
            string filter = "report_date=@report_date and status=@status";

            var list = new DBContext.Table("push_data_report")
                .Where(filter, new { report_date = report_date.Date, status = 0 })
                .Select<PushDataReportDTO>();

            int count = list.Count();

            if (count > 0)
            {
                NotifyCore.Notify(new NifyMessage
                {
                    message = $"【数据回传】未推送警告\n当日还有：{count} 条数据未推送",
                    priority = NifyMessagePriority.high,
                    tags = ["red_circle"]
                });
                _ = NotifyCore.QYWeixinPushNotifyAsync("【数据回传】未推送警告", $"当日还有：{count}条数据未推送");
            }
            return count;
        }
    }
}