using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("EncryptionScript/密钥")]
public class EncryptionScript : MonoBehaviour
{
    public string encryptionKey = "defaultKey";
    private string url_key = "http://172.16.1.253:8087/priceRule.json";
    [SerializeField] private string inputKey = null;
    /// <summary>
    /// 密钥是否过期
    /// </summary>
    public static bool isOverdueKey = true;
    /// <summary>
    /// 密钥运行时间
    /// </summary>
    private float elapsedTime = 0;
    /// <summary>
    /// 密钥有效时间
    /// </summary>
    private float averageSecondsInMonth = 5270400f;

    private /*async*/ void Start()
    {
        //await GetKey();//读取JSON获取密钥
        encryptionKey = (KeyGenerator.GenerateKey("123"));
        averageSecondsInMonth = 5f;
    }

    private /*async*/ void Update()
    {
        // 等待用户输入密钥
        if (elapsedTime > averageSecondsInMonth || Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
        {
            //await GetKey();//读取JSON更新密钥
            if (elapsedTime > averageSecondsInMonth)
            {
                encryptionKey = (KeyGenerator.GenerateKey("123"));//更新密钥
                isOverdueKey = true;
            }
            if (isOverdueKey && encryptionKey.Equals(inputKey))
            {
                ResetTimer();
                isOverdueKey = false;
                Debug.Log("密钥正确，继续运行程序");
            }
            else if (isOverdueKey)
            {
                Debug.Log("密钥错误，程序无法运行");
                Application.Quit(); // 密钥错误，退出应用程序
            }
        }
        /*else if (isOverdueKey && Input.GetKeyDown(KeyCode.Backspace))
        {
            if (inputKey.Length >= 1)
                inputKey = inputKey.Substring(0, inputKey.Length - 1);
            else
                return;
        }
        else if (isOverdueKey && Input.anyKeyDown)
        {
            inputKey += Input.inputString;
        }*/
        else if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
        {
            if (isOverdueKey && Input.GetKeyDown(KeyCode.V))
            {
                string pasteText = GUIUtility.systemCopyBuffer; // 获取系统粘贴板的内容
                inputKey = pasteText; // 将粘贴的值赋给Input字段
            }
        }
    }

    private void LateUpdate()
    {
        //elapsedTime += Time.deltaTime;
        //Debug.Log("elapsedTime: " + elapsedTime);
    }


    /// <summary>
    /// 重置计时器、秘钥有效期更新
    /// </summary>
    public void ResetTimer()
    {
        elapsedTime = 0f;
        averageSecondsInMonth = 5270400f;
    }

    private async Task<string> Get_Api(string url_pice)
    {
        var apiDoc_p = await GetApiDocumentation(url_pice);
        return (apiDoc_p);
    }

    private async Task<string> GetApiDocumentation(string apiUrl)
    {
        // 创建 HTTP 客户端
        using (var httpClient = new HttpClient())
        {
            // 发送 GET 请求并等待响应
            var response = await httpClient.GetAsync(apiUrl);

            // 确认响应是否成功
            response.EnsureSuccessStatusCode();

            // 读取响应内容并返回
            return await response.Content.ReadAsStringAsync();
        }
    }

    [System.Serializable]
    public class Data
    {
        /// <summary>
        /// 
        /// </summary>
        public double flat { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public double tip { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public double valley { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public double peak { get; set; }
    }

    [System.Serializable]
    public class Root
    {
        /// <summary>
        /// 
        /// </summary>
        public Data data { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string msg { get; set; }
    }

    public async Task GetKey()
    {
        try
        {
            var apiData = await Get_Api(url_key);
            if (apiData != null)
            {
                Debug.Log("API CabinetList: " + apiData);
                Root root = JsonConvert.DeserializeObject<Root>(apiData);
                encryptionKey = root.data.flat.ToString();
            }
            else
            {
                Debug.Log("API请求失败或返回空数据。");
            }
        }
        catch (Exception e)
        {
            Debug.LogError("API请求期间发生错误: " + e.Message);
        }

    }
}
