/*
 * @Author: yuananting
 * @Date: 2021-02-25 11:23:47
 * @LastEditors: yuananting
 * @LastEditTime: 2021-06-03 17:13:30
 * @Description: 助学工具-题库-试卷列表数据
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Dropdown,
  Row,
  Input,
  Tooltip,
  Menu,
  Button,
  Modal,
  message,
  ConfigProvider,
  Empty,
} from "antd";
import { PageControl, XMTable } from "@/components";
import "./PaperList.less";
import { Route, withRouter } from "react-router-dom";
import OperatePaper from "@/modules/teach-tool/paper-manage/OperatePaper";
import AddExam from "@/modules/teach-tool/examination-manager/AddExam";
import User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import Service from "@/common/js/service";
import _ from "underscore";
import PaperPreviewModal from "../modal/PreviewPaperModal";
import MoveModal from '../../modal/MoveModal';
import Bus from "@/core/bus";
import college from '@/common/lottie/college';


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, // 试卷预览模态框
      loading: false,
      selectedPaperKeys: [],
      paperInfo: {}, // 选择的某份试卷用于组织考试
    };
  }

  componentDidMount() {
    this.queryPaperPageList();
    this.queryCategoryTree();
    Bus.bind("queryPaperPageList", (selectedCategoryId, count) => {
      selectedCategoryId =
        selectedCategoryId === "null" ? null : selectedCategoryId;
      this.clearSelect();
      this.setState({ loading: true });
      if (count >= 100) {
        setTimeout(() => {
          this.InitSearch(selectedCategoryId);
        }, 5000);
      } else {
        this.InitSearch(selectedCategoryId);
      }
    });
  }

  componentWillUnmount() {
    Bus.unbind("queryPaperPageList", this.queryPaperPageList);
  }
  
  // 查询分类树
  queryCategoryTree = () => {
    let query = {
      bizType: 'PAPER',
      count: true,
      source: 0,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    AidToolService.queryCategoryTree(query).then((res) => {
      const { categoryList = [] } = res.result;
      let list = this.renderTreeNodes(categoryList);
      this.setState({ paperData: list });
    });
  }

  renderTreeNodes = (data) => {
    let newTreeData = data.map((item) => {
      item.title = item.categoryName;
      item.value = item.id;
      item.key = item.id;
      if (item.sonCategoryList) {
        item.children = this.renderTreeNodes(item.sonCategoryList);
      }
      return item;
    });
    return newTreeData;
  };

  // 初始化列表查询
  InitSearch = (categoryId) => {
    const _query = {
      ...this.state.query,
      categoryId,
      current: 1,
      paperName: null, // 试卷名称
    };
    this.setState({ query: _query }, () => {
      this.queryPaperPageList();
    });
  };

  // 查询试卷列表
  queryPaperPageList = async () => {
    const res = await AidToolService.queryPaperPageList(this.state.query);
    const { records = [], total = 0 } = res.result;
    this.setState({ dataSource: records, total, loading: false });
  };

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

  // 编辑试卷
  editPaper = (record) => {
    if (record.relatedExam === 0) {
      const { categoryId } = this.state.query;
      const { match } = this.props;
      window.RCHistory.push({
        pathname: `${match.url}/paper-operate-page/operate?type=edit&paperId=${record.paperId}&categoryId=${categoryId}`,
      });
    } else {
      return Modal.info({
        title: "无法编辑",
        icon: (
          <span className="icon iconfont default-confirm-icon">&#xe834;</span>
        ),
        content:
          "该试卷已被考试采用，无法继续编辑。如需修改，请复制一份进行修改。",
        okText: "我知道了",
      });
    }
  };

  organizeExam = (record) => {
    const { match } = this.props;
    this.setState(
      {
        paperInfo: record,
      },
      () => {
        window.RCHistory.push({
          pathname: `${match.url}/exam-operate-page`,
        });
      }
    );
  };

  // 删除试卷
  deletePaper = (record) => {
    let params = {
      paperId: record.paperId,
      source: 0,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
    };
    AidToolService.deletePaper(params).then((res) => {
      if (res.success) {
        message.success("删除成功");
        const { query, total, selectedPaperKeys } = this.state;
        const { size, current } = query;
        const _query = query;
        let data = {};
        
        if (total / size < current) {
          if (total % size === 1) {
            _query.current = 1;
          }
        }
        data.query = _query;
        if (selectedPaperKeys.includes(record.paperId)) {
          data.selectedPaperKeys = _.reject(selectedPaperKeys, item => item === record.paperId);
        }
        this.setState(data, () => {
          this.queryPaperPageList();
          Bus.trigger("queryCategoryTree", "remain");
        });
      }
    });
  };

  // 删除试卷确认
  confirmDeletePaper = (record) => {
    if (record.relatedExam === 0) {
      return Modal.confirm({
        title: "删除试卷",
        content: "确认要删除该试卷吗？",
        icon: (
          <span className="icon iconfont default-confirm-icon">&#xe839; </span>
        ),
        okText: "删除",
        cancelText: "取消",
        onOk: () => {
          this.deletePaper(record);
        },
      });
    } else {
      return Modal.info({
        title: "删除试卷",
        content: "该试卷已被考试采用，无法删除。",
        icon: (
          <span className="icon iconfont default-confirm-icon">&#xe834; </span>
        ),
        okText: "我知道了",
      });
    }
  };

  // 表头设置
  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",
        width: this.props.type !== "modal-select" ? "16%" : "24%",
        render: (val, record) => {
          return (
            <span>
              {record.passScore}/{record.totalScore}
            </span>
          );
        },
      },
      {
        title: "题目数量",
        key: "questionCnt",
        dataIndex: "questionCnt",
        width: this.props.type !== "modal-select" ? "12%" : "20%",
        align: "right",
        render: (val, record) => {
          return this.props.type !== "modal-select" ? (
            <span>{record.questionCnt}</span>
          ) : (
            <Tooltip
              overlayClassName="tool-list"
              title={
                <div>
                  <div className="item">
                    单选题:{record.singleChoiceCnt || 0}个
                  </div>
                  <div className="item">
                    多选题:{record.multiChoiceCnt || 0}个
                  </div>
                  <div className="item">判断题:{record.judgeCnt || 0}个</div>
                  <div className="item">
                    填空题:{record.gapFillingCnt || 0}个
                  </div>
                  <div className="item">
                    不定项选择题:{record.indefiniteChoiceCnt || 0}个
                  </div>
                </div>
              }
              placement="top"
              overlayStyle={{ maxWidth: 700 }}
            >
              <span>{record.questionCnt}</span>
            </Tooltip>
          );
        },
      },
    ];

    if (this.props.type !== "modal-select") {
      const isPermiss = ["CloudManager", "StoreManager"].includes(
        User.getUserRole()
      );
      columns.push({
        title: "关联考试数",
        key: "relatedExam",
        dataIndex: "relatedExam",
        width: this.props.type !== "modal-select" ? "16%" : "24%",
        align: "right",
      });
      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>
              {isPermiss && (
                <span className="record-operate__item split"> | </span>
              )}
              {isPermiss && (
                <div
                  className="record-operate__item"
                  onClick={() => this.copyPaper(record)}
                >
                  复制
                </div>
              )}
              {isPermiss && (
                <span className="record-operate__item split"> | </span>
              )}
              {isPermiss && (
                <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="organizeExam">
          <span onClick={() => this.organizeExam(item)}>组织考试</span>
        </Menu.Item>
        <Menu.Item key="del">
          <span onClick={() => this.confirmDeletePaper(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] || {});
  };

  batchMove = () => {
    const { selectedPaperKeys } = this.state;
    if (_.isEmpty(selectedPaperKeys)) {
      message.warning('请先选择要移动的试卷');
      return null;
    }
    this.setState({ openMoveModal: true });
  }

  batchMoveRemote = (categoryId) => {
    const { selectedPaperKeys, query } = this.state;
    const data = {
      categoryId,
      paperId: selectedPaperKeys,
      source: 0,
      tenantId: User.getStoreId(),
      userId: User.getUserId(),
    };
    Service.Hades('public/hades/batchMovePaperCategory', data, { reject: true }).then((res) => {
      if (res.success) {
        message.success('移动成功');
        this.setState(
          {
            query: {
              ...query,
              current: 1,
            },
          },
          () => {
            this.queryPaperPageList();
          }
        );
        Bus.trigger("queryCategoryTree", "remain");
        this.clearSelect();
      } else {
        message.error('移动失败');
      }
    }).catch(() => {
      message.error('移动失败');
    })
  }

  batchDelete = () => {
    const { selectedPaperKeys, query } = this.state;
    if (_.isEmpty(selectedPaperKeys)) {
      message.warning('请先选择要删除的试卷');
      return null;
    }
    Modal.confirm({
      title: "确定要删除试卷吗？",
      content: "删除后，不可恢复。",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        const data = {
          paperId: selectedPaperKeys,
          source: 0,
          tenantId: User.getStoreId(),
          userId: User.getUserId(),
        };
        Service.Hades('public/hades/batchDeletePaper', data, { reject: true }).then((res) => {
          if (res.success) {
            message.success('删除成功');
            this.setState(
              {
                query: {
                  ...query,
                  current: 1,
                },
              },
              () => {
                this.queryPaperPageList();
              }
            );
            Bus.trigger("queryCategoryTree", "remain");
            this.clearSelect();
          } else {
            message.error('删除失败');
          }
        }).catch(() => {
          message.error('删除失败');
        })
      },
    })
  }

  onSelectPaper = (selectedPaperKeys) => {
    if (selectedPaperKeys.length > 50) {
      const extraLength = selectedPaperKeys.length - 50;
      selectedPaperKeys.splice(selectedPaperKeys.length - extraLength, extraLength);
      message.warning('最多只能选择50个试卷');
    }
    this.setState({ selectedPaperKeys });
  };

  clearSelect = () => {
    this.setState({ selectedPaperKeys: [] });
  }

  render() {
    const {
      dataSource = [],
      total,
      query,
      paperPreviewModal,
      selectedRowKeys,
      loading,
      selectedPaperKeys,
      openMoveModal,
      paperData,
      paperInfo,
    } = this.state;
    const { current, size, categoryId, paperName } = query;
    const paperRowSelection = {
      selectedRowKeys: selectedPaperKeys,
      preserveSelectedRowKeys: true,
      onChange: this.onSelectPaper,
    }
    const rowSelection = {
      type: "radio",
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const isPermiss = ["CloudManager", "StoreManager"].includes(
      User.getUserRole()
    );
    const { match } = this.props;
    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: 177 }}
                  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" && isPermiss && (
          <div className="select-box">
            {_.isEmpty(selectedPaperKeys) ?
              (!!categoryId && <Button
                type="primary"
                className="mr8"
                onClick={() => {
                  window.RCHistory.push({
                    pathname: `${match.url}/paper-operate-page?type=new&categoryId=${categoryId}`,
                  });
                }}
              >
                新建试卷
              </Button>)
              : <div className="select-container">
                <span className="con">
                  <div>
                    <span className="icon iconfont tip">&#xe6f2;</span>
                    <span className="text">已选择{selectedPaperKeys.length}项</span>
                  </div>
                  <div>
                    <span className="clear" onClick={this.clearSelect}>清空</span>
                  </div>
                </span>
              </div>
            }
            <Button
              className="mr8"
              onClick={() => {
                this.batchMove();
              }}
            >批量移动</Button>
            <Button
              onClick={() => {
                this.batchDelete();
              }}
            >批量删除</Button>
          </div>
        )}

        <div className="paper-list-content">
          {this.props.type !== "modal-select" ? (
            <XMTable
              rowKey={(record) => record.paperId}
              rowSelection={paperRowSelection}
              dataSource={dataSource}
              columns={this.parseColumns()}
              pagination={false}
              bordered
              loading={loading}
              renderEmpty={{
                image: college,
                description: <span style={{ display: 'block', paddingBottom: 24 }}>还没有试卷</span>
              }}
            />
          ) : (
            <XMTable
              rowKey={(record) => record.paperId}
              dataSource={dataSource}
              size={this.props.type == "modal-select" ? "small" : "middle"}
              rowKey={(item) => {
                return item.paperId;
              }}
              rowSelection={rowSelection}
              columns={this.parseColumns()}
              pagination={false}
              bordered
              renderEmpty={{
                image: college,
                description: <span style={{ display: 'block', paddingBottom: 24 }}>还没有试卷</span>
              }}
            />
          )}

          {total > 0 && (
            <div className="box-footer">
              <PageControl
                current={current - 1}
                pageSize={size}
                total={total}
                size={this.props.type == "modal-select" ? "small" : "middle"}
                toPage={(page) => {
                  const _query = { ...query, current: page + 1 };
                  this.setState({ query: _query }, () =>
                    this.queryPaperPageList()
                  );
                }}
                showSizeChanger={true}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          )}
          {paperPreviewModal}
          {openMoveModal &&
            <MoveModal
              visible={openMoveModal}
              title="试卷"
              data={paperData}
              categoryId={query.categoryId}
              length={selectedRowKeys.length}
              onCancel={() => this.setState({ openMoveModal: false })}
              onOk={(categoryId) => {
                this.batchMoveRemote(categoryId);
                this.setState({ openMoveModal: false });
              }}
            />
          }
        </div>
        <Route
          path={`${match.url}/paper-operate-page`}
          component={OperatePaper}
        />
        <Route
          path={`${match.url}/exam-operate-page`}
          render={() => {
            return (
              <AddExam
                paperInfo={paperInfo}
                type="organizeExam"
              />
            );
          }}
        />
      </div>
    );
  }
}

export default withRouter(PaperList);
