/*
 * @Author: yuananting
 * @Date: 2021-03-27 16:15:13
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-31 19:50:36
 * @Description: 助学工具-新建试卷
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import {
  Form,
  Button,
  Input,
  Table,
  InputNumber,
  ConfigProvider,
  Empty,
  Tooltip,
} 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";

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: null, // 分类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(),
      },
    };
  }

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

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

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

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

  // 保存题目
  saveExaminationPaper = (totalScore) => {
    const { questionList } = this.state.formData;
    let _questionList = [];
    questionList.forEach((item, index) => {
      _questionList.push({
        categoryId: item.categoryId,
        portionScore: item.portionScore || 0,
        questionId: item.id,
        questionType: item.questionType,
        score: item.score || 2,
        sort: index,
      });
    });

    console.log(this.state);
    // try {
    //   await this.formRef.current.validateFields();
    // } catch (e) {
    //   console.log(e);
    // }
  };

  // 表头设置
  parseColumns = () => {
    const { formData } = 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 _questionList = [...formData.questionList];
                this.setState({
                  formData: {
                    ...formData,
                    questionList: _questionList.map((item) =>
                      item.id === record.id ? { ...item, score: value } : item
                    ),
                  },
                });
              }}
            />
          );
        },
      },
      {
        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 _questionList = [...formData.questionList];
                    this.setState({
                      formData: {
                        ...formData,
                        questionList: _questionList.map((item) =>
                          item.id === record.id
                            ? { ...item, portionScore: value }
                            : item
                        ),
                      },
                    });
                  }}
                />
              </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 < formData.questionList.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, formData } = this.state;
    const { paperName, passRate, questionList } = formData;

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

    const totalCount = questionList.length;
    const singleCount = singleQuestion.length;
    const multiCount = multiQuestion.length;
    const judgeCount = judgeQuestion.length;
    const gapCount = gapQuestion.length;
    const indefiniteCount = indefiniteQuestion.length;

    const totalScore = questionList.reduce((prev, cur) => {
      return prev + Number(cur.score) || 0;
    }, 0);
    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({ 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}
                    onBlur={(e) => {
                      this.setState({
                        formData: {
                          ...formData,
                          passRate: e.target.value,
                        },
                      });
                    }}
                  />
                </Form.Item>{" "}
                %
                <span style={{ marginLeft: 20 }}>
                  总分（{totalScore}）*及格线（{passRate || 0}%）=及格分数（
                  {Math.round(totalScore * passRate * 0.01)}）
                </span>
              </div>
            </Form.Item>

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

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

export default NewExaminationPaper;
