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 COSXML.Network;
using System.Linq;
using static dodohold.core.ZTOExpress.CreateOrderArgs;
using MySqlX.XDevAPI;

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

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

        /// <summary>
        /// oppo调用
        /// </summary>
        /// <param name="s">正文</param>
        /// <param name="c">渠道。tb/jd</param>
        /// <param name="a">分配的客户端账号</param>
        /// <param name="t">11位时间戳</param>
        /// <param name="sign">签名</param>
        /// <param name="ip">客户的IP</param>
        /// <param name="oaid">客户的唯一ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> getLink([FromBody] JsonElement form, [FromQuery] string a = "", [FromQuery] int t = 0, [FromQuery] string sign = "")
        {
            var channel = form.Read("c", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);

#if DEBUG
#else

            //验证签名
            if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(sign))
            {
                return new APIResult(new { success = false, message = "验证错误" }, APIResultCodeEnum.Unauthorized);
            }

            DateTime time1 = t.Convert2Datetime();
            if (time1 < DateTime.Now.AddMinutes(-10))
            {
                return new APIResult(new { success = false, message = "验证错误2" }, APIResultCodeEnum.Unauthorized);
            }

            var account = ApiAccountCore.GetOne(a);
            if (account == null)
            {
                return new APIResult(new { success = false, message = "验证错误3" }, APIResultCodeEnum.Unauthorized);
            }
            string app_sign = $"{account.api_secret}@{t}".MD5();
            if (sign != app_sign)
            {
                return new APIResult(new { success = false, message = "验证错误4" }, APIResultCodeEnum.Unauthorized);
            }


#endif
            return await UnionCPSCore.GetLinkAsync(channel, ip, oaid);
        }

        [HttpPost]
        public async Task<ActionResult> unsafeGetLink([FromBody] JsonElement form)
        {
            var channel = form.Read("c", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
#if DEBUG
            ip = "127.0.0.1";
            oaid = "test-oaid";
#endif
            return await UnionCPSCore.GetLinkAsync(channel, ip, oaid);
        }


    }
}