/*
 * @Author: yuananting
 * @Date: 2021-03-27 16:15:13
 * @LastEditors: yuananting
 * @LastEditTime: 2021-04-02 10:51:10
 * @Description: 助学工具-新建试卷
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Form,
  Button,
  Input,
  Table,
  InputNumber,
  ConfigProvider,
  Empty,
  Tooltip,
  message,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import ShowTips from "@/components/ShowTips";
import Breadcrumbs from "@/components/Breadcrumbs";
import "./NewExaminationPaper.less";
import SelectQuestionModal from "./modal/SelectQuestionModal";
import User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";

const questionTypeEnum = {
  SINGLE_CHOICE: "单选题",
  MULTI_CHOICE: "多选题",
  JUDGE: "判断题",
  GAP_FILLING: "填空题",
  INDEFINITE_CHOICE: "不定项选择题",
};
class NewExaminationPaper extends Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      formData: {
        categoryId: getParameterByName("categoryId"), // 分类ID
        singleChoiceCnt: 0, // 单选题数量
        multiChoiceCnt: 0, // 多选题数量
        judgeCnt: 0, // 判断题数量
        gapFillingCnt: 0, // 填空题数量
        indefiniteChoiceCnt: 0, // 不定项选择题数量
        paperName: null, // 试卷名称
        passRate: 60, // 及格线
        passScore: 0, // 及格分
        questionCnt: 0, // 题目数量
        totalScore: 0, // 总分
        questionList: [], // 题目列表
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      },
      selectQuestionModal: null,
      selectQuestionList: [],
    };
  }

  componentDidMount() {
    if (getParameterByName("paperId")) {
      // 编辑
      this.setState({ currentOperate: "edit" });
      this.queryPaperDetail();
    }
  }

  // 编辑试卷时获取相应试卷详情
  queryPaperDetail = () => {
    let query = {
      categoryId: getParameterByName("categoryId"),
      paperId:getParameterByName("paperId"),
      source: 0,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    AidToolService.queryPaperDetail(query).then((res) => {
      const { result } = res;
      this.setState({ selectQuestionList: result.questionList, formData: result, },() => {
        this.setFormData([])
      })
    });
  };

  // 校验试卷名称是否重名
  checkExistPaperName = (paperName) => {};
  
  // 自定义表格空状态
  customizeRenderEmpty = () => {
    return (
      <Empty
        image="https://image.xiaomaiketang.com/xm/emptyTable.png"
        imageStyle={{
          height: 100,
        }}
        description={"请在右上角选择出题方式添加题"}
      ></Empty>
    );
  };

  setFormData = (list) => {
    const { formData, selectQuestionList } = this.state;
    const _selectQuestionList = [...selectQuestionList, ...list];
    const totalScore = _selectQuestionList.reduce((prev, cur) => {
      return prev + Number(cur.score) || 0;
    }, 0);
    const passScore = Math.round(totalScore * formData.passRate * 0.01);
    this.setState({
      selectQuestionList: _selectQuestionList,
      formData: {
        ...formData,
        singleChoiceCnt: _.filter(
          _selectQuestionList,
          (item) => item.questionType === "SINGLE_CHOICE"
        ).length,
        multiChoiceCnt: _.filter(
          _selectQuestionList,
          (item) => item.questionType === "MULTI_CHOICE"
        ).length,
        judgeCnt: _.filter(
          _selectQuestionList,
          (item) => item.questionType === "JUDGE"
        ).length,
        gapFillingCnt: _.filter(
          _selectQuestionList,
          (item) => item.questionType === "GAP_FILLING"
        ).length,
        indefiniteChoiceCnt: _.filter(
          _selectQuestionList,
          (item) => item.questionType === "INDEFINITE_CHOICE"
        ).length,
        passScore,
        questionCnt: _selectQuestionList.length,
        totalScore,
      },
    });
  };

  // 选择题目
  chooseQuestion = () => {
    const m = (
      <SelectQuestionModal
        setSelectedQuestion={(list) => {
          this.setFormData(list);
          this.setState({ selectQuestionModal: null });
        }}
        close={() => {
          this.setState({
            selectQuestionModal: null,
          });
        }}
      />
    );
    this.setState({ selectQuestionModal: m });
  };

  // 移动已选题目
  handleMoveItem = (index, moveLength) => {
    const { selectQuestionList } = this.state;
    const item = selectQuestionList.splice(index + moveLength, 1);
    selectQuestionList.splice(index, 0, item[0]);
    this.setState({ selectQuestionList });
  };

  // 移除已选题目
  handleDelItem = (delId) => {
    const { selectQuestionList } = this.state;
    this.setState(
      {
        selectQuestionList: [...selectQuestionList].filter(
          (item) => item.id !== delId
        ),
      },
      () => this.setFormData([])
    );
  };

  // 保存题目
  saveExaminationPaper = async () => {
    try {
      await this.formRef.current.validateFields();
      const { selectQuestionList, formData } = this.state;
      let questionList = [];
      selectQuestionList.forEach((item, index) => {
        questionList.push({
          categoryId: item.categoryId,
          portionScore: item.portionScore || 0,
          questionId: item.id,
          questionType: item.questionType,
          score: item.score || 2,
          sort: index,
        });
      });
      this.setState(
        {
          formData: {
            ...formData,
            questionList,
          },
        },
        () => {
          AidToolService.createPaper(this.state.formData).then((res) => {
            if (res.success){
              message.success("新建成功");
              window.RCHistory.push({
                pathname: `/examination-paper-index?categoryId=${getParameterByName("categoryId")}`,
              });
            }
          });
        }
      );
    } catch (e) {
      console.log(e);
    }
  };

  // 表头设置
  parseColumns = () => {
    const { selectQuestionList } = this.state;
    const columns = [
      {
        title: "序号",
        dataIndex: "index",
        width: "10%",
        render: (val, record, index) => {
          return <span>{index + 1}</span>;
        },
      },
      {
        title: "题型",
        dataIndex: "questionType",
        width: "16%",
        filters: [
          {
            text: "单选题",
            value: "SINGLE_CHOICE",
          },
          {
            text: "多选题",
            value: "MULTI_CHOICE",
          },
          {
            text: "判断题",
            value: "JUDGE",
          },
          {
            text: "填空题",
            value: "GAP_FILLING",
          },
          {
            text: "不定项选择题",
            value: "INDEFINITE_CHOICE",
          },
        ],
        filterMultiple: false,
        onFilter: (value, record) => record.questionType.indexOf(value) === 0,
        render: (val) => questionTypeEnum[val],
      },
      {
        title: "题目",
        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: (
          <Tooltip title="多选题和填空题的漏选/半对得分不能高于题目本身分值">
            分值
          </Tooltip>
        ),
        dataIndex: "score",
        width: "12%",
        render: (val, record, index) => {
          return (
            <InputNumber
              min={1}
              max={100}
              value={record.score || 2}
              onChange={(value) => {
                const _selectQuestionList = [...selectQuestionList];
                this.setState(
                  {
                    selectQuestionList: _selectQuestionList.map((item) =>
                      item.id === record.id ? { ...item, score: value } : item
                    ),
                  },
                  () => this.setFormData([])
                );
              }}
            />
          );
        },
      },
      {
        dataIndex: "portionScore",
        width: "18%",
        render: (val, record, index) => {
          return (
            ["MULTI_CHOICE", "GAP_FILLING", "INDEFINITE_CHOICE"].includes(
              record.questionType
            ) && (
              <div>
                {record.questionType === "GAP_FILLING" ? (
                  <span>半对得</span>
                ) : (
                  <span>漏选得</span>
                )}{" "}
                <InputNumber
                  min={0}
                  max={record.score}
                  value={record.portionScore || 0}
                  onChange={(value) => {
                    const _selectQuestionList = [...selectQuestionList];
                    this.setState(
                      {
                        selectQuestionList: _selectQuestionList.map((item) =>
                          item.id === record.id
                            ? { ...item, portionScore: value }
                            : item
                        ),
                      },
                      () => this.setFormData([])
                    );
                  }}
                />
              </div>
            )
          );
        },
      },
      {
        title: "操作",
        dataIndex: "operate",
        width: "16%",
        render: (val, record, index) => {
          return (
            <div className="record-operate">
              <div
                className={
                  index > 0 ? "record-operate__item" : "record-operate__ban"
                }
                onClick={() => {
                  this.handleMoveItem(index, -1);
                }}
              >
                上移
              </div>
              <span className="record-operate__item split"> | </span>
              <div
                className={
                  index < selectQuestionList.length - 1
                    ? "record-operate__item"
                    : "record-operate__ban"
                }
                onClick={() => {
                  this.handleMoveItem(index, 1);
                }}
              >
                下移
              </div>
              <span className="record-operate__item split"> | </span>
              <div
                className="record-operate__item"
                onClick={() => {
                  this.handleDelItem(record.id);
                }}
              >
                移除
              </div>
            </div>
          );
        },
      },
    ];
    return columns;
  };

  render() {
    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 22 },
    };

    const { selectQuestionModal, selectQuestionList, formData } = this.state;
    const {
      paperName,
      passRate,
      passScore,
      totalScore,
      questionCnt,
    } = formData;

    const singleQuestion = _.filter(
      selectQuestionList,
      (item) => item.questionType === "SINGLE_CHOICE"
    );
    const multiQuestion = _.filter(
      selectQuestionList,
      (item) => item.questionType === "MULTI_CHOICE"
    );
    const judgeQuestion = _.filter(
      selectQuestionList,
      (item) => item.questionType === "JUDGE"
    );
    const gapQuestion = _.filter(
      selectQuestionList,
      (item) => item.questionType === "GAP_FILLING"
    );
    const indefiniteQuestion = _.filter(
      selectQuestionList,
      (item) => item.questionType === "INDEFINITE_CHOICE"
    );

    const singleScore = singleQuestion.reduce((prev, cur) => {
      return prev + Number(cur.score) || 0;
    }, 0);
    const multiScore = multiQuestion.reduce((prev, cur) => {
      return prev + Number(cur.score) || 0;
    }, 0);
    const judgeScore = judgeQuestion.reduce((prev, cur) => {
      return prev + Number(cur.score) || 0;
    }, 0);
    const gapScore = gapQuestion.reduce((prev, cur) => {
      return prev + Number(cur.score) || 0;
    }, 0);
    const indefiniteScore = indefiniteQuestion.reduce((prev, cur) => {
      return prev + Number(cur.score) || 0;
    }, 0);

    return (
      <div className="page new-examination-paper">
        <Breadcrumbs navList={"新建试卷"} goBack={() => this.handleGoBack()} />
        <div className="box">
          <div className="show-tips">
            <ShowTips message="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企培保有依据国家规定及平台规则进行处理的权利" />
          </div>
          <Form
            ref={this.formRef}
            {...formItemLayout}
            style={{ marginTop: 32 }}
          >
            <Form.Item
              name="paperName"
              label="试卷名称："
              required
              rules={[
                {
                  required: true,
                  message: "请输入试卷名称",
                },
                // ({ getFieldValue }) => ({
                //   validator(_, value) {
                //     if (_that.checkExistPaperName( value)) {
                //       return Promise.reject("该试卷名称已存在");
                //     } else {
                //       return Promise.resolve();
                //     }
                //   },
                // }),
              ]}
            >
              <Input
                value={paperName}
                autoComplete="off"
                maxLength={40}
                placeholder="请输入试卷名称（40字以内）"
                onChange={(e) => {
                  this.setState({
                    formData: {
                      ...formData,
                      paperName: e.target.value.trim(),
                    },
                  });
                }}
              />
            </Form.Item>

            <Form.Item label="及格线：" required>
              <div>
                <Form.Item
                  noStyle
                  initialValue={60}
                  name="passRate"
                  rules={[
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value) {
                          return Promise.reject("请输入及格线");
                        } else {
                          return Promise.resolve();
                        }
                      },
                    }),
                  ]}
                >
                  <InputNumber
                    min={1}
                    max={100}
                    value={passRate}
                    onChange={(value) => {
                      this.setState(
                        {
                          formData: {
                            ...formData,
                            passRate: value,
                          },
                        },
                        () => this.setFormData([])
                      );
                    }}
                  />
                </Form.Item>{" "}
                %
                <span style={{ marginLeft: 20 }}>
                  总分（{totalScore}）*及格线（{passRate || 0}%）=及格分数（
                  {passScore}）
                </span>
              </div>
            </Form.Item>

            <Button icon={<PlusOutlined />} onClick={this.chooseQuestion}>
              自选题目
            </Button>
            <div style={{ margin: "10px 0 20px" }}>
              总计{totalScore}分，共{questionCnt}题。{" "}
              {singleQuestion.length > 0 &&
                `单选题${singleQuestion.length}题，共
              ${singleScore}分；`}
              {multiQuestion.length > 0 &&
                `多选题${multiQuestion.length}题，共${multiScore}分；`}
              {judgeQuestion.length > 0 &&
                `判断题
              ${judgeQuestion.length}题，共${judgeScore}分，`}
              {gapQuestion.length > 0 &&
                `填空题${gapQuestion.length}题，共${gapScore}
              分，`}
              {indefiniteQuestion.length > 0 &&
                `不定项选择题${indefiniteQuestion.length}题，共${indefiniteScore}分`}
            </div>

            <ConfigProvider renderEmpty={this.customizeRenderEmpty}>
              <Table
                columns={this.parseColumns()}
                dataSource={selectQuestionList}
                pagination={false}
              />
            </ConfigProvider>
          </Form>
        </div>
        <div className="footer">
          <Button>取消</Button>
          <Button>预览</Button>
          <Button
            type="primary"
            onClick={() => this.saveExaminationPaper()}
          >
            保存
          </Button>
        </div>
        {selectQuestionModal}
      </div>
    );
  }
}

export default NewExaminationPaper;
