/*
 * @Author: yuananting
 * @Date: 2021-02-25 13:46:35
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-18 09:32:02
 * @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 { defineQuestionInfo } from "./components/model";
import QuestionBankService from "@/domains/question-bank-domain/QuestionBankService";
import User from "@/common/js/user";
import UploadOss from "@/core/upload";

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"), // 不定项选择题
    };
  }

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

  queryQuestionDetails = () => {
    let query = {
      id: getParameterByName("id"),
      source: 0,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    QuestionBankService.queryQuestionDetails(query).then((res) => {
      const { result = [] } = res;
      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":
          this.setState({ gapFillingContent: result });
          break;
        case "INDEFINITE_CHOICE":
          this.setState({ indefiniteChoiceContent: result });
          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")) {
      params = {
        ...content,
        id: getParameterByName("id"),
        categoryId: categoryId || null,
        source: 0,
        tenantId: User.getStoreId(),
        userId: User.getStoreUserId(),
      };

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

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

  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;
    }
  };

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

  render() {
    const {
      activeKey,
      singleChoiceContent,
      multiChoiceContent,
      judgeContent,
      gapFillingContent,
      indefiniteChoiceContent,
    } = this.state;
    return (
      <div className="page add-new-question">
        <Breadcrumbs
          navList={getParameterByName("id") ? "编辑题目" : "新增题目"}
          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 className="icon iconfont">&#xe7fa; 单选题</span>}
              key="SINGLE_CHOICE"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.singleChoiceRef = ref;
                }}
                questionInfo={singleChoiceContent}
                onSetState={(newContent) => {
                  console.log("newContent:", newContent)
                  Object.assign(singleChoiceContent, newContent);
                }}
                onLogger={this.handleLogger}
              />
            </TabPane>
            <TabPane
              tab={<span className="icon iconfont">&#xe7fb; 多选题</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 className="icon iconfont">&#xe7fc; 判断题</span>}
              key="JUDGE"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.judgeRef = ref;
                }}
                questionInfo={judgeContent}
                onSetState={(newContent) => {
                  Object.assign(judgeContent, newContent);
                }}
              />
            </TabPane>
            <TabPane
              tab={<span className="icon iconfont">&#xe7fd; 填空题</span>}
              key="GAP_FILLING"
            >
              <NewQuestionTab
                questionTypeKey={activeKey}
                onRef={(ref) => {
                  this.gapRef = ref;
                }}
                questionInfo={gapFillingContent}
                onSetState={(newContent) => {
                  Object.assign(gapFillingContent, newContent);
                  console.log("gapFillingContent:", newContent);
                }}
              />
            </TabPane>
            <TabPane
              tab={
                <span className="icon iconfont">
                  &#xe7fe; 不定项选择题{" "}
                  <Tooltip title="至少有一项正确，至多不限的选择题，多项选择题的一种特殊形式">
                    <span 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>
          <Button onClick={() => {
            this.confirmSaveQuestion("add");
          }}>保存并继续添加</Button>
          <Button
            type="primary"
            onClick={() => {
              this.confirmSaveQuestion("close");
            }}
          >
            保存
          </Button>
        </div>
      </div>
    );
  }
}

export default AddNewQuestion;
