/*
 * @Author: yuananting
 * @Date: 2021-02-25 13:46:35
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-29 20:24:01
 * @Description: 助学工具-题库-新建题目
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Tabs, Button, Tooltip, message, Modal } from "antd";
import Breadcrumbs from "@/components/Breadcrumbs";
import ShowTips from "@/components/ShowTips";
import "./AddNewQuestion.less";
import NewQuestionTab from "./components/NewQuestionTab";
import {
  defineJudgeOptionInfo,
  defineOptionInfo,
  defineQuestionInfo,
} from "../components/model";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import User from "@/common/js/user";

const { TabPane } = Tabs;
class AddNewQuestion extends Component {
  constructor(props) {
    super(props);
    let activeKey = "";
    if (getParameterByName("type")) {
      activeKey = getParameterByName("type");
    } else if (getParameterByName("key")) {
      activeKey = getParameterByName("key");
    } else {
      activeKey = "SINGLE_CHOICE";
    }
    this.state = {
      activeKey: activeKey,
      // 构建题目基本结构
      singleChoiceContent: defineQuestionInfo("SINGLE_CHOICE"), // 单选题
      multiChoiceContent: defineQuestionInfo("MULTI_CHOICE"), // 多选题
      judgeContent: defineQuestionInfo("JUDGE"), // 判断题
      gapFillingContent: defineQuestionInfo("GAP_FILLING"), // 填空题
      indefiniteChoiceContent: defineQuestionInfo("INDEFINITE_CHOICE"), // 不定项选择题
      currentOperate: "new",
    };
  }

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

  transferStemDocument = (txt) => {
    const template = `<p class='content'>${txt}</p>`;
    let doc = new DOMParser().parseFromString(template, "text/html");
    let p = doc.querySelector(".content");
    return p;
  };

  // 编辑题目时获取相应题目详情
  queryQuestionDetails = () => {
    let query = {
      id: getParameterByName("id"),
      source: 0,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    AidToolService.queryQuestionDetails(query).then((res) => {
      const { result = [] } = res;
      let stemContent = _.find(
        result.questionStemList,
        (contentItem) => contentItem.type === "RICH_TEXT"
      );
      const { questionTypeEnum } = result;
      switch (questionTypeEnum) {
        case "SINGLE_CHOICE":
          this.setState({ singleChoiceContent: result });
          break;
        case "MULTI_CHOICE":
          this.setState({ multiChoiceContent: result });
          break;
        case "JUDGE":
          this.setState({ judgeContent: result });
          break;
        case "GAP_FILLING":
          stemContent.content = stemContent.content
            .split("")
            .map((item) => {
              if (item === "_") {
                return `<input class="add-fill-line" disabled correctAnswerList="" id=${window.random_string(
                  16
                )} value="填空"/>`;
              }
              return item;
            })
            .join("");
          this.setState({ gapFillingContent: result });
          break;
        case "INDEFINITE_CHOICE":
          this.setState({ indefiniteChoiceContent: result });
          break;
      }
    });
  };

  // 保存并继续添加时重新构建题目结构
  handleRest = (type) => {
    this.setState({ currentOperate: "add" });
    switch (type) {
      case "SINGLE_CHOICE":
        let singleChoiceContent = defineQuestionInfo("SINGLE_CHOICE");
        for (var i = 0; i < 4; i++) {
          singleChoiceContent.optionList.push(defineOptionInfo());
        }
        this.setState({ singleChoiceContent });
        break;
      case "MULTI_CHOICE":
        let multiChoiceContent = defineQuestionInfo("MULTI_CHOICE");
        for (var i = 0; i < 4; i++) {
          multiChoiceContent.optionList.push(defineOptionInfo());
        }
        this.setState({ multiChoiceContent });
        break;
      case "JUDGE":
        let judgeContent = defineQuestionInfo("JUDGE");
        var judgeOptions = ["正确", "错误"];
        judgeOptions.forEach((item) => {
          judgeContent.optionList.push(defineJudgeOptionInfo(item));
        });
        this.setState({ judgeContent });
        break;
      case "GAP_FILLING":
        this.setState({
          gapFillingContent: defineQuestionInfo("GAP_FILLING"),
        });
        break;
      case "INDEFINITE_CHOICE":
        let indefiniteChoiceContent = defineQuestionInfo("INDEFINITE_CHOICE");
        for (var i = 0; i < 4; i++) {
          indefiniteChoiceContent.optionList.push(defineOptionInfo());
        }
        this.setState({ indefiniteChoiceContent });
    }
  };

  initOption = (content) => {
    chooseOptions.push(defineJudgeOptionInfo(content));
  };

  // 取消编辑并返回上一级路由
  handleGoBack = () => {
    Modal.confirm({
      title: "确定要返回吗？",
      content: "返回后，本次编辑的内容将不被保存",
      okText: "确认返回",
      cancelText: "留在本页",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>
      ),
      onOk: () => {
        window.RCHistory.push({
          pathname: `/question-bank-index?categoryId=${getParameterByName("categoryId")}`,
        });
      },
    });
  };

  // 校验保存题目
  confirmSaveQuestion = (next) => {
    const {
      singleChoiceContent,
      multiChoiceContent,
      judgeContent,
      gapFillingContent,
      indefiniteChoiceContent,
    } = this.state;
    switch (this.state.activeKey) {
      case "SINGLE_CHOICE":
        if (this.singleChoiceRef.checkInput() === 0) {
          this.saveCurrentQuestion(singleChoiceContent, "SINGLE_CHOICE", next);
        }
        break;
      case "MULTI_CHOICE":
        if (this.multiChoiceRef.checkInput() === 0) {
          this.saveCurrentQuestion(multiChoiceContent, "MULTI_CHOICE", next);
        }
        break;
      case "JUDGE":
        if (this.judgeRef.checkInput() === 0) {
          this.saveCurrentQuestion(judgeContent, "JUDGE", next);
        }
        break;
      case "GAP_FILLING":
        if (this.gapRef.checkInput() === 0) {
          this.saveCurrentQuestion(gapFillingContent, "GAP_FILLING", next);
        }
        break;
      case "INDEFINITE_CHOICE":
        if (this.indefiniteRef.checkInput() === 0) {
          this.saveCurrentQuestion(
            indefiniteChoiceContent,
            "INDEFINITE_CHOICE",
            next
          );
        }
        break;
    }
  };

  // 确认保存题目
  saveCurrentQuestion = (content, type, next) => {
    content.questionStemList.map((item, index) => {
      item.sort = index;
      return item;
    });
    content.optionList.map((item) => {
      item.questionOptionContentList.map((childItem, childIndex) => {
        childItem.sort = childIndex;
        return childItem;
      });
      return item;
    });
    content.questionAnswerDescList.map((item, index) => {
      item.sort = index;
      return item;
    });
    let params = {};
    let categoryId = getParameterByName("categoryId");
    if (getParameterByName("id") && this.state.currentOperate === "edit") {
      params = {
        ...content,
        id: getParameterByName("id"),
        categoryId: categoryId === "null" ? null : categoryId,
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      };

      AidToolService.editQuestion(params).then((res) => {
        if (res.success) {
          message.success("保存成功");
          if (next === "add") {
            this.handleRest(type);
          }
          if (next === "close") {
            window.RCHistory.push({
              pathname: `/question-bank-index?categoryId=${categoryId}`,
            });
          }
        }
      });
    } else {
      params = {
        ...content,
        categoryId,
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      };
      AidToolService.addQuestion(params).then((res) => {
        if (res.success) {
          message.success("保存成功");
          if (next === "add") {
            this.handleRest(type);
          }
          if (next === "close") {
            window.RCHistory.push({
              pathname: `/question-bank-index?categoryId=${categoryId}`,
            });
          }
        }
      });
    }
  };

  handleLogger = (en, cn) => {
    const { onLogger } = this.props;
    onLogger && onLogger(en, cn);
  };

  render() {
    const {
      activeKey,
      singleChoiceContent,
      multiChoiceContent,
      judgeContent,
      gapFillingContent,
      indefiniteChoiceContent,
    } = this.state;
    const categoryId = getParameterByName("categoryId");
    return (
      <div className="page add-new-question">
        <Breadcrumbs
          navList={
            getParameterByName("id") && this.state.currentOperate === "edit"
              ? "编辑题目"
              : "新增题目"
          }
          goBack={() => this.handleGoBack()}
        />
        <div className="box">
          <div className="show-tips">
            <ShowTips message="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企培保有依据国家规定及平台规则进行处理的权利" />
          </div>
          <Tabs
            style={{ marginTop: 32 }}
            activeKey={activeKey}
            onChange={(activeKey) => {
              this.setState({ activeKey });
            }}
          >
            <TabPane
              tab={
                <span>
                  <span
                    className="icon iconfont"
                    style={{
                      color:
                        activeKey === "SINGLE_CHOICE" ? "#ffb714" : "#CCCCCC",
                    }}
                  >
                    &#xe7fa;{" "}
                  </span>
                  <span>单选题</span>
                </span>
              }
              key="SINGLE_CHOICE"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.singleChoiceRef = ref;
                }}
                questionInfo={singleChoiceContent}
                onSetState={(newContent) => {
                  Object.assign(singleChoiceContent, newContent);
                }}
                onLogger={this.handleLogger}
              />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <span
                    className="icon iconfont"
                    style={{
                      color:
                        activeKey === "MULTI_CHOICE" ? "#ffb714" : "#CCCCCC",
                    }}
                  >
                    &#xe7fb;{" "}
                  </span>
                  <span>多选题</span>
                </span>
              }
              key="MULTI_CHOICE"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.multiChoiceRef = ref;
                }}
                questionInfo={multiChoiceContent}
                onSetState={(newContent) => {
                  Object.assign(multiChoiceContent, newContent);
                }}
                onLogger={this.handleLogger}
              />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <span
                    className="icon iconfont"
                    style={{
                      color: activeKey === "JUDGE" ? "#ffb714" : "#CCCCCC",
                    }}
                  >
                    &#xe7fc;{" "}
                  </span>
                  <span>判断题</span>
                </span>
              }
              key="JUDGE"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.judgeRef = ref;
                }}
                questionInfo={judgeContent}
                onSetState={(newContent) => {
                  Object.assign(judgeContent, newContent);
                }}
              />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <span
                    className="icon iconfont"
                    style={{
                      color:
                        activeKey === "GAP_FILLING" ? "#ffb714" : "#CCCCCC",
                    }}
                  >
                    &#xe7fd;{" "}
                  </span>
                  <span>填空题</span>
                </span>
              }
              key="GAP_FILLING"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.gapRef = ref;
                }}
                questionInfo={gapFillingContent}
                onSetState={(newContent) => {
                  Object.assign(gapFillingContent, newContent);
                }}
              />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <span
                    className="icon iconfont"
                    style={{
                      color:
                        activeKey === "INDEFINITE_CHOICE"
                          ? "#ffb714"
                          : "#CCCCCC",
                    }}
                  >
                    &#xe7fe;{" "}
                  </span>
                  <span>不定项选择题 </span>
                  <Tooltip title="至少有一项正确，至多不限的选择题，多项选择题的一种特殊形式">
                    <span
                      className="icon iconfont"
                      style={{ color: "#BFBFBF" }}
                    >
                      &#xe7c4;
                    </span>
                  </Tooltip>
                </span>
              }
              key="INDEFINITE_CHOICE"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.indefiniteRef = ref;
                }}
                questionInfo={indefiniteChoiceContent}
                onSetState={(newContent) => {
                  Object.assign(indefiniteChoiceContent, newContent);
                }}
                onLogger={this.handleLogger}
              />
            </TabPane>
          </Tabs>
        </div>
        <div className="footer">
          <Button
            onClick={() => {
              this.handleGoBack();
            }}
          >
            取消
          </Button>
          {categoryId && categoryId !== "null" && (
            <Button
              onClick={() => {
                this.confirmSaveQuestion("add");
              }}
            >
              保存并继续添加
            </Button>
          )}
          <Button
            type="primary"
            onClick={() => {
              this.confirmSaveQuestion("close");
            }}
          >
            保存
          </Button>
        </div>
      </div>
    );
  }
}

export default AddNewQuestion;
