using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Ocsp;
using System.Text.Json;
using System.Runtime.InteropServices;
using System.Net;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authentication;
using TencentCloud.Ecm.V20190719.Models;
using Dataoke;
using System.Web;

namespace molilian.api.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class H5Controller : ControllerBase
    {

        protected IHttpContextAccessor _accessor;
        public H5Controller(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }


        [HttpGet]
        public ActionResult sign()
        {
            string referer = _accessor.HttpContext.Request.Referer();

            var api = DataokeCore.GetOne(referer);
            if (api == null)
            {
                return new APIResult(new
                {
                    success = false,
                    message = "没有可用签名账户"
                });
            }

            int nonce;
            string timer;
            DtkApp app = new(api.app_key, api.app_secret);
            string sign = app.MakeSign(out nonce, out timer);
            string sign_url = $"appKey={api.app_key}&nonce={nonce}&signRan={sign}&timer={timer}";

            return new APIResult(new
            {
                success = true,
                message = "ok",
                sign_url
            });
        }

        [HttpPost]
        public ActionResult ddsign([FromBody] JsonElement form)
        {

            var api = PddPoolCore.GetOne(PddUnionWorkMode.SiteApi);
            if (api == null)
            {
                return new APIResult(new
                {
                    success = false,
                    message = "没有可用签名账户"
                });
            }

            string ts = DateTime.Now.Convert2UnixTimestamp().ToString();
            string url = $"https://gw-api.pinduoduo.com/api/router";

            Dictionary<string, string> args = new Dictionary<string, string>
            {
                { "client_id", api.app_key },
                { "timestamp", ts }
            };

            // 提取客户端的业务参数并排除 "client_id" 和 "timestamp"
            foreach (JsonProperty prop in form.EnumerateObject())
            {
                if (prop.Name != "client_id" && prop.Name != "timestamp")
                {
                    args.Add(prop.Name, prop.Value.GetString());
                }
            }


            ////其他业务参数接收客户端的form，记得排除client_id 和 timestamp
            //args.Add("type", "pdd.ddk.goods.recommend.get");
            //args.Add("data_type", "JSON");
            //args.Add("custom_parameters", "5");


            args = PddUnionPlus.GenerateSignature(api, args);
            string queryString = string.Join("&", args.Select(kv => $"{HttpUtility.UrlEncode(kv.Key)}={HttpUtility.UrlEncode(kv.Value)}"));
            string sign_url = $"{url}?{queryString}";
            return new APIResult(new
            {
                success = true,
                message = "ok",
                sign_url
            });

            //WebClientUtility client = new WebClientUtility();
            //var response = client.Request(url);
            //var body = response.Body();
            //return Content(body);
        }
    }
}