import React, { useState, useEffect } from 'react';
import { Card } from '@easyv/antd';
import message from 'components/message';
import { request } from '../../utils/fetch';
import { api } from '../../constants/config';
import Title from './components/Title';
import Text from './components/Text';
import Button from './components/Button';
import PriButton from './components/PriButton';
import FileSelect from '../FileSelect';
import EasyvButton from 'components/EasyvButton';
import styles from './index.less';

const Certificate = ({ type, code, message: msg, expTime, originExp }) => {
  const [file, setFile] = useState<File | null>(null);

  const getClient = (type) => () => {
    request(api.getCrt)
      .then((data) => {
        if (type === 'file') {
          window.location.href = window.location.origin + '/' + data.file;
        }

        if (type === 'key') {
          navigator.clipboard.writeText(data.key);
        }
      })
      .catch(() => {
        message.error('获取配置信息失败');
      });
  };

  const uploadFile = () => {
    if (file) {
      const formData = new FormData();
      formData.append('file', file);
      request(api.uploadCrt, undefined, undefined, formData)
        .then(() => {
          window.location.href = '/';
        })
        .catch(() => {
          message.error('上传授权证书失败');
        });
    } else {
      message.error('请先上传产品密钥');
    }
  };

  const getTitle = () => {
    if (type == 'lifelong') return '产品信息';
    if (code === 3) return '产品到期';
    if (code === -1) return '产品激活';
    if (code === 200) return '产品升级';
    return '密钥异常';
  };

  const getSubTitle = () => {
    if (type == 'lifelong') return null;
    if (code === 3) return <span style={{ color: '#fff' }}>{`您的产品使用权限已于 ${expTime} 到期，请重新对产品进行激活。`}</span>;
    if (code === -1) return '欢迎使用袋鼠云数据可视化平台EasyV，请先按以下步骤对产品进行激活。';
    if (code === 200)
      return +new Date(originExp) < Date.now() + 30 * 24 * 3600 * 1000 ? (
        <span style={{ color: '#fff' }}>{`您的产品将在 ${expTime} 到期，请尽快升级以保障产品正常使用。`}</span>
      ) : (
        `您的产品使用权限将在 ${expTime} 到期。`
      );

    return (
      <span>
        您的密钥出现以下错误：
        <span style={{ color: '#fff' }}>{msg}</span>
        ，请升级密钥修复异常。
      </span>
    );
  };

  return (
    <div className={styles.container}>
      <Card
        style={{
          width: 520,
          height: 551,
          boxShadow: '0px 2px 6px 0px rgba(0,0,0,0.1)',
          borderRadius: 2,
          borderWidth: 0,
          background: '#2a2e3d'
        }}>
        <p
          style={{
            textAlign: 'center',
            fontSize: 18,
            fontFamily: 'PingFangSC-Medium',
            color: '#fff'
          }}>
          {getTitle()}
        </p>
        <Text styles={{ marginTop: 20, color: '#fff' }}>{getSubTitle()}</Text>
        <Title number={1} text={'获取产品密钥'} />
        <Text>请与我方业务负责人联系（韬云：187-5716-1892），我方将根据您的实际情况为您分配密钥。</Text>
        <EasyvButton onClick={getClient('file')} style={{ marginTop: 12 }} theme="default">
          下载配置信息
        </EasyvButton>
        <Button onClick={getClient('key')} styles={{ marginTop: 12, marginLeft: 104, opacity: 0 }}>
          复制配置信息
        </Button>
        <Title number={2} text={'上传产品密钥'} />
        <FileSelect
          containerStyles={{
            margin: 0,
            width: 340,
            height: 126,
            padding: 0
          }}
          multiple={false}
          accept={['.crt']}
          onComplete={(file) => {
            setFile(file);
          }}
        />
        {file && <div className={styles.fileName}>{file.name}</div>}
        <div style={{ display: 'flex', marginTop: 40, justifyContent: 'center' }}>
          <PriButton onClick={uploadFile}>{code === 3 ? '激活' : '升级'}</PriButton>
        </div>
      </Card>
    </div>
  );
};

const Wrapper = () => {
  const [type, setType] = useState(null);
  const [originExp, setOriginExp] = useState(null);
  const [expTime, setExpTime] = useState(null);
  const [code, setCode] = useState(-1);
  const [msg, setMsg] = useState(null);

  useEffect(() => {
    const controller = window.AbortController && new AbortController();
    const signal = controller && controller.signal;

    request(api.getCrtInfo, undefined, undefined, undefined, { signal: signal }).then(({ code, message, expTime, originExp, type }) => {
      setExpTime(expTime);
      setCode(code);
      setOriginExp(originExp);
      setMsg(message);
      setType(type);
    });

    return () => {
      controller && controller.abort();
    };
  }, []);

  return <Certificate type={type} originExp={originExp} code={code} message={msg} expTime={expTime} />;
};

export default Wrapper;
