/*
 * @Author: yuananting
 * @Date: 2021-02-25 11:23:47
 * @LastEditors: yuananting
 * @LastEditTime: 2021-04-01 15:06:37
 * @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 User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import _ from "underscore";
import PaperPreviewModal from "../modal/PreviewPaperModal";

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, // 试卷预览模态框
    };
  }

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

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

  // 预览试卷
  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;
    window.RCHistory.push({
      pathname: `/paper-operate-page?type=copy&paperId=${record.paperId}&categoryId=${categoryId}`,
    });
  };

  // 编辑试卷
  editPaper = (record) => {
    const { categoryId } = this.state.query;
    window.RCHistory.push({
      pathname: `/paper-operate-page/operate?type=edit&paperId=${record.paperId}&categoryId=${categoryId}`,
    });
  };

  // 删除试卷
  deletePaper(record) {
    return Modal.confirm({
      title: "提示",
      content: "确定要删除此试卷吗？",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        let params = {
          categoryId: this.state.query.categoryId,
          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());
          }
        });
      },
    });
  }

  // 自定义表格空状态
  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",

        render: (val, record) => {
          return (
            <span>
              {record.passScore}/{record.totalScore}
            </span>
          );
        },
      },
      {
        title: "题目数量",
        key: "questionCnt",
        dataIndex: "questionCnt",

      },
      {
        title: "关联考试数",
        key: "relatedExam",
        dataIndex: "relatedExam",

      },
    ];

    if ((this.props.type !== 'modal-select')) {
      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>
              <span className="record-operate__item split"> | </span>
              <div
                className="record-operate__item"
                onClick={() => this.copyPaper(record)}
              >
                复制
              </div>
              <span className="record-operate__item split"> | </span>
              <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.deletePaper(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 } = this.state;
    const { current, size, categoryId, paperName } = query;

    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    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: 200 }}
                  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') && <Button
            type="primary"
            onClick={() => {
              window.RCHistory.push({
                pathname: `/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
              onChange={this.handleChangeTable}
            /> :
              <Table
                rowKey={(record) => record.id}
                dataSource={dataSource}
                rowKey={(item) => {
                  return item.paperId
                }}
                rowSelection={rowSelection}
                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.queryPaperPageList()
                  );
                }}
                showSizeChanger={true}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          )}
          {paperPreviewModal}
        </div>
      </div>
    );
  }
}

export default PaperList;