<template>
  <div class="v-page">
    <div class="v-ctx" v-loading="page_is_loading">
      <QuestionTypeTabBar :options="questionTypeOptions" v-model="activeName">
      </QuestionTypeTabBar>
      <div class="gy-form inline" style="--fix:80px;margin-bottom: 20px;" v-if="activeName && activeName.id!==-1">
        <div class="gy-form-item mb">
          <div class="gy-label middle">试题分类：</div>
          <QuestionClassifySelector v-model="form.classifyId" :mountedLoad="true"></QuestionClassifySelector>
        </div>
        <div class="gy-form-item mb" >
          <div class="gy-label middle">知识点：</div>
          <KnowledgeSelector v-model="form.knowledgeId" :mountedLoad="true"></KnowledgeSelector>
        </div>
        <div class="gy-form-item"  >
          <div class="gy-label middle">难易程度：</div>
          <QuestionDifficultyLevelSelector v-model="form.difficultyLevel" :mountedLoad="true"></QuestionDifficultyLevelSelector>
        </div>
      </div>
      <div class="gy-question-editer" v-if="activeName && activeName.id!==-1">
        <div class="gy-form" style="--fix:80px;">
          <div class="gy-form-item">
            <div class="gy-label ">题目：</div>
            <el-input type="textarea" v-model="form.title"></el-input>
          </div>
          <div class="gy-form-item " style="margin-top:16px;">
            <div class="gy-label " v-if="!['textarea'].includes(currentOptionElement)">选项：</div>
          </div>
          <!-- 多选项，多答案的题型选项或答案的编辑 -->
          <div class="gy-unform-content" style="margin-top:16px;">
            <div class="options-list">
              <div :class="{'radio-option':true,'horizontal-option':['radio*2'].includes(currentOptionElement)}"
                v-if="['radio', 'checkbox','radio*2','input'].includes(currentOptionElement)">
                <div v-for="(item, ind) in form.options" :key="ind" class="option-item">
                  <div style="display:flex;align-items:center;"
                    v-if="['radio', 'checkbox','radio*2'].includes(currentOptionElement)">
                    <!-- 单选题、多选题、填空题的左侧文字ABC -->
                    <div style="width:30px;font-size:14px;padding:9px 0"
                      v-if="['radio', 'checkbox','input'].includes(currentOptionElement)">{{ optionsWordList[ind] }}:</div>
                    <!-- 单选题、多选题、判断题的checkbox -->
                    <el-checkbox-group v-model="form.answer">
                      <el-checkbox :label="optionsWordList[ind]" @change="selectedAnswer(optionsWordList[ind])">{{['radio',
                        'checkbox'].includes(currentOptionElement)?'答案':form.options[ind]}}
                      </el-checkbox>
                    </el-checkbox-group>
                    <!-- 右侧删除按钮 -->
                    <el-button type="text" icon="i-j-ksap-shanchu" style="color:#ec0000;font-size:14px;margin-left:20px"
                      @click="deleteOption(ind)" v-if="['radio', 'checkbox','input'].includes(currentOptionElement)">删除
                    </el-button>
                  </div>
                  <el-input v-model="form.options[ind]" placeholder="请输入选项内容"
                    v-if="['radio', 'checkbox'].includes(currentOptionElement)"></el-input>
                  <div style="display:flex;align-items:center;" v-if="['input'].includes(currentOptionElement)">
                    <!-- 单选题、多选题、填空题的左侧文字ABC -->
                    <div style="min-width:60px;font-size:14px;padding:15px 10px 15px 0">填空{{ ind+1 }}:</div>
                    <!-- 右侧删除按钮 -->
                    <el-input v-model="form.options[ind]" placeholder="请输入填空内容" style="flex-basis:0;flex-grow:1;"></el-input>
                    <el-button type="text" icon="i-j-ksap-shanchu" style="color:#ec0000;font-size:14px;padding:9px 10px"
                      @click="deleteOption(ind)">删除</el-button>
                  </div>
                  <!-- 选项输入框 -->
                </div>
              </div>
              <el-button type="pramiry" v-if="['radio', 'checkbox','input'].includes(currentOptionElement)" plain
                icon="el-icon-plus" class="addbtn-restyle mt" @click="addOption">增加选项
              </el-button>
            </div>
          </div>
          <!-- 简答题解答和关键字的编辑 -->
          <div class="gy-form-item" v-if="['textarea'].includes(currentOptionElement)">
            <div class="gy-label ">解答：</div>
            <el-input type="textarea" v-model="form.answer[0]"></el-input>
          </div>
          <!-- <div class="gy-form-item" style="padding:16px 0;" v-if="['textarea'].includes(currentOptionElement)">
            <div class="gy-label ">关键词：</div>
            <TagEditer v-model="form.options"></TagEditer>
          </div> -->
          <div class="gy-unform-content">
            <div class="gy-form-item">
              <div class="gy-label" style="padding:10px 0">答案解析：</div>
            </div>
            <div class="gy-form-item">
              <el-input type="textarea" v-model="form.analysis" placeholder="可依据需求填写答案解析内容"></el-input>
            </div>
          </div>
        </div>
      </div>
      <!-- 试题导入开始 -->
      <ImportQuestions v-if="activeName && activeName.id===-1"></ImportQuestions>
      <!-- 试题导入结束 -->
      <div style="width:100%;margin-top:30px;"  v-if="activeName && activeName.id!==-1">
        <ActionBar center @onConfirm="confirmQuestion" @onCancel="cancelQuestion"></ActionBar>
      </div>
    </div>
  </div>
</template>

<script>
import '@/views/assessment-evaluation/utils/gyStyle.scss'
import { getQuestionTypeOptionsApi, createQuestionApi, getQuestionByIdApi, patchQuestionByIdApi } from '@/api/assessment-evaluation/questions'
import { ActionBar } from '@/components/layout'
// import TagEditer from './components/TagEditer.vue'
import QuestionClassifySelector from './components/QuestionClassifySelector.vue'
import KnowledgeSelector from './components/KnowledgeSelector.vue'
import QuestionDifficultyLevelSelector from './components/QuestionDifficultyLevelSelector.vue'
import QuestionTypeTabBar from './components/QuestionTypeTabBar.vue'
import { formatJsonPropertyToMap, formatMapPropertyToJson } from '@/views/assessment-evaluation/utils/questionInfoMapJsonTrans'
import ImportQuestions from './components/ImportQuestions.vue'
const globalWords = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
export default {
  components: { ActionBar, /* TagEditer, */ QuestionClassifySelector, KnowledgeSelector, QuestionDifficultyLevelSelector, QuestionTypeTabBar, ImportQuestions },
  data: () => ({
    page_is_loading: false,
    activeName: null,
    questionTypeOptions: [],
    optionsWordList: globalWords,
    modifyBackupForm: {},
    form: {
      type: null,
      difficultyLevel: null,
      title: '',
      options: [],
      answer: [],
      classifyId: null,
      knowledgeId: null,
      analysis: ''
    }
    // rules: {
    //   classifyId: { required: true, message: '请选择分类', trigger: 'blur' }
    // }
  }),
  props: {
    questionId: {
      require: false
    }
  },
  computed: {
    isModify () {
      return this.$route.params.questionId != null
    },
    currentOptionElement () {
      return this.activeName ? this.activeName.element : null
    }
  },
  watch: {
    activeName: {
      deep: true,
      immediate: true,
      handler (nv) {
        this.typeOnChangeHandler(nv)
      }
    }
  },
  created () {
    this.formItems = [
      { prop: 'classifyId', label: '科目' }
      // { prop: 'knowledgeId', label: '知识点' },
      // { prop: 'difficultyLevel', label: '难度' }
    ]
  },
  activated () {
    this.findQuestionTypeOptions().then(() => {
      this.getRouteParamsAndRequest()
    })
  },
  deactivated () {
    this.initFormData()
  },
  methods: {
    /*
      获取路由传参
    */
    getRouteParamsAndRequest () {
      const { questionId } = this.$route.params
      const { activeTag } = this.$route.query

      if (questionId) {
        this.getQuestionDetails(questionId)
      }
      if (!isNaN(parseInt(activeTag))) {
        this.changeQuestionTypeTag(activeTag)
      }
    },
    /*
      表单信息
    */
    changeFormInitData () {
      if (!this.isModify) {
        this.activeName != null && (this.form = {
          type: this.activeName.id,
          difficultyLevel: null,
          title: '',
          options: [],
          answer: [],
          classifyId: null,
          knowledgeId: null,
          analysis: ''
        })
      } else {
        this.form = JSON.parse(JSON.stringify(this.modifyBackupForm))
        this.form.type = this.activeName.id
      }
      if (this.modifyBackupForm && this.activeName.id === this.modifyBackupForm.type) {
        this.form.answer = [...this.modifyBackupForm.answer]
        this.form.options = [...this.modifyBackupForm.options]
      }
      // this.form = JSON.parse(JSON.stringify(this.modifyBackupForm))
      if (this.form.answer && ['radio', 'checkbox'].includes(this.currentOptionElement)) {
        if (this.form.answer.every(item => typeof item === 'number')) {
          this.form.answer = []
        }
        this.optionsWordList = globalWords
      }
      if (['radio*2'].includes(this.currentOptionElement)) {
        this.form.answer = (this.modifyBackupForm?.element === 'radio*2' && this.modifyBackupForm?.answer) ? this.modifyBackupForm.answer : [1]
        this.form.options = ['正确', '错误']
        this.optionsWordList = [1, 0]
      }
      if (['radio', 'x'].includes(this.currentOptionElement)) {
        if (this.form.answer && this.form.answer.length > 1) {
          this.form.answer.splice(1)
        }
      }
    },
    /*
      初始化表单数据
    */
    initFormData () {
      if (this.isModify) {
        this.modifyBackupForm = null
        // this.cancelQuestion();
      }
      if (this.activeName != null) {
        (this.form = {
          type: this.activeName.id,
          difficultyLevel: null,
          title: '',
          options: [],
          answer: [],
          classifyId: null,
          knowledgeId: null,
          analysis: ''
        })
        if (['radio*2'].includes(this.currentOptionElement)) {
          this.form.answer = [1]
          this.form.options = ['正确', '错误']
          this.optionsWordList = [1, 0]
        }
      }
    },
    /*
      取消添加
    */
    cancelQuestion () {
      this.initFormData()
      this.$router.replace({ path: '/assessment-evaluation/question-bank-manage' })
    },
    /*
      删除选项
    */
    deleteOption (ind) {
      this.form.options.splice(ind, 1)
    },
    /*
      新增选项
    */
    addOption () {
      const optionsList = this.form.options
      if (['radio', 'checkbox'].includes(this.currentOptionElement)) {
        if (optionsList.length >= this.optionsWordList.length) return this.$message.error('最多26个选项')
      }
      optionsList.push('')
    },
    handleClick (e) {

    },
    /*
    试题类型改变的回调【watch】
    */
    typeOnChangeHandler (nv) {
      if (nv) {
        this.form.type = nv.id
        if (!this.isModify) {
          this.initFormData()
        }
        this.changeFormInitData()
      }
    },
    /*
    根据ID获取试题详情
    */
    getQuestionDetails (id) {
      this.page_is_loading = true
      getQuestionByIdApi(id).then(res => {
        const { data } = res
        const newData = formatJsonPropertyToMap(data)
        this.changeQuestionTypeTag(newData.type).then(_ => {
          this.modifyBackupForm = newData
          this.form = JSON.parse(JSON.stringify(newData))
        })
      }).finally(_ => {
        this.page_is_loading = false
      })
    },
    /*
      试题类型的tab bar 被切换
    */
    changeQuestionTypeTag (xid) {
      const selfComponent = this

      return new Promise((resolve, reject) => {
        let count = 20
        function changex (idx, self) {
          if (self.questionTypeOptions.length > 0) {
            const item = self.questionTypeOptions.find(item => parseInt(item.id) === parseInt(idx))
            self.$nextTick(_ => {
              self.activeName = item
            })
            resolve()
          } else {
            count--
            if (count > 0) {
              setTimeout(() => {
                changex(idx, self)
              }, 100)
            } else {
              reject(new Error('超时请求试题类型'))
            }
          }
        }
        changex(xid, selfComponent)
      })
    },
    /*
      答案被选择的回调
    */
    selectedAnswer (e) {
      // 单选题keyi
      if (this.activeName.element === 'radio' || this.activeName.element === 'radio*2') {
        this.form.answer = [e]
      }
    },
    /*
      提交试题后的回调
    */
    confirmQuestion () {
      const form = this.form
      if (form.classifyId == null) return this.$message.error('请选择科目')
      // if (form.knowledgeId == null) return this.$message.info('请选择知识点')
      if (form.difficultyLevel == null) return this.$message.error('请选择难度')
      if (form.title === '') return this.$message.error('请填写题目')
      // if (form.options.length === 0) return this.$message.error('请添加选项或关键词') //修改为重复率
      if (!['textarea'].includes(this.currentOptionElement) && form.options.length === 0) return this.$message.error('请添加选项')
      if (['radio', 'checkbox', 'radio*2'].includes(this.currentOptionElement) && form.answer.length === 0) return this.$message.error('请确定正确答案或选项')
      if ((this.activeName.element === 'radio' || this.activeName.element === 'radio*2') && form.answer.length > 1) return this.$message.error('题型只能选择一个正确答案')
      if (form.options.filter(item => item === '' || item === null).length > 0) return this.$message.error('选项不能为空')
      const newForm = formatMapPropertyToJson(this.form)
      if (newForm.knowledgeId === 'null' || newForm.knowledgeId === '') newForm.knowledgeId = null

      this.page_is_loading = true
      /*
       是否为修改试题
       */
      if (this.isModify) {
        patchQuestionByIdApi(newForm).then(res => {
          if (res.code === 0) {
            this.$message.success('修改成功')
            this.cancelQuestion()
            // this.initFormData()
          }
        }).catch(err => {
          console.info(err)
        }).finally(_ => {
          this.page_is_loading = false
        })
      } else {
        createQuestionApi(newForm).then(res => {
          if (res.code === 0) {
            this.$message.success('添加成功')
            this.initFormData()
          }
        }).catch(err => {
          console.info(err)
        }).finally(_ => {
          this.page_is_loading = false
        })
      }
    },
    /*
      获取所有试题类型选项 用于渲染tabbar
    */
    findQuestionTypeOptions () {
      // 获取试题分类
      return new Promise((resolve, reject) => {
        this.page_is_loading = true
        getQuestionTypeOptionsApi().then(({ data }) => {
          this.questionTypeOptions = data
          if (!this.isModify) {
            this.questionTypeOptions.push({ id: -1, name: '导入' })
          }
          this.activeName = this.activeName != null ? this.activeName : this.questionTypeOptions[0]
        }).catch(err => {
          console.info(err)
        }).finally(_ => {
          this.page_is_loading = false
          resolve()
        })
      })
    }
  }

}
</script>
<style lang="scss">
 .el-form.el-form--label-left {
  .el-form-item__label {
    width: 60px !important;
    padding: 0 0 0 12px;
  }
}
</style>
<style lang="scss" scoped>
// .option-item+.option-item{
//   margin-top: 16px;
// }
.radio-option.horizontal-option{
  display:flex;
  .option-item{
    margin-right:20px;
  }
}

</style>
