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 System.Text.RegularExpressions;
using Org.BouncyCastle.Ocsp;
using System.Diagnostics;
using TencentCloud.Fmu.V20191213.Models;
using Microsoft.VisualBasic;
using System.Text.Json;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Security.Cryptography;
using System.Security.Policy;
using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.Components;
using Org.BouncyCastle.Pqc.Crypto.Ntru;


namespace molilian.core
{
    public partial class DyUnionPlus
    {
        string _app_key;
        string _app_secret;
        const string _base_url = "https://ecom.pangolin-sdk-toutiao.com";
        public DyUnionPlus(string app_key, string app_secret)
        {
            _app_key = app_key;
            _app_secret = app_secret;
        }

        public string _sign(string req_id, int timestamp, string data)
        {
            string signStr = $"app_id={_app_key}&data={data}&req_id={req_id}&timestamp={timestamp}{_app_secret}";
            return signStr.MD5();
        }


        public async Task<DyDataDTO> ParseAsync(string content, DyDataDTO result, CancellationToken cancellationToken = default)
        {
            string path = "/command_parse";
            string post = new { command = content, share_type = new int[] { 1, 3, 5 } }.Convert2Json();

            var body = await RequestAsync(path, post, cancellationToken);
            //{"code":500000,"desc":"command parse error:商品没有加入精选联盟"}
            //{"code":500000,"desc":"command parse error:商家已设置该商品仅指定作者可推广，请您更换其他商品"}
            //{"code":0,"desc":"","data":{"command_type":1,"product_info":{"product_id":3660263780149019445,"share_info":{"deeplink":"snssdk1128://lynxview?surl=https%3A%2F%2Flf-dy-sourcecdn-tos.bytegecko.com%2Fobj%2Fbyte-gurd-source%2F1325%2Fgecko%2Fresource%2Ffe_lynx_distribution_landing%2Fapp%2Ftemplate.js&hide_nav_bar=1&hide_status_bar=1&token=ijRcTEAk&distribution_ab=1&alliance_distribution=1","share_command":"","zlink":"","share_link":""}}}}
            var root = body.Convert2JsonElement();
            int code = root.Read<int>("code");
            if (code == 0)
            {
                var share_info = result.link_type switch
                {
                    LinkTypeEnum.live => root.ElementRead("data").ElementRead("live_info").ElementRead("share_info"),
                    _ => root.ElementRead("data").ElementRead("product_info").ElementRead("share_info"),
                };

                result.deeplink_url = share_info.Read<string>("deeplink");
                result.taoToken = share_info.Read<string>("share_command");
                result.shortLinkurl = share_info.Read<string>("share_link");
                result.success = true;
                result.message = "OK";
            }
            else
            {
                //{"code":500000,"desc":"command parse error:商品没有加入精选联盟"}
                //{"code":500000,"desc":"command parse error:商家已设置该商品仅指定作者可推广，请您更换其他商品"}
                string desc = root.Read<string>("desc", string.Empty);
                desc = desc.Replace("command parse error:", "");
                result.reason = desc;
                result.success = false;
                result.message = "转链失败";
                result.reason = "";
                result.success = false;
            }
            return result;
        }


        public async Task<string> AggregateH5Async(string material_id, CancellationToken cancellationToken = default)
        {
            //string path = "/aggregate/h5";
            //string post = new { material_id }.Convert2Json();


            //material_id = "1796636629603354";
            //string path = "/life/product/detail";
            //string post = new
            //{
            //    product_id_list = new string[] { material_id },
            //}.Convert2Json();

            string path = "/life/product/search";
            string post = new
            {
                keyword = material_id,
            }.Convert2Json();


            var body = await RequestAsync(path, post, cancellationToken);
            return body;
        }

        public async Task<string> RequestAsync(string path, string data, CancellationToken cancellationToken = default)
        {
            int timestamp = DateTime.Now.Convert2UnixTimestamp();
            string req_id = Guid.NewGuid().ToString();

            var sign = _sign(req_id, timestamp, data);

            string url = $"{_base_url}{path}";
            var postData = new
            {
                app_id = _app_key,
                timestamp,
                sign,
                req_id,
                data
            }.Convert2Json();

            var log = new LoggerLibrary("pangolin", path.Replace("/", "_")).Info(postData);
            var client = new WebClientUtility();
            client.SetContentType("application/json");
            client.Post(postData);
            var response = await client.RequestAsync(url, "POST", cancellationToken);
            var body = response.Body();
            _ = log.Info(body).SaveAsync();

            //var root = body.Convert2JsonElement();
            return body;
        }

        public static bool ShouldIgnoreRequest(string ip, string oaid, out string reason)
        {
            reason = string.Empty;
            try
            {
                var config = TkConfigCore.Get();

                int ignorePercentage = config.jdIgnorePercentage;
                if (ignorePercentage == 0) return false;
                Random random = new Random();
                var randomValue = (decimal)random.Next(0, 100);
                bool result = randomValue <= ignorePercentage; // 如果生成的随机数小于忽略百分比，则返回 true，表示需要忽略请求
                if (result) reason = "流量控制";
                return result;

            }
            catch (Exception ex)
            {
                reason = $"配置异常";
                return true;
            }
        }


    }
}
