import React, { Fragment, useState } from 'react';
import { connect } from 'react-redux';
import { Button } from '@easyv/antd';
import message from 'components/message';
import { Upload } from 'components/easyDesign';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import styles from './Extend.less';
import {getAssetsUrl} from 'utils/utils';
import { getUserInfo } from 'models/user';
import EasyvModal, { useActionModalRef } from 'components/EasyvModal';

function Extend({ children, screenCount }) {
  const modalRef = useActionModalRef();
  const [file, setFile] = useState<File>();

  const handleDownload = async () => {
    const result = await request(api.getUserCrt);
    if (result) {
      window.location.href = getAssetsUrl(result.file);
    }
  };

  const handleSelectFile = (e) => {
    setFile(e.file);
  };

  const handleUpload = async () => {
    if (file) {
      const formData = new FormData();
      formData.append('file', file);
      const result = await request(api.uploadCrt, undefined, undefined, formData);
      if (!result) {
        message.error('上传授权证书失败');
      } else {
        window.location.reload();
      }
    } else {
      message.error('请先上传产品密钥');
    }
  };

  const handleClose = () => {
    modalRef.current?.close();
  };

  return (
    <Fragment>
      <span
        onClick={() => {
          modalRef.current?.show();
        }}>
        {children}
      </span>
      <EasyvModal.ActionModal
        ref={modalRef}
        okText="扩容"
        onOk={handleUpload}
        onCancel={handleClose}
        title="发布空间扩容"
        content={
          <>
            <p style={{ marginBottom: 20 }}>当前可发布项目总数共{screenCount}个， 可联系我方业务人员进行扩容</p>
            <h3 className={styles.title}>
              <span className={styles.circle}>1</span>
              获取产品密钥
            </h3>
            <p style={{ marginBottom: 12 }}>请与我方业务负责人联系（韬云：187-5716-1892），我方将根据您的实际情况为您分配密钥</p>
            <Button type="primary" ghost style={{ marginBottom: 20 }} onClick={handleDownload}>
              下载备用配置信息
            </Button>
            <h3 className={styles.title}>
              <span className={styles.circle}>2</span>
              上传新的产品密钥
            </h3>
            <Upload style={{ width: '100%' }} accept=".crt" customRequest={handleSelectFile}>
              <i className={styles.uploadIcon} />
              <p>单击或拖放文件至此处进行上传</p>
            </Upload>
            {file && <div>{file.name}</div>}
          </>
        }
      />
    </Fragment>
  );
}

const mapStateToProps = ({ user }) => {
  return {
    screenCount: user.userInfo.screenCount
  };
};

const mapDispatchToProps = {
  getUserInfo: getUserInfo
};

export default connect(mapStateToProps, mapDispatchToProps)(Extend);
