/*
 * @Author: yuananting
 * @Date: 2021-02-25 11:23:47
 * @LastEditors: yuananting
 * @LastEditTime: 2021-05-20 11:37:40
 * @Description: 助学工具-题库-试卷列表数据
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Table,
  Dropdown,
  Row,
  Input,
  Tooltip,
  Menu,
  Button,
  Modal,
  message,
  ConfigProvider,
  Empty,
} from "antd";
import { PageControl } from "@/components";
import "./PaperList.less";
import { Route, withRouter } from "react-router-dom";
import OperatePaper from "@/modules/teach-tool/paper-manage/OperatePaper";
import User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import _ from "underscore";
import PaperPreviewModal from "../modal/PreviewPaperModal";
import Bus from "@/core/bus";

const { Search } = Input;

class PaperList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: {
        current: 1,
        size: 10,
        categoryId: null, // 当前题库分类Id
        paperName: null, // 试卷名称
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      },
      selectedRowKeys: [this.props.paperId],
      dataSource: [],
      paperPreviewModal: null, // 试卷预览模态框
      loading: false,
    };
  }

  componentDidMount() {
    this.queryPaperPageList();
    Bus.bind("queryPaperPageList", (selectedCategoryId, count) => {
      selectedCategoryId =
        selectedCategoryId === "null" ? null : selectedCategoryId;
      this.setState({ loading: true });
      if (count >= 100) {
        setTimeout(() => {
          this.InitSearch(selectedCategoryId);
        }, 5000);
      } else {
        this.InitSearch(selectedCategoryId);
      }
    });
  }

  componentWillUnmount() {
    Bus.unbind("queryPaperPageList", this.queryPaperPageList);
  }

  // 初始化列表查询
  InitSearch = (categoryId) => {
    const _query = {
      ...this.state.query,
      categoryId,
      current: 1,
      paperName: null, // 试卷名称
    };
    this.setState({ query: _query }, () => {
      this.queryPaperPageList();
    });
  };

  // 查询试卷列表
  queryPaperPageList = async () => {
    const res = await AidToolService.queryPaperPageList(this.state.query);
    Bus.trigger("queryCategoryTree", "remain");
    const { records = [], total = 0 } = res.result;
    this.setState({ dataSource: records, total, loading: false });
  };

  // 预览试卷
  previewPaper = (record) => {
    const m = (
      <PaperPreviewModal
        previewPage="paper-list"
        categoryId={this.state.query.categoryId}
        paperId={record.paperId}
        close={() => {
          this.setState({
            paperPreviewModal: null,
          });
        }}
      />
    );
    this.setState({ paperPreviewModal: m });
  };

  // 复制试卷
  copyPaper = (record) => {
    const { categoryId } = this.state.query;
    const { match } = this.props;
    window.RCHistory.push({
      pathname: `${match.url}/paper-operate-page?type=copy&paperId=${record.paperId}&categoryId=${categoryId}`,
    });
  };

  // 编辑试卷
  editPaper = (record) => {
    if (record.relatedExam === 0) {
      const { categoryId } = this.state.query;
      const { match } = this.props;
      window.RCHistory.push({
        pathname: `${match.url}/paper-operate-page/operate?type=edit&paperId=${record.paperId}&categoryId=${categoryId}`,
      });
    } else {
      return Modal.info({
        title: "无法编辑",
        icon: (
          <span className="icon iconfont default-confirm-icon">&#xe834;</span>
        ),
        content:
          "该试卷已被考试采用，无法继续编辑。如需修改，请复制一份进行修改。",
        okText: "我知道了",
      });
    }
  };

  // 删除试卷
  deletePaper = (record) => {
    let params = {
      paperId: record.paperId,
      source: 0,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
    };
    AidToolService.deletePaper(params).then((res) => {
      if (res.success) {
        message.success("删除成功");
        const { query, total } = this.state;
        const { size, current } = query;
        const _query = query;
        if (total / size < current) {
          if (total % size === 1) {
            _query.current = 1;
          }
        }
        this.setState({ query: _query }, () => {
          this.queryPaperPageList();
        });
      }
    });
  };

  // 删除试卷确认
  confirmDeletePaper = (record) => {
    if (record.relatedExam === 0) {
      return Modal.confirm({
        title: "删除试卷",
        content: "确认要删除该试卷吗？",
        icon: (
          <span className="icon iconfont default-confirm-icon">&#xe839; </span>
        ),
        okText: "删除",
        cancelText: "取消",
        onOk: () => {
          this.deletePaper(record);
        },
      });
    } else {
      return Modal.info({
        title: "删除试卷",
        content: "该试卷已被考试采用，无法删除。",
        icon: (
          <span className="icon iconfont default-confirm-icon">&#xe834; </span>
        ),
        okText: "我知道了",
      });
    }
  };

  // 自定义表格空状态
  customizeRenderEmpty = () => {
    return (
      <Empty
        image="https://image.xiaomaiketang.com/xm/emptyTable.png"
        imageStyle={{
          height: 100,
        }}
        description={"还没有试卷"}
      ></Empty>
    );
  };

  // 表头设置
  parseColumns = () => {
    const columns = [
      {
        title: "试卷",
        key: "paperName",
        dataIndex: "paperName",
        ellipsis: {
          showTitle: false,
        },
        render: (val, record) => {
          var handleVal = val;
          handleVal = handleVal.replace(/<(?!img|input).*?>/g, "");
          handleVal = handleVal.replace(/<\s?input[^>]*>/gi, "_、");
          handleVal = handleVal.replace(/\&nbsp\;/gi, " ");
          return (
            <Tooltip
              overlayClassName="tool-list"
              title={
                <div style={{ maxWidth: 700, width: "auto" }}>{handleVal}</div>
              }
              placement="topLeft"
              overlayStyle={{ maxWidth: 700 }}
            >
              {handleVal}
            </Tooltip>
          );
        },
      },
      {
        title: "及格分/总分",
        key: "score",
        dataIndex: "score",
        width: this.props.type !== "modal-select" ? "16%" : "24%",
        render: (val, record) => {
          return (
            <span>
              {record.passScore}/{record.totalScore}
            </span>
          );
        },
      },
      {
        title: "题目数量",
        key: "questionCnt",
        dataIndex: "questionCnt",
        width: this.props.type !== "modal-select" ? "12%" : "20%",
        align: "right",
        render: (val, record) => {
          return this.props.type !== "modal-select" ? (
            <span>{record.questionCnt}</span>
          ) : (
            <Tooltip
              overlayClassName="tool-list"
              title={
                <div>
                  <div className="item">
                    单选题:{record.singleChoiceCnt || 0}个
                  </div>
                  <div className="item">
                    多选题:{record.multiChoiceCnt || 0}个
                  </div>
                  <div className="item">判断题:{record.judgeCnt || 0}个</div>
                  <div className="item">
                    填空题:{record.gapFillingCnt || 0}个
                  </div>
                  <div className="item">
                    不定项选择题:{record.indefiniteChoiceCnt || 0}个
                  </div>
                </div>
              }
              placement="top"
              overlayStyle={{ maxWidth: 700 }}
            >
              <span>{record.questionCnt}</span>
            </Tooltip>
          );
        },
      },
    ];

    if (this.props.type !== "modal-select") {
      const isPermiss = ["CloudManager", "StoreManager"].includes(
        User.getUserRole()
      );
      columns.push({
        title: "关联考试数",
        key: "relatedExam",
        dataIndex: "relatedExam",
        width: this.props.type !== "modal-select" ? "16%" : "24%",
        align: "right",
      });
      columns.push({
        title: "操作",
        key: "operate",
        dataIndex: "operate",
        width: "24%",
        render: (val, record) => {
          return (
            <div className="record-operate">
              <div
                className="record-operate__item"
                onClick={() => this.previewPaper(record)}
              >
                预览
              </div>
              {isPermiss && (
                <span className="record-operate__item split"> | </span>
              )}
              {isPermiss && (
                <div
                  className="record-operate__item"
                  onClick={() => this.copyPaper(record)}
                >
                  复制
                </div>
              )}
              {isPermiss && (
                <span className="record-operate__item split"> | </span>
              )}
              {isPermiss && (
                <Dropdown overlay={this.initDropMenu(record)}>
                  <div className="record-operate__item">更多</div>
                </Dropdown>
              )}
            </div>
          );
        },
      });
    }
    return columns;
  };

  // 操作更多下拉项
  initDropMenu = (item) => {
    return (
      <Menu>
        <Menu.Item key="edit">
          <span onClick={() => this.editPaper(item)}>编辑</span>
        </Menu.Item>
        <Menu.Item key="del">
          <span onClick={() => this.confirmDeletePaper(item)}>删除</span>
        </Menu.Item>
      </Menu>
    );
  };

  // 页展示数修改
  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    let _query = this.state.query;
    _query.size = size;
    this.setState({ query: _query }, () => this.queryPaperPageList());
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys,
    });
    this.props.onSelect(selectedRows[0] || {});
  };

  render() {
    const {
      dataSource = [],
      total,
      query,
      paperPreviewModal,
      selectedRowKeys,
      loading,
    } = this.state;
    const { current, size, categoryId, paperName } = query;
    const rowSelection = {
      type: "radio",
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const isPermiss = ["CloudManager", "StoreManager"].includes(
      User.getUserRole()
    );
    const { match } = this.props;
    return (
      <div className={"paper-list " + this.props.type}>
        <div className="paper-list-filter">
          <Row type="flex" justify="space-between" align="top">
            <div className="search-condition">
              <div className="search-condition__item">
                <span className="search-label">试卷：</span>
                <Search
                  placeholder="搜索试卷名称"
                  value={paperName}
                  style={{ width: 177 }}
                  onChange={(e) => {
                    this.setState({
                      query: {
                        ...query,
                        paperName: e.target.value.trim(),
                        current: 1,
                      },
                    });
                  }}
                  onSearch={() => {
                    this.queryPaperPageList();
                  }}
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                />
              </div>
            </div>
          </Row>
        </div>
        {this.props.type !== "modal-select" && isPermiss && categoryId && (
          <Button
            type="primary"
            onClick={() => {
              window.RCHistory.push({
                pathname: `${match.url}/paper-operate-page?type=new&categoryId=${categoryId}`,
              });
            }}
          >
            新建试卷
          </Button>
        )}

        <div className="paper-list-content">
          <ConfigProvider renderEmpty={this.customizeRenderEmpty}>
            {this.props.type !== "modal-select" ? (
              <Table
                rowKey={(record) => record.id}
                dataSource={dataSource}
                columns={this.parseColumns()}
                pagination={false}
                bordered
                loading={loading}
              />
            ) : (
              <Table
                rowKey={(record) => record.id}
                dataSource={dataSource}
                size={this.props.type == "modal-select"?'small':'middle'}
                rowKey={(item) => {
                  return item.paperId;
                }}
                rowSelection={rowSelection}
                columns={this.parseColumns()}
                pagination={false}
                bordered
              />
            )}
          </ConfigProvider>

          {total > 0 && (
            <div className="box-footer">
              <PageControl
                current={current - 1}
                pageSize={size}
                total={total}
                size={this.props.type == "modal-select"?'small':'middle'}
                toPage={(page) => {
                  const _query = { ...query, current: page + 1 };
                  this.setState({ query: _query }, () =>
                    this.queryPaperPageList()
                  );
                }}
                showSizeChanger={true}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          )}
          {paperPreviewModal}
        </div>
        <Route
          path={`${match.url}/paper-operate-page`}
          component={OperatePaper}
        />
      </div>
    );
  }
}

export default withRouter(PaperList);
