import React, { useEffect, useState } from 'react';
import { Form, Input, DatePicker, Select, Button, message, FormInstance } from 'antd';
import { GetMachineAuthorizationTypeOptions } from '@/services/enum/machineAuthorizationEnum';
import CryptoJS from 'crypto-js'; // 添加这一行导入
import * as LZString from 'lz-string';
import { AddMachineIdAuthorizationFunc } from '@/services/services/other';


interface AddMachineIdAuthorizationProps {
  setFormRef: (form: FormInstance) => void;
}

const AddMachineIdAuthorization: React.FC<AddMachineIdAuthorizationProps> = ({ setFormRef }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [messageApi, messageHolder] = message.useMessage();

  useEffect(() => {
    setFormRef(form);
    form.setFieldsValue({
      type: 0,
      useType: 0,
      expiryTime: 365,
      authorizationCode: ""
    })
  }, [form, setFormRef]);

  const handleSubmit = async () => {
    try {
      setLoading(true);
      // TODO: Implement API call to save the authorization
      let values = form.getFieldsValue();
      await AddMachineIdAuthorizationFunc(values);
      messageApi.success('Machine ID authorization added successfully');
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setLoading(false);
    }
  };

  /**
 * 生成唯一授权码
 * @returns 返回一个唯一的授权码字符串，长度与UUID相似
 */
  function generateUniqueAuthCode(): string {
    // 基于时间戳的组件
    const timestamp = Date.now().toString(16);

    // 使用加密安全的随机值生成函数
    const getRandomHex = (length: number): string => {
      const bytes = new Uint8Array(length);
      // 使用浏览器的加密API生成随机数
      window.crypto.getRandomValues(bytes);
      // 转换为十六进制字符串
      return Array.from(bytes)
        .map(b => b.toString(16).padStart(2, '0'))
        .join('');
    };

    // 生成四个随机组件
    const randomA = getRandomHex(4);
    const randomB = getRandomHex(2);
    const randomC = getRandomHex(2);
    const randomD = getRandomHex(6);

    // 组合成类似UUID格式的字符串，但算法完全不同
    return `${timestamp}${randomA}${randomB}${randomC}${randomD}`.toUpperCase();
  }

  function GenerateAuthorizationCode() {

    let code = generateUniqueAuthCode();
    form.setFieldsValue({ authorizationCode: code });

    // return;
    // const values = form.getFieldsValue();
    // const { machineId, type, authorizedDate, expiryDate } = values;

    // if (!machineId || type === undefined || !authorizedDate || !expiryDate) {
    //   messageApi.error('请先填写必要信息（机器码、类型和日期）');
    //   return;
    // }
    // try {
    //   // Format dates to strings
    //   const authDate = moment(authorizedDate).format('YYYY-MM-DD HH:mm:ss');
    //   const expDate = moment(expiryDate).format('YYYY-MM-DD HH:mm:ss');
    //   let obj = {
    //     machineId: machineId,
    //     type: type,
    //     authorizedDate: authDate,
    //     expiryDate: expDate
    //   }

    //   // Create the string to encrypt
    //   const dataToEncrypt = JSON.stringify(obj);

    //   // Assuming CryptoJS is imported
    //   const secretKey = machineId;

    //   // Generate a secure encryption key from machineId
    //   const key = CryptoJS.enc.Utf8.parse(CryptoJS.SHA256(secretKey).toString());

    //   // Generate a random initialization vector
    //   const iv = CryptoJS.lib.WordArray.random(16);

    //   // Encrypt the data using AES encryption
    //   const encrypted = CryptoJS.AES.encrypt(dataToEncrypt, key, {
    //     iv: iv,
    //     mode: CryptoJS.mode.CBC,
    //     padding: CryptoJS.pad.Pkcs7
    //   });

    //   // Convert IV to base64 for storage
    //   const ivBase64 = CryptoJS.enc.Base64.stringify(iv);

    //   // Get the encrypted data in base64 format
    //   const encryptedBase64 = encrypted.toString();

    //   // Combine IV and encrypted data with a delimiter for future decryption
    //   const authCode = ivBase64 + ':' + encryptedBase64;

    //   // 使用LZString压缩
    //   const compressedCode = LZString.compressToEncodedURIComponent(authCode);
    //   // Set the encrypted value in the form
    //   form.setFieldsValue({ authorizationCode: compressedCode });

    //   messageApi.success('授权码已生成');
    // } catch (error) {
    //   console.error('生成授权码时出错:', error);
    //   messageApi.error('生成授权码失败');
    // }
  }



  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      autoComplete="off"
    >


      <Form.Item
        name="type"
        label="授权软件类型"
        rules={[{ required: true, message: '请输入授权软件类型' }]}
      >
        <Select placeholder="选择授权软件类型" options={GetMachineAuthorizationTypeOptions()}></Select>
      </Form.Item>

      <Form.Item
        name="useType"
        label="授权使用类型"
        rules={[{ required: true, message: '请输入授权软件类型' }]}
      >
        <Select placeholder="选择授权软件类型" options={[
          { label: '基础', value: 0 },
          { label: '专业', value: 1 },
        ]}></Select>
      </Form.Item>

      <Form.Item
        name="authorizedDate"
        label="授权时间"
      >
        <DatePicker
          disabled
          showTime
          style={{ width: '100%' }}
          placeholder="选择授权日期和时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      </Form.Item>

      <Form.Item
        name="expiryDate"
        label="到期时间"
      >
        <DatePicker
          disabled
          showTime
          style={{ width: '100%' }}
          placeholder="选择到期日期和时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      </Form.Item>

      <Form.Item
        name="expiryTime"
        label="授权到期时间"
        rules={[{ required: true, message: '请选择授权到期时间' }]}
      >
        <Select
          placeholder="请选择授权时间"
          showSearch
          allowClear
          optionFilterProp="children"
          options={[
            { label: '0天', value: 0 },
            { label: '30天', value: 30 },
            { label: '90天', value: 90 },
            { label: '180天', value: 180 },
            { label: '365天', value: 365 },
          ]}
        />
      </Form.Item>

      <Form.Item name="authorizationCode" label="授权码"
        rules={[{ required: true, message: '请先生成授权码' }]}
      >
        <Input
          placeholder="授权码将显示在这里"
        />

      </Form.Item>

      <Form.Item style={{ textAlign: 'right' }}>
        {/* <Button
          style={{ marginRight: 8 }}
          type="primary"
          onClick={() => {
            const values = form.getFieldsValue();
            const { machineId, authorizationCode } = values;
            if (!machineId || !authorizationCode) {
              messageApi.error('请先填写机器码和授权码');
              return;
            }
            const result = DecryptAuthorizationCode(authorizationCode, machineId);
            if (result.success) {
              messageApi.success('授权码解密成功');
              console.log('解密结果:', result.data);
            } else {
              messageApi.error(`解密失败: ${result.error}`);
            }
          }}
        >
          解密授权码
        </Button> */}
        <Button
          type="primary"
          onClick={GenerateAuthorizationCode}
          style={{ marginRight: 8 }}
        >
          计算授权码
        </Button>
        <Button type="primary" htmlType="submit" loading={loading}>
          保存
        </Button>
      </Form.Item>
      {messageHolder}
    </Form >
  );
};

export default AddMachineIdAuthorization;