<template>
  <ai-detail class="AppQuestionBank-add" v-loading="isLoading">
    <template slot="title">
      <ai-title :title="params.id ? '编辑' + '试题' : '添加' + '试题'" isShowBack isShowBottomBorder @onBackClick="cancel(false)"></ai-title>
    </template>
    <template slot="content">
      <ai-card title="基本信息">
        <template #content>
          <el-form class="ai-form" :model="form" label-width="120px" ref="form">
            <el-form-item label="题目描述" style="width: 100%;" prop="title" :rules="[{required: true, message: '请输入标题', trigger: 'blur'}]">
              <el-input size="small" type="textarea" :rows="4" v-model="form.title" clearable placeholder="请输入..." :maxlength="500" :show-word-limit="true"></el-input>
            </el-form-item>
            <el-form-item prop="type" label="题目类型" :rules="[{required: true, message: '请选择题目类型', trigger: 'change'}]">
              <el-radio-group v-model="form.type" @change="onTypeChange">
                <el-radio :label="item.dictValue" :key="item.dictValue" v-for="item in dict.getDict('qjQBType')">{{ item.dictName }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="items" v-if="form.type !== '2'" style="width: 100%;" label="题目选项" :rules="[{required: true, message: '请输入题目选项', trigger: 'change'}]">
              <div class="options" v-for="(item, index) in form.items" :key="index">
                <span>选项{{ index + 1 }}</span>
                <el-input placeholder="请输入选项名" size="small" :maxlength="100" show-word-limit v-model="item.content"></el-input>
                <i class="iconfont iconDelete" @click="removeOptions(index)"></i>
              </div>
              <el-button type="text" class="add-select" @click="addOptions">添加选项</el-button>
            </el-form-item>
            <el-form-item style="width: 100%;" v-if="form.items.length && form.type !== '2'" prop="answer" label="题目答案" :rules="[{required: true, message: '请选择题目答案', trigger: 'change'}]">
              <el-select :multiple="form.type === '1'" v-model="form.answer" size="small" placeholder="请选择题目答案">
                <el-option
                  v-for="(item, index) in form.items"
                  :key="index"
                  :label="item.content"
                  :value="item.content">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.type === '2'" style="width: 100%;" prop="answer" label="题目答案" :rules="[{required: true, message: '请选择题目答案', trigger: 'change'}]">
              <el-radio-group v-model="form.answer">
                <el-radio label="1">正确</el-radio>
                <el-radio label="0">错误</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="答案解析" prop="analysis" style="width: 100%;" :rules="[{required: true, message: '请输入内容', trigger: 'change'}]">
              <ai-editor v-model="form.analysis" :instance="instance"/>
            </el-form-item>
          </el-form>
        </template>
      </ai-card>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :loading="isLoading" @click="confirm">提交</el-button>
    </template>
  </ai-detail>
</template>

<script>
  import { mapState } from 'vuex'
  export default {
    name: 'Add',

    props: {
      instance: Function,
      dict: Object,
      params: Object,
      areaId: String
    },
    data () {
      return {
        info: {},
        form: {
          title: '',
          analysis: '',
          type: '0',
          answer: '',
          items: []
        },
        isLoading: false,
        id: '',
        sort: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
      }
    },

    computed: {
      ...mapState(['user'])
    },

    created () {
      this.dict.load('qjQBType').then(() => {
        if (this.params && this.params.id) {
          this.id = this.params.id
          this.getInfo(this.params.id)
        }
      })
    },

    methods: {
      getInfo (id) {
        this.instance.post(`/app/appquestionbank/queryDetailById?id=${id}`).then(res => {
          if (res.code === 0) {
            this.form = {
              ...res.data,
              answer: res.data.type === '1' ?
                res.data.items.filter(v => v.checked === '1').map(v => v.content)
                : res.data.items.filter(v => v.checked === '1')[0].content
            }

            if (res.data.type === '2') {
              this.form.answer = this.form.answer === '正确' ? '1' : '0'
            }
          }
        })
      },

      onTypeChange (e) {
        if (e === '2') {
          this.form.answer = []
        } else {
          this.form.answer = ''
        }
      },

      addOptions () {
        this.form.items.push({
          content: ''
        })
      },

      removeOptions (index) {
        this.form.items.splice(index, 1)
      },

      confirm () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const items = this.form.type !== '2' ? this.form.items.map((v, index) => {
              return {
                ...v,
                sort: this.sort[index],
                checked: this.form.type === '0' ? (this.form.answer === v.content ? '1' : '0') : (this.form.answer.indexOf(v.content) !== -1 ? '1' : 0)
              }
            }) : [{
              content: '正确',
              sort: 'A',
              checked: this.form.answer === '1' ? 1 : 0
            }, {
              content: '错误',
              sort: 'B',
              checked: this.form.answer === '0' ? 1 : 0
            }]

            this.instance.post(`/app/appquestionbank/addOrUpdate`, {
              ...this.form,
              items,
              id: this.params.id || ''
            }).then(res => {
              if (res.code == 0) {
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.cancel(true)
                }, 600)
              }
            })
          }
        })
      },

      cancel (isRefresh) {
        this.$emit('change', {
          type: 'List',
          isRefresh: !!isRefresh
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .AppQuestionBank-add {
    .options {
      display: flex;
      align-items: center;

      .el-input {
        width: 420px;
        margin: 0 14px;
      }

      span {
        color: #666;
      }

      i:hover {
        cursor: pointer;
        opacity: 0.7;
      }
    }
  }
</style>
