/*
 * @Author: yuananting
 * @Date: 2021-02-25 11:23:47
 * @LastEditors: yuananting
 * @LastEditTime: 2021-04-07 15:17:55
 * @Description: 助学工具-新建试卷-选择题目列表
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Table,
  ConfigProvider,
  Empty,
  Row,
  Input,
  Select,
  Tooltip,
  message,
} from "antd";
import { PageControl } from "@/components";
import "./SelectQuestionList.less";
import User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import _ from "underscore";
import Bus from "@/core/bus";

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 SelectQuestionList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: {
        current: 1,
        size: 10,
        order: "ACCURACY_DESC",
        categoryId: null, // 当前题库分类Id
        questionName: null, // 题目名称
        questionType: null, // 题目类型
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      },
      dataSource: [],
      selectQuestionKeys: [],
    };
  }

  componentDidMount() {
    this.queryQuestionModalList()
    Bus.bind('queryQuestionModalList', (selectedCategoryId) => {
      selectedCategoryId = selectedCategoryId === "null" ? null : selectedCategoryId;
      this.InitSearch(selectedCategoryId)
    })
  }

  componentWillUnmount() {
    Bus.unbind('queryQuestionModalList', this.queryQuestionModalList)
  }

  // 初始化列表查询
  InitSearch = (categoryId) => {
    const _query = {
      ...this.state.query,
      categoryId,
      current: 1,
      order: "UPDATED_DESC", // 排序规则
      questionName: null, // 题目名称
      questionType: null, // 题目类型
    };
    this.setState({ query: _query }, () => {
      this.queryQuestionModalList();
    });
  };

  queryQuestionModalList = () => {
    AidToolService.queryQuestionPageList(this.state.query).then((res) => {
      const { records = [], total = 0 } = res.result;
      this.setState({ dataSource: records, total });
    });
  };

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

  // 表头设置
  parseColumns = () => {
    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="tool-list"
              title={
                <div style={{ maxWidth: 700, width: "auto" }}>{handleVal}</div>
              }
              placement="topLeft"
              overlayStyle={{ maxWidth: 700 }}
            >
              {handleVal}
            </Tooltip>
          );
        },
      },
      {
        title: "题型",
        key: "questionTypeEnum",
        dataIndex: "questionTypeEnum",
        render: (val) => {
          return questionTypeEnum[val];
        },
      },
      {
        title: "正确率",
        key: "accuracy",
        dataIndex: "accuracy",
        sorter: true,
        showSorterTooltip: false,
        render: (val) => {
          return val + "%";
        },
      },
    ];
    return columns;
  };

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

  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    let _query = this.state.query;
    _query.size = size;
    this.setState({ query: _query }, () => this.queryQuestionModalList());
  };

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

  // 选择题目-单项选择
  selectQuestionRow = (record, selected) => {
    const { selectQuestionKeys } = this.state;
    let _list = [];
    if (
      selected ||
      !_.find(selectQuestionKeys, (item) => item.id == record.id)
    ) {
      _list = _.uniq(
        selectQuestionKeys.concat([record]),
        false,
        (item) => item.id
      );
    } else {
      _list = _.reject(selectQuestionKeys, (item) => item.id === record.id);
    }
    if (_list.length > 150) {
      return message.warning("一份试卷最多支持150道题目");
    }
    this.setState({ selectQuestionKeys: _list });
  };

  // 选择题目-当前全选
  selectQuestionAll = (selected, selectedRows, changeRows) => {
    const { selectQuestionKeys } = this.state;
    let _list = [];
    if (selected) {
      _list = _.uniq(
        selectQuestionKeys.concat(changeRows),
        false,
        (item) => item.id
      );
    } else {
      _list = _.reject(selectQuestionKeys, (item) =>
        _.find(changeRows, (data) => data.id === item.id)
      );
    }
    if (_list.length > 150) {
      message.warning("一份试卷最多支持150道题目");
      const extraLength = _list.length - 150;
      _list.splice(_list.length - extraLength, extraLength);
    }
    this.setState({ selectQuestionKeys: _list });
  };

  render() {
    const {
      dataSource = [],
      total,
      query,
      selectQuestionKeys = [],
    } = this.state;
    const { current, size, questionName, questionType } = query;
    const rowSelection = {
      columnWidth: 48,
      selectedRowKeys: _.pluck(selectQuestionKeys, "id"),
      onSelect: (record, selected) => {
        this.selectQuestionRow(record, selected);
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        this.selectQuestionAll(selected, selectedRows, changeRows);
      },
    };
    const singleCount = _.filter(
      selectQuestionKeys,
      (item) => item.questionTypeEnum === "SINGLE_CHOICE"
    ).length;
    const multiCount = _.filter(
      selectQuestionKeys,
      (item) => item.questionTypeEnum === "MULTI_CHOICE"
    ).length;
    const judgeCount = _.filter(
      selectQuestionKeys,
      (item) => item.questionTypeEnum === "JUDGE"
    ).length;
    const gapCount = _.filter(
      selectQuestionKeys,
      (item) => item.questionTypeEnum === "GAP_FILLING"
    ).length;
    const indefiniteCount = _.filter(
      selectQuestionKeys,
      (item) => item.questionTypeEnum === "INDEFINITE_CHOICE"
    ).length;
    return (
      <div className="select-question-list">
        <div className="select-question-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: 178 }}
                  onChange={(e) => {
                    this.handleChangeQuery("questionName", e.target.value);
                  }}
                  onSearch={() => {
                    this.queryQuestionModalList();
                  }}
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                />
              </div>

              <div className="search-condition__item">
                <span className="search-label">题型：</span>
                <Select
                  placeholder="请选择题目类型"
                  value={questionType}
                  style={{ width: 178 }}
                  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>
        <div className="select-tip-box">
          <div>
            <span className="icon iconfont tip-icon">&#xe61d;</span>
            <span style={{marginRight: 8}}>已选<span style={{color: "#FFB714"}}>{selectQuestionKeys.length}</span>题</span>
            {selectQuestionKeys.length > 0 && (
              <span>(
                {singleCount > 0 && `单选题${singleCount}题`}
                {multiCount > 0 && `、多选题${multiCount}题`}
                {judgeCount > 0 && `、判断题${judgeCount}题`}
                {gapCount > 0 && `、填空题${gapCount}题`}
                {indefiniteCount > 0 && `、不定项选择题${indefiniteCount}题`})
              </span>
            )}
          </div>
          {selectQuestionKeys.length > 0 && (
            <span className="clear-btn" onClick={() => this.setState({selectQuestionKeys:[]})}>清空</span>
          )}
        </div>
        <div className="select-question-content">
          <ConfigProvider renderEmpty={this.customizeRenderEmpty}>
            <Table
              rowSelection={rowSelection}
              rowKey={(record) => record.id}
              dataSource={dataSource}
              columns={this.parseColumns()}
              pagination={false}
              bordered
            />
          </ConfigProvider>
          <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.queryQuestionModalList()
                );
              }}
              showSizeChanger={true}
              onShowSizeChange={this.onShowSizeChange}
            />
          </div>
        </div>
      </div>
    );
  }
}

export default SelectQuestionList;
