import React, { useState, useEffect, ChangeEvent } from 'react';
import { Button, Input, message, Popconfirm } from 'antd';
import styles from './index.less';
import { createAppID, createSecretKey, getAppID, getSecretKey } from '@/services/system/secretKey';
import { Access, useAccess } from 'umi';

const { TextArea } = Input;

const SecretKey: React.FC = () => {
  const access = useAccess();
  const [secretKey, setSecretKey] = useState('');
  const [appIDString, setAppIDString] = useState('');

  const create = async () => {
    const data = await createSecretKey({});
    message.success('密钥创建成功');
    setSecretKey(data + '');
  };

  const appIDCreate = async () => {
    if (appIDString == '') {
      message.warning('请填写AppID');
      return;
    }
    await createAppID({ appid: appIDString });
    message.success('AppID创建成功');
  };

  const getAppIDString = async () => {
    const data = await getAppID();
    setAppIDString(data + '');
  };

  const getUserSecretKey = async () => {
    const data = await getSecretKey();
    setSecretKey(data + '');
  };

  useEffect(() => {
    getAppIDString();
    getUserSecretKey();
  }, [secretKey]);

  return (
    <div className={styles.container}>
      <Access accessible={access.canShowButton('创建密钥')}>
        <Popconfirm title="确定创建密钥?" onConfirm={create} okText="确定" cancelText="取消">
          <Button className={styles.button} type="primary">
            创建密钥
          </Button>
        </Popconfirm>
      </Access>

      <TextArea className={styles.textarea} rows={16} value={secretKey} />
      <br />
      <br />
      <Input.Group compact>
        <Input
          style={{ width: 'calc(50% - 160px)' }}
          value={appIDString}
          onChange={(event: ChangeEvent<HTMLInputElement>) => {
            setAppIDString(event.target.value);
          }}
          placeholder="请输入AppID"
        />
        <Access accessible={access.canShowButton('创建AppID')}>
          <Popconfirm
            title="确定创建AppID?"
            onConfirm={appIDCreate}
            okText="确定"
            cancelText="取消"
          >
            <Button className={styles.button} type="primary">
              创建AppID
            </Button>
          </Popconfirm>
        </Access>
      </Input.Group>
    </div>
  );
};

export default SecretKey;
