/*
 * @Author: yuananting
 * @Date: 2021-02-25 11:23:47
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-30 19:32:28
 * @Description: 助学工具-题库-题目管理主页面列表数据
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Table,
  Dropdown,
  Row,
  Input,
  Tooltip,
  Menu,
  Button,
  Modal,
  message,
} from "antd";
import { PageControl } from "@/components";
import "./ExaminationPaperContent.less";
import User from "@/common/js/user";
import QuestionBankService from "@/domains/question-bank-domain/QuestionBankService";
import _ from "underscore";

const { Search } = Input;

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

  componentDidMount() {}

  shouldComponentUpdate(nextProps, nextState) {
    let { selectedCategoryId } = nextProps;
    const _query = this.state.query;
    if (this.props.selectedCategoryId !== selectedCategoryId) {
      _query.categoryId = selectedCategoryId === "null" ? null : selectedCategoryId;
      _query.examinationPaperName = null;
      _query.current = 1;
      this.setState({ query: _query }, () => this.queryExaminationPaperList());
    }
    return true;
  }

  // 查询试卷列表
  queryExaminationPaperList = () => {};

  // 预览试卷
  previewExaminationPaper = (record) => {};

  // 复制试卷
  copyExaminationPaper = (record) => {};

  // 编辑试卷
  editExaminationPaper = (record) => {};

  // 删除试卷
  delExaminationPaper(record) {
    return Modal.confirm({
      title: "提示",
      content: "确定要删除此试卷吗？",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        let params = {
          id: record.id,
          source: 0,
          tenantId: User.getStoreId(),
          userId: User.getStoreUserId(),
        };
        QuestionBankService.deleteQuestion(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.queryQuestionPageList()
            );
          }
        });
      },
    });
  }

  // 表头设置
  parseColumns = () => {
    const columns = [
      {
        title: "试卷",
        key: "examinationPaperName",
        dataIndex: "examinationPaperName",
        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: "16%",
        render: (val, record) => {
          return (
            <span>
              {record.passScore}/{record.totalScore}
            </span>
          );
        },
      },
      {
        title: "题目数量",
        key: "count",
        dataIndex: "count",
        width: "14%",
      },
      {
        title: "关联考试数",
        key: "relatedCount",
        dataIndex: "relatedCount",
        width: "14%",
      },
      {
        title: "操作",
        key: "operate",
        dataIndex: "operate",
        width: "24%",
        render: (val, record) => {
          return (
            <div className="record-operate">
              <div
                className="record-operate__item"
                onClick={() => this.previewQuestion(record.id)}
              >
                预览
              </div>
              <span className="record-operate__item split"> | </span>
              <div
                className="record-operate__item"
                onClick={() =>
                  this.toEditQuetion(record.id, record.questionTypeEnum)
                }
              >
                复制
              </div>
              <span className="record-operate__item split"> | </span>
              <Dropdown overlay={this.initDropMenu(val)}>
                <div className="record-operate__item">更多</div>
              </Dropdown>
            </div>
          );
        },
      },
    ];
    return columns;
  };

  // 操作更多下拉项
  initDropMenu = (item) => {
    return (
      <Menu>
        <Menu.Item key="edit">
          <span onClick={() => this.editExaminationPaper(item)}>编辑</span>
        </Menu.Item>
        <Menu.Item key="del">
          <span onClick={() => this.delExaminationPaper(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.queryQuestionPageList());
  };

  // 改变搜索条件
  handleChangeQuery = (searchType, value) => {
    this.setState(
      {
        query: {
          ...this.state.query,
          [searchType]: value || null,
          current: 1,
        },
      },
      () => {
        if (searchType === "questionName") return;
        this.queryQuestionPageList();
      }
    );
  };

  render() {
    const { dataSource = [], total, query } = this.state;
    const { current, size, categoryId, questionName, questionType } = query;
    return (
      <div className="question-manage-content">
        <div className="question-manage-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={questionName}
                  style={{ width: "calc(100% - 100px)" }}
                  onChange={(e) => {
                    this.handleChangeQuery("questionName", e.target.value);
                  }}
                  onSearch={() => {
                    this.queryQuestionPageList();
                  }}
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                />
              </div>
            </div>
          </Row>
        </div>
        <Button
          type="primary"
          onClick={() => {
            window.RCHistory.push({
              pathname: `/new-examination-paper?categoryId=${this.state.query.categoryId}`,
            });
          }}
        >
          新建试卷
        </Button>
        <div className="question-manage-list">
          <Table
            rowKey={(record) => record.id}
            dataSource={dataSource}
            columns={this.parseColumns()}
            pagination={false}
            bordered
            onChange={this.handleChangeTable}
          />
          {total > 0 && (
            <div className="box-footer">
              <PageControl
                current={current - 1}
                pageSize={size}
                total={total}
                toPage={(page) => {
                  const _query = { ...query, current: page + 1 };
                  this.setState({ query: _query }, () =>
                    this.queryQuestionPageList()
                  );
                }}
                showSizeChanger={true}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default ExaminationPaperContent;
