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;
using System.Web;
using TencentCloud.Scf.V20180416.Models;


namespace molilian.core
{
    public partial class ReduPlus
    {
        string _app_key;
        string _app_secret;
        string _base_url = "http://api-service.868676.cn/openapi/";
        public ReduPlus(string base_url, string app_key, string app_secret)
        {
            _base_url = base_url;
            _app_key = app_key;
            _app_secret = app_secret;
            //#if DEBUG
            //            _base_url = "http://api-service.868676.cn/openapi/";
            //            _app_key = "10024";
            //            _app_secret = "dbbb7b5a216a30e7f7a0b8d9d18a13e8";
            //#endif
        }

        private string AddSignToQueryString(Dictionary<string, object> param, string appSecret = "")
        {
            param.Remove("sign");

            var sortedParam = param.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);

            sortedParam["app_secret"] = appSecret;

            var paramsVal = new List<string>();
            foreach (var entry in sortedParam)
            {
                string value;
                if (entry.Value is Dictionary<string, object> || entry.Value is List<object>)
                {
                    value = JsonSerializer.Serialize(entry.Value);
                }
                else
                {
                    value = entry.Value.ToString();
                }

                paramsVal.Add($"{entry.Key}={value}");
            }

            var strToSign = string.Join("&", paramsVal);

            string sign = strToSign.MD5(false, false);
            param["sign"] = sign;

            var queryParams = param.Select(entry =>
            {
                string value = entry.Value is Dictionary<string, object> || entry.Value is List<object>
                    ? JsonSerializer.Serialize(entry.Value)
                    : entry.Value.ToString();

                return $"{HttpUtility.UrlEncode(entry.Key)}={HttpUtility.UrlEncode(value)}";
            });
            return string.Join("&", queryParams);
        }



        public async Task<string> RequestAsync(string path, Dictionary<string, object> param, CancellationToken cancellationToken = default)
        {
            int timestamp = DateTime.Now.Convert2UnixTimestamp();

            param.Add("app_id", _app_key);
            param.Add("time", timestamp);
            var queryParams = AddSignToQueryString(param, _app_secret);
            string url = $"{_base_url}{path}?{queryParams}";



            var log = new LoggerLibrary("redu", path.Replace("/", "_")).Info(queryParams);
            var client = new WebClientUtility();
            client.SetContentType("application/json");
            var response = await client.RequestAsync(url, "GET", cancellationToken);
            var body = response.Body();
            _ = log.Info(body).SaveAsync();
            return body;
        }

        public async Task<JsonElement> DouyinParse(string command, CancellationToken cancellationToken = default)
        {
            string path = "douyin/goodsShare";
            Dictionary<string, object> param = [];
            if (decimal.TryParse(command, out _))
            {
                param.Add("product_id", command);
            }
            else
            {
                param.Add("command", command);
            }
            var body = await RequestAsync(path, param, cancellationToken);
            var root = body.Convert2JsonElement();
            return root;
        }
        public async Task<JsonElement> KuaishouParse(string command, CancellationToken cancellationToken = default)
        {
            string path = "kuaishou/goodsShare";
            Dictionary<string, object> param = [];
            if (decimal.TryParse(command, out _))
            {
                param.Add("product_id", command);
            }
            else
            {
                param.Add("command", command);
            }
            var body = await RequestAsync(path, param, cancellationToken);
            var root = body.Convert2JsonElement();
            return root;
        }

    }
}
