/*
 * @Author: yuananting
 * @Date: 2021-02-25 11:23:47
 * @LastEditors: yuananting
 * @LastEditTime: 2021-04-01 13:47:54
 * @Description: 助学工具-题库-题目列表数据
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Table,
  ConfigProvider,
  Empty,
  Row,
  Input,
  Select,
  Tooltip,
  Space,
  Button,
  Modal,
  message,
} from "antd";
import { PageControl } from "@/components";
import "./QuestionList.less";
import User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import _ from "underscore";
import PreviewQuestionModal from "../modal/PreviewQuestionModal";
import BatchImportQuestionModal from "../modal/BatchImportQuestionModal";

const { Search } = Input;

const questionTypeEnum = {
  SINGLE_CHOICE: "单选题",
  MULTI_CHOICE: "多选题",
  JUDGE: "判断题",
  GAP_FILLING: "填空题",
  INDEFINITE_CHOICE: "不定项选择题",
};

const questionTypeList = [
  {
    label: "单选题",
    value: "SINGLE_CHOICE",
  },
  {
    label: "多选题",
    value: "MULTI_CHOICE",
  },
  {
    label: "判断题",
    value: "JUDGE",
  },
  {
    label: "填空题",
    value: "GAP_FILLING",
  },
  {
    label: "不定项选择题",
    value: "INDEFINITE_CHOICE",
  },
];

class QuestionList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: {
        current: 1,
        size: 10,
        order: "UPDATED_DESC", // 排序规则[ ACCURACY_DESC, ACCURACY_ASC, CREATED_DESC, CREATED_ASC, UPDATED_DESC, UPDATED_ASC ]
        categoryId: null, // 当前题库分类Id
        questionName: null, // 题目名称
        questionType: null, // 题目类型
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      },
      dataSource: [], // 题库列表
      previewQuestionModal: null, // 题目预览模态框
      batchImportQuestionModal: null, // 批量导入模态框
    };
  }

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

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

  // 清空搜索条件
  handleReset = () => {
    const _query = {
      ...this.state.query,
      current: 1,
      order: "ACCURACY_DESC", // 排序规则
      questionName: null, // 题目名称
      questionType: null, // 题目类型
    };
    this.setState({ query: _query }, () => {
      this.queryQuestionPageList();
    });
  };

  // 题库列表查询
  queryQuestionPageList = () => {
    const _query = this.state.query;
    AidToolService.queryQuestionPageList(_query).then((res) => {
      const { records = [], total = 0 } = res.result;
      this.setState({ dataSource: records, total }, () =>
        this.props.updatedSiderTree(total, this.props.selectedCategoryId)
      );
    });
  };

  // 自定义表格空状态
  customizeRenderEmpty = () => {
    const { categoryId } = this.state.query;
    return (
      <Empty
        image="https://image.xiaomaiketang.com/xm/emptyTable.png"
        imageStyle={{
          height: 100,
        }}
        description={
          <div>
            <span>还没有题目</span>
            {["CloudManager", "StoreManager"].includes(User.getUserRole()) &&
              categoryId && (
                <span>
                  ，快去
                  <span
                    className="empty-list-tip"
                    onClick={() => {
                      this.handleCreateQuestion();
                    }}
                  >
                    新建一个
                  </span>
                  吧！
                </span>
              )}
          </div>
        }
      ></Empty>
    );
  };

  // 排序
  handleChangeTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter;
    let sort = null;
    if (columnKey === "accuracy" && order === "ascend") {
      sort = "ACCURACY_ASC";
    }
    if (columnKey === "accuracy" && order === "descend") {
      sort = "ACCURACY_DESC";
    }
    if (columnKey === "updateTime" && order === "ascend") {
      sort = "UPDATED_ASC";
    }
    if (columnKey === "updateTime" && order === "descend") {
      sort = "UPDATED_DESC";
    }
    const _query = this.state.query;
    _query.order = sort || "UPDATED_DESC";
    _query.current = 1;
    this.setState({ query: _query }, () => this.queryQuestionPageList());
  };

  // 表头设置
  parseColumns = () => {
    // 权限判断
    const isPermiss = ["CloudManager", "StoreManager"].includes(
      User.getUserRole()
    );
    const columns = [
      {
        title: "题目",
        key: "questionStem",
        dataIndex: "questionStem",
        ellipsis: {
          showTitle: false,
        },
        render: (val) => {
          var handleVal = val;
          handleVal = handleVal.replace(/<(?!img|input).*?>/g, "");
          handleVal = handleVal.replace(/<\s?input[^>]*>/gi, "_、");
          handleVal = handleVal.replace(/\&nbsp\;/gi, " ");
          return (
            <Tooltip
              overlayClassName="aid-tool-list"
              title={
                <div style={{ maxWidth: 700, width: "auto" }}>{handleVal}</div>
              }
              placement="topLeft"
              overlayStyle={{ maxWidth: 700 }}
            >
              {handleVal}
            </Tooltip>
          );
        },
      },
      {
        title: "题型",
        key: "questionTypeEnum",
        dataIndex: "questionTypeEnum",
        width: "16%",
        render: (val) => {
          return questionTypeEnum[val];
        },
      },
      {
        title: "正确率",
        key: "accuracy",
        dataIndex: "accuracy",
        sorter: true,
        showSorterTooltip: false,
        width: "14%",
        render: (val) => {
          return val + "%";
        },
      },
      {
        title: "更新时间",
        key: "updateTime",
        dataIndex: "updateTime",
        sorter: true,
        showSorterTooltip: false,
        width: "24%",
        render: (val) => {
          return formatDate("YYYY-MM-DD H:i:s", val);
        },
      },
      {
        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>
              {isPermiss && (
                <span className="record-operate__item split"> | </span>
              )}
              {isPermiss && (
                <div
                  className="record-operate__item"
                  onClick={() =>
                    this.editQuestion(record.id, record.questionTypeEnum)
                  }
                >
                  编辑
                </div>
              )}
              {isPermiss && (
                <span className="record-operate__item split"> | </span>
              )}
              {isPermiss && (
                <div
                  className="record-operate__item"
                  onClick={() => this.delQuestionConfirm(record)}
                >
                  删除
                </div>
              )}
            </div>
          );
        },
      },
    ];
    return columns;
  };

  // 设置表格每页展示条数
  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    let _query = this.state.query;
    _query.size = size;
    this.setState({ query: _query }, () => this.queryQuestionPageList());
  };

  // 预览题目
  previewQuestion = (id) => {
    const m = (
      <PreviewQuestionModal
        id={id}
        close={() => {
          this.setState({
            previewQuestionModal: null,
          });
        }}
      />
    );
    this.setState({ previewQuestionModal: m });
  };

  // 编辑题目
  editQuestion = (id, type) => {
    const { categoryId } = this.state.query;
    window.RCHistory.push({
      pathname: `question-operate-page?id=${id}&type=${type}&categoryId=${categoryId}`,
    });
  };

  // 删除题目确认弹窗
  delQuestionConfirm(record) {
    return Modal.confirm({
      title: "提示",
      content: "确定要删除此题目吗？",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        this.deleteQuestion(record);
      },
    });
  }

  // 删除题目
  deleteQuestion = (record) => {
    let params = {
      id: record.id,
      source: 0,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
    };
    AidToolService.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());
      }
    });
  };

  // 创建题目-跳转新建页
  handleCreateQuestion = () => {
    window.RCHistory.push({
      pathname: `question-operate-page?categoryId=${this.state.query.categoryId}`,
    });
  };

  // 批量导入弹窗
  batchImportQuestion = () => {
    const { categoryId } = this.state.query;
    const m = (
      <BatchImportQuestionModal
        close={() => {
          this.setState({ batchImportQuestionModal: null }, () => {
            this.queryQuestionPageList();
          });
        }}
        categoryId={categoryId}
      />
    );
    this.setState({ batchImportQuestionModal: m });
  };

  render() {
    const {
      dataSource = [],
      total,
      query,
      previewQuestionModal,
      batchImportQuestionModal,
    } = this.state;
    const { current, size, categoryId, questionName, questionType } = query;
    return (
      <div className="question-list">
        <div className="question-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={questionName}
                  style={{ width: "calc(100% - 84px)" }}
                  onChange={(e) => {
                    this.handleChangeQuery("questionName", e.target.value);
                  }}
                  onSearch={() => {
                    this.queryQuestionPageList();
                  }}
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                />
              </div>

              <div className="search-condition__item">
                <span className="search-label">题型：</span>
                <Select
                  placeholder="请选择题目类型"
                  value={questionType}
                  style={{ width: "calc(100% - 70px)" }}
                  showSearch
                  allowClear
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                  filterOption={(inputVal, option) =>
                    option.props.children.includes(inputVal)
                  }
                  onChange={(value) => {
                    if (_.isEmpty(value)) {
                      this.handleChangeQuery("questionType", value);
                    }
                  }}
                  onSelect={(value) => {
                    this.handleChangeQuery("questionType", value);
                  }}
                >
                  {_.map(questionTypeList, (item, index) => {
                    return (
                      <Select.Option value={item.value} key={item.key}>
                        {item.label}
                      </Select.Option>
                    );
                  })}
                </Select>
              </div>
            </div>

            <div className="reset-fold-area">
              <Tooltip title="清空筛选">
                <span
                  className="resetBtn iconfont icon"
                  onClick={this.handleReset}
                >
                  &#xe61b;{" "}
                </span>
              </Tooltip>
            </div>
          </Row>
        </div>
        {["CloudManager", "StoreManager"].includes(User.getUserRole()) &&
          categoryId && (
            <Space size={16}>
              <Button type="primary" onClick={this.handleCreateQuestion}>
                新建题目
              </Button>
              <Button onClick={this.batchImportQuestion}>批量导入</Button>
            </Space>
          )}
        <div className="question-list-content">
          <ConfigProvider renderEmpty={this.customizeRenderEmpty}>
            <Table
              rowKey={(record) => record.id}
              dataSource={dataSource}
              columns={this.parseColumns()}
              pagination={false}
              bordered
              onChange={this.handleChangeTable}
            />
          </ConfigProvider>
          {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>
          )}
          {previewQuestionModal}
          {batchImportQuestionModal}
        </div>
      </div>
    );
  }
}

export default QuestionList;
