/*
 * @Author: yuananting
 * @Date: 2021-03-27 11:15:03
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-29 16:22:28
 * @Description: 助学工具-题库-批量导入题目
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Modal, Button, message, Spin } from "antd";
import "./BatchImportQuestionModal.less";
import SelectPrepareFileModal from "@/modules/prepare-lesson/modal/SelectPrepareFileModal";
import User from "@/common/js/user";
import QuestionBankService from "@/domains/question-bank-domain/QuestionBankService";
import { LoadingOutlined } from "@ant-design/icons";
class BatchImportQuestionModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showSelectFileModal: false, // 云盘列表弹窗显隐
      diskList: [], // 资料云盘文件列表
      uploadFile: null, // 上传的文件
      uploadResult: {
        elapsedTime: 0,
        failCnt: 0,
        resourceUrl: null,
        successCnt: 0,
      }, // 上传返回结果
      message: null,
      status: "init",
    };
  }

  // 下载题目模板
  handleDownTemplate = () => {
    const a = document.createElement("a");
    a.href = "https://image.xiaomaiketang.com/xm/题目批量导入标准模版.xlsx";
    a.click();
  };

  // 选择云盘资源
  handleSelectExcel = (file) => {
    this.setState({ uploadFile: file });
    this.setState({
      showSelectFileModal: false,
    });
  };

  // 导入
  handleImport = async () => {
    const { uploadFile } = this.state;
    if (!uploadFile) {
      message.warning("请选择要导入的文件");
    } else {
      let flag = false;
      setTimeout(() => {
        if (!flag) {
          this.setState({ status: "uploading" });
        }
      }, 1000);

      let params = {
        categoryId: this.props.categoryId,
        resourceId: this.state.uploadFile.resourceId,
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      };
      const res = await QuestionBankService.batchImport(params);
      const { result } = res;
      const { bizSuccess, bizMessage } = result;
      if (res) {
        flag = true;
        this.setState({ status: bizSuccess ? "success" : "fail" });
        this.setState({ uploadResult: result });
        this.setState({ message: bizMessage });
      }
    }
  };

  // 下载错误报告
  downErrorReport = async () => {
    const { uploadResult } = this.state;
    const { resourceUrl } = uploadResult;
    const a = document.createElement("a");
    a.href = resourceUrl;
    a.click();
  };

  render() {
    const {
      diskList,
      showSelectFileModal,
      uploadFile,
      status,
      uploadResult,
      message,
    } = this.state;
    const { failCnt, resourceUrl, successCnt } = uploadResult;
    const loadingIcon = <LoadingOutlined style={{ fontSize: 76 }} spin />;
    return (
      <div>
        <Modal
          closable={status !== "uploading"}
          className="import-score-modal"
          title="导入题目信息"
          visible={true}
          width={560}
          maskClosable={false}
          footer={
            status === "init" && [
              <Button onClick={this.props.close}>取消</Button>,
              <Button type="primary" onClick={this.handleImport}>
                导入
              </Button>,
            ]
          }
          onCancel={() => {
            this.props.close();
          }}
        >
          {status === "init" && (
            <div>
              <div className="step-section">
                <h4 className="step-title">1.下载导入模板，按要求填写信息</h4>
                <div
                  className="down-btn"
                  style={{ fontSize: "14px" }}
                  onClick={this.handleDownTemplate}
                >
                  下载题目导入模板
                </div>
              </div>
              <div className="step-section">
                <h4 className="step-title">2.选择需要导入的Excel文件</h4>
                <p style={{ marginBottom: 16, color: "gray" }}>
                  导入限制：一次最多导入1000个题目
                </p>
                <Button
                  type="primary"
                  className="add-btn"
                  onClick={() => this.setState({ showSelectFileModal: true })}
                >
                  {uploadFile ? "重新添加" : "添加文件"}
                </Button>
                {uploadFile && (
                  <div className="file-box">
                    <div>
                      <img
                        className="link-img"
                        src="https://image.xiaomaiketang.com/xm/link.png"
                      />
                      <span>{uploadFile.folderName}</span>
                      <img
                        className="del-img"
                        src="https://image.xiaomaiketang.com/xm/del.png"
                        onClick={() => this.setState({ uploadFile: null })}
                      />
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
          {status === "uploading" && (
            <div className="import-status-box">
              <div className="status-content">
                <Spin indicator={loadingIcon} />
                <p className="status">题目导入中...</p>
                <p className="status-tip">请勿关闭页面和此弹窗</p>
                <p className="status-tip">
                  <span>以防题目导入失败</span>
                </p>
              </div>
            </div>
          )}
          {status === "success" && (
            <div className="import-status-box">
              <div className="status-content">
                <img
                  src="https://image.xiaomaiketang.com/xm/success.png"
                  alt=""
                />
                <p className="status">导入完成</p>
                <p className="status-tip">
                  <span style={{ color: successCnt === 0 ? "" : "#FF9D14" }}>
                    {successCnt}
                  </span>
                  个题目导入成功，
                  <span style={{ color: failCnt === 0 ? "" : "#FF9D14" }}>
                    {failCnt}
                  </span>
                  个题目导入失败。
                </p>
                {resourceUrl ? (
                  <Button
                    type="primary"
                    className="down-btn"
                    onClick={() => this.downErrorReport(resourceUrl)}
                  >
                    下载错误报告
                  </Button>
                ) : (
                  <Button
                    onClick={() => {
                      this.props.close();
                    }}
                  >
                    关闭
                  </Button>
                )}
              </div>
            </div>
          )}
          {status === "fail" && (
            <div className="import-status-box">
              <div className="status-content">
                <img src="https://image.xiaomaiketang.com/xm/fail.png" alt="" />
                <p className="status">导入失败</p>
                <p className="status-tip">{message}</p>
                {message ? (
                  <Button
                    type="primary"
                    className="down-btn"
                    onClick={() => {
                      this.setState({
                        status: "init",
                        uploadFile: null,
                        showSelectFileModal: true,
                      });
                    }}
                  >
                    重新上传文件
                  </Button>
                ) : (
                  <Button
                    onClick={() => {
                      this.props.close();
                    }}
                  >
                    关闭
                  </Button>
                )}
              </div>
            </div>
          )}
        </Modal>
        <SelectPrepareFileModal
          operateType="select"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
          selectTypeList={[
            "vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "vnd.ms-excel",
          ]}
          tooltip="支持文件类型：xls、xlsx"
          isOpen={showSelectFileModal}
          diskList={diskList}
          onClose={() => {
            this.setState({ showSelectFileModal: false });
          }}
          onSelect={this.handleSelectExcel}
        />
      </div>
    );
  }
}

export default BatchImportQuestionModal;
