/*
 * @Author: yuananting
 * @Date: 2021-02-25 11:23:47
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-18 10:24:47
 * @Description: 助学工具-题库-题目管理主页面列表数据
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Table,
  Switch,
  ConfigProvider,
  Empty,
  Row,
  Input,
  Select,
  Tooltip,
  Space,
  Button,
  Modal,
  message,
} from "antd";
import { PageControl } from "@/components";
import "./QuestionManageContent.less";
import User from "@/common/js/user";
import QuestionBankService from "@/domains/question-bank-domain/QuestionBankService";
import _ from "underscore";
import QuestionPreviewModal from "../modal/QuestionPreviewModal";
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 QuestionManageContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: {
        current: 1,
        size: 10,
        order: "ACCURACY_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(),
      },
      questionTypeList: [], // 题型列表
      dataSource: [],
      totalCount: 0,
      QuestionPreviewModal: null, // 题目预览模态框
    };
  }

  componentDidMount() { }

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

  queryQuestionPageList = () => {
    const _query = this.state.query;
    if (_query.categoryId === "0") _query.categoryId = null;
    QuestionBankService.queryQuestionPageList(_query).then((res) => {
      const { records = [], total = 0 } = res.result;
      this.setState({ dataSource: records });
      this.setState({ total });
    });
  };

  handleCreateQuestionBank = () => {
    window.RCHistory.push({
      pathname: `/create-new-question?categoryId=${this.state.query.categoryId}`,
    });
  };

  delCategoryConfirm(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(),
    };
    QuestionBankService.deleteQuestion(params).then((res) => {
      if (res.success) {
        message.success("删除成功");
        this.queryQuestionPageList();
        this.props.updatedSiderTree(this.props.selectedCategoryId);
      }
    });
  };

  // 排序
  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;
    _query.current = 1;
    this.setState({ query: _query }, () => this.queryQuestionPageList());
  };

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

  previewQuestion = (id) => {
    const m = (
      <QuestionPreviewModal
        id={id}
        close={() => {
          this.setState({
            QuestionPreviewModal: null,
          });
        }}
      />
    );
    this.setState({ QuestionPreviewModal: m });
  };

  toEditQuetion = (id, type) => {
    const { categoryId } = this.state.query;
    if (categoryId) {
      window.RCHistory.push({
        pathname: `/create-new-question?id=${id}&type=${type}&categoryId=${categoryId}`,
      });
    } else {
      window.RCHistory.push({
        pathname: `/create-new-question?id=${id}&type=${type}`,
      });
    }
  };

  // 表头设置
  parseColumns = () => {
    const isPermiss = ["CloudManager", "StoreManager"].includes(User.getUserRole());
    const columns = [
      {
        title: "题目",
        key: "questionStem",
        dataIndex: "questionStem",
        render: (val, record) => {
          var handleVal = val;
          handleVal = handleVal.replace(/<(?!img|input).*?>/g, "");
          handleVal = handleVal.replace(/<\s?input[^>]*>/gi, "_、");
          handleVal = handleVal.replace(/<\s?img[^>]*>/gi, "【图片】");
          handleVal = handleVal.replace(/\&nbsp\;/gi, " ");
          return (
            <Tooltip title={handleVal}>
              <div className="record-name">{handleVal}</div>
            </Tooltip>
          );
        },
      },
      {
        title: "题型",
        key: "questionTypeEnum",
        dataIndex: "questionTypeEnum",
        render: (val) => {
          return questionTypeEnum[val];
        },
      },
      {
        title: "正确率",
        key: "accuracy",
        dataIndex: "accuracy",
        sorter: true,
        sortDirections: ["ascend", "descend", "ascend"],
        showSorterTooltip: false,
        render: (val) => {
          return val + "%";
        },
      },
      {
        title: "更新时间",
        key: "updateTime",
        dataIndex: "updateTime",
        sorter: true,
        sortDirections: ["ascend", "descend", "ascend"],
        showSorterTooltip: false,
        render: (val) => {
          return formatDate("YYYY-MM-DD H:i:s", val);
        },
      },
      {
        title: "操作",
        key: "operate",
        dataIndex: "operate",
        fixed: "right",
        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.toEditQuetion(record.id, record.questionTypeEnum)
                }
              >
                编辑
              </div>}
              {isPermiss && <span className="record-operate__item split"> | </span>}
              {isPermiss && <div
                className="record-operate__item"
                onClick={() => this.delCategoryConfirm(record)}
              >
                删除
              </div>}
            </div>
          );
        },
      },
    ];
    return columns;
  };

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

  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();
      }
    );
  };

  batchImportQuestion = () => {
    const { categoryId } = this.state.query;
    const ImportQuestionModal = (
      <BatchImportQuestionModal
        close={() => {
          this.setState({ ImportQuestionModal: null }, () => { this.queryQuestionPageList(); this.props.updatedSiderTree(this.props.selectedCategoryId) });
        }}
        categoryId={categoryId}
      />
    );
    this.setState({ ImportQuestionModal });
  };

  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% - 84px)" }}
                  onChange={(e) => {
                    this.handleChangeQuery("questionName", e.target.value);
                  }}
                  onSearch={() => {
                    this.queryQuestionPageList();
                  }}
                />
              </div>

              <div className="search-condition__item">
                <span className="search-label">题型：</span>
                <Select
                  placeholder="请选择题目类型"
                  value={questionType}
                  style={{ width: "calc(100% - 70px)" }}
                  showSearch
                  allowClear
                  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()) && !["0", null].includes(categoryId)) && (
          <Space size="large">
            <Button type="primary" onClick={this.handleCreateQuestionBank}>
              新建题目
            </Button>
            <Button onClick={this.batchImportQuestion}>批量导入</Button>
          </Space>
        )}
        <div className="question-manage-list">
          <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>
          )}
          {this.state.QuestionPreviewModal}
          {this.state.ImportQuestionModal}
        </div>
      </div>
    );
  }
}

export default QuestionManageContent;
