<template>
  <div class="app-container">
    <div class="common-card exam-question-create-body">
      <a-spin :spinning="loading">
        <a-form
          :form="aquestionAddForm"
          @submit="handleSubmitForm"
          style="width: 515px;"
          :loading="loading"
        >
          <a-form-item
            label="试题内容"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-textarea
              placeholder="试题内容"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              :maxLength="500"
              v-decorator="[
                'content',
                {
                  rules: [{ required: true, message: '请输入试题内容！' }],
                  initialValue: examQuestionDetail.content,
                },
              ]"
            />
          </a-form-item>
          <div class="question-option">
            <span class="question-option-title">正确答案：</span>
            <span class="question-option-add" @click="questionOptionAddFun"
              >新增填空</span
            >
          </div>
          <div
            class="question-option-list-row"
            v-for="(item, index) in optionsList"
            :key="index"
          >
            <span
              v-if="optionsList.length > 1"
              class="question-option-list-row-delete"
              @click="questionOptionDeleteFun(index)"
              >删除</span
            >
            <a-form-item
              label=" "
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-input
                placeholder="填空需与试题一一对应"
                :maxLength="100"
                v-decorator="[
                  `answers-${index}`,
                  {
                    rules: [{ required: true, message: '请输入填空答案！' }],
                    initialValue: item.value,
                  },
                ]"
              />
            </a-form-item>
          </div>
          <div class="create-select-div">
            <span>试题类型：</span>
            <div class="create-select-row">
              <div class="create-select-item">
                <span>父类:</span>
                <a-select
                  v-model="typeConditionParentValue"
                  @change="selectTypeConditionParent"
                >
                  <a-select-option
                    v-for="(item, index) in typeConditionParentList"
                    :key="index"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </div>
              <div class="create-select-item">
                <span>子类:</span>
                <a-select
                  v-model="typeConditionChildrenValue"
                  :disabled="!typeConditionParentValue"
                >
                  <a-select-option
                    v-for="(item, index) in typeConditionChildrenList"
                    :key="index"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </div>
            </div>
          </div>
          <a-form-item
            label="工种类别"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-select
              v-decorator="[
                'engineeringWorkChooseValue',
                {
                  rules: [
                    {
                      required: false,
                    },
                  ],
                  initialValue: engineeringWorkChooseValue,
                },
              ]"
            >
              <a-select-option
                v-for="(item, index) in engineeringWorkList"
                :key="index"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button
              class="qusetionSubmitBtn"
              type="primary"
              html-type="submit"
              >提交</a-button
            >
          </a-form-item>
        </a-form>
      </a-spin>
    </div>
    <div class="company-info">
      <span>
        copyright © 浮游科技有限公司出品
      </span>
    </div>
  </div>
</template>

<script>
import {
  // formatQuestionLetter,
  formateUrlParams,
  formatePathParams,
} from '@/filters';
import { mapGetters } from 'vuex';
export default {
  name: 'examQusetionCreateGapFilling',
  props: {},
  components: {},
  data() {
    return {
      loading: false, // 是否显示加载动画
      labelCol: { span: 6 }, // 表单行中label的占位
      wrapperCol: { span: 18 }, // 表单行中内容的占位
      aquestionAddForm: this.$form.createForm(this, {
        name: 'examQusetionAddDuoXuan',
      }),
      questionType: 'TianKong', // 试题类型：填空题
      optionsList: [{ value: '' }], // 选项列表
      typeConditionParentList: [], // 试题类型-父类列表
      typeConditionParentValue: '', // 父类所选值
      typeConditionChildrenList: [], // 试题类型-子类列表
      typeConditionChildrenValue: '', // 子类所选值
      engineeringWorkList: [], // 工种数据列表
      engineeringWorkChooseValue: '', // 所选工种
      finalAnswerIndexs: undefined, // 正确答案下标
      examQuestionDetail: {
        id: '', // key
        content: '', // 内容
        finalAnswer: [], // 正确答案
        engineerTypes: [], // 信息集合：工种
        type: '', // 试题类型ID
        answers: [], // 选项
        rootQuestionCategory: '', // 试题类型-父类
        questionCategory: '', // 试题类型-子类
      }, // 题目的信息
    };
  },
  created() {
    this.initDataFun(); // 初始化数据
  },
  mounted() {},
  beforeDestroy() {},
  watch: {},
  computed: {
    ...mapGetters([
      'GET_ENGINEERING_WORK_LIST',
      'GET_EXAM_QUESTION_TYPE_CONDITION_PARENT',
    ]),
  },
  methods: {
    // 初始化数据
    initDataFun() {
      // 试题类型
      this.typeConditionParentList = [
        ...this.GET_EXAM_QUESTION_TYPE_CONDITION_PARENT,
      ];
      // 工种类别
      this.engineeringWorkList = [
        { name: '不限', id: '' },
        ...this.GET_ENGINEERING_WORK_LIST,
      ];
      if (this.$route.query.id) {
        this.getExamQuestionDetailFun(this.$route.query.id); // 查询：试题的详情
      } else {
        this.typeConditionParentValue = this.typeConditionParentList[0].id; // 所选试题类型-父类
        this.getTableChildrenListFun(true); // 查询：试题类型列表-子类
      }
    },
    // 查询：试题的详情
    getExamQuestionDetailFun(id) {
      if (!id) {
        return;
      }
      this.loading = true;
      let params = {
        questionId: id,
      };
      this.$_http
        .get(
          formatePathParams(
            this.$_API.INTERFACE_GET_EXAMS_QUESTION_DETAIL,
            params
          )
        )
        .then((res) => {
          this.examQuestionDetail = { ...res.data };
          // 选项
          this.optionsList = this.examQuestionDetail.finalAnswer.map((item) => {
            return { value: item };
          });
          // 正确答案
          // this.finalAnswerIndexs = formatQuestionLetter(
          //   this.examQuestionDetail.finalAnswer[0]
          // )[0];
          // 试题类型-父类
          this.typeConditionParentValue =
            this.examQuestionDetail.rootQuestionCategory.id || '';
          this.getTableChildrenListFun(); // 查询：试题类型列表-子类
          // 试题类型-子类
          this.typeConditionChildrenValue =
            this.examQuestionDetail.questionCategory.id || '';
          // 工种
          this.engineeringWorkChooseValue = this.examQuestionDetail.engineerTypes[0];
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 查询：试题类型列表-子类
    getTableChildrenListFun(isNeedReset) {
      this.loading = true;
      let params = {
        categoryId: this.typeConditionParentValue,
      };
      this.$_http
        .get(
          formatePathParams(
            this.$_API.INTERFACE_GET_EXAMS_QUESTION_TYPE_CONDITION_CHILDRENS,
            params
          )
        )
        .then((res) => {
          this.typeConditionChildrenList = res.data;
          if (isNeedReset) {
            this.typeConditionChildrenValue = this.typeConditionChildrenList[0].id;
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 操作：新增选项
    questionOptionAddFun() {
      this.optionsList.push({ value: '' });
    },
    // 操作：删除选项
    questionOptionDeleteFun(index) {
      this.optionsList.splice(index, 1);
    },
    // 操作：选择了父类
    selectTypeConditionParent() {
      if (this.typeConditionParentValue) {
        this.getTableChildrenListFun(true); // 查询：试题类型列表-子类
      } else {
        this.typeConditionChildrenList = [];
        this.typeConditionChildrenValue = '';
      }
    },
    // 操作：表单提交
    handleSubmitForm(e) {
      e.preventDefault();
      this.aquestionAddForm.validateFields((err, values) => {
        if (!err) {
          // 需要拼接到请求地址后面的参数
          let urlParams = {
            categoryid: this.typeConditionChildrenValue, // 试题类型ID
            engineertypeid: values.engineeringWorkChooseValue, // 工种ID
          };
          // 接口Body参数
          let params = {
            content: values.content, // 内容
            finalAnswer: this.formatQuestionAnswersArr(values), // 正确答案
            engineerTypes: [values.engineeringWorkChooseValue], // 工种信息集合
            type: this.questionType, // 试题类型ID
            answers: [], // 选项
          };
          if (this.examQuestionDetail.id) {
            params.id = this.examQuestionDetail.id;
            let pathParams = {
              questionId: this.examQuestionDetail.id,
            };
            this.httpQuestEditFun(urlParams, params, pathParams); // 编辑
          } else {
            this.httpQuestAddFun(urlParams, params); // 新建
          }
        }
      });
    },
    // 把答案放入一个数组中
    formatQuestionAnswersArr(values) {
      let arr = [];
      for (let key in values) {
        if (key.includes('answers-')) {
          arr.push(values[key]);
        }
      }
      return arr;
    },
    // 新建
    httpQuestAddFun(urlParams, params) {
      this.loading = true;
      this.$_http
        .post(
          formateUrlParams(
            this.$_API.INTERFACE_POST_EXAMS_QUESTION_ADD,
            urlParams
          ),
          params
        )
        .then(() => {
          this.loading = false;
          this.$message.success('添加填空题成功');
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 编辑
    httpQuestEditFun(urlParams, params, pathParams) {
      this.loading = true;
      this.$_http
        .put(
          formatePathParams(
            formateUrlParams(
              this.$_API.INTERFACE_POST_EXAMS_QUESTION_EDIT,
              urlParams
            ),
            pathParams
          ),
          params
        )
        .then(() => {
          this.loading = false;
          this.$message.success('编辑填空题成功');
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="less"></style>

<style lang="less" scoped>
@import '~@/styles/common/variable.less';
</style>
