<template>
  <div style="padding: 20px">
    <h2 style="text-align: center">
      游戏题目{{ questionId ? "编辑" : "添加" }}
    </h2>
    <el-form ref="form" :rules="rules" :model="form" label-width="90px">
      <el-form-item label="题目：" prop="title">
        <el-input v-model="form.title" placeholder="请输入实例名（必填）">
          <el-select slot="prepend" v-model="form.optType" style="width:100px" placeholder="请选择">
            <el-option label="单选题" value="1" />
            <el-option label="多选题" value="2" />
            <el-option label="判断题" value="3" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item v-if="questionId!==undefined && resultMode === 'examination'" label="正确选项：">
        <!-- filterable可搜索 multiple可多选 default-first-option回车可选-->
        <el-select
          v-model="form.rightAnswer"
          style="width:100%"
          multiple
          filterable
          default-first-option
          placeholder="请选择"
        >
          <el-option
            v-for="item in rightList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">确定</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
    <el-card v-if="questionId!==undefined" class="box-card">
      <div slot="header" class="clearfix">
        <h3 style="float:left">答案列表</h3>
        <el-button
          type="primary"
          style="float: right"
          icon="el-icon-plus"
          @click="onAddAnswer"
        >添加特征</el-button>
      </div>
      <ul style="list-style-type: none;margin:10px 0 10px -40px">
        <li v-for="answer in answerList" :key="answer.answerId" class="answerli">
          <div style="flex:1;width: 100%;overflow: hidden;display: flex;" @click="handleEdit(answer)">
            <span style="width:45px">{{ answer.option }}</span>
            <span style="flex:1">{{ answer.content }}</span>
          </div>
          <el-popconfirm
            style="width:30px"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除这个答案吗？"
            @onConfirm="handleDelete(answer)"
          >
            <el-button slot="reference" type="text" class="deleteQuestion" style="color:red">删除</el-button>
          </el-popconfirm>
        </li>
      </ul>
    </el-card>
    <QuestionDrawer
      :dialog="dialog"
      :question-id="questionId"
      :answer-id="answerId"
      :game-id="gameId"
      :result-mode="resultMode"
      @handleCloseDrawer="handleCloseDrawer"
      @handleEditDrawer="handleEditDrawer"
    />
  </div>
</template>
<script>

import { saveQuestion, UpdateQuestion, getQuestionDetail } from '@/api/question'
import { getAnswerList, deleteAnswer } from '@/api/answer'
import QuestionDrawer from '@/components/Question/drawer.vue'

export default {
  components: {
    QuestionDrawer
  },
  props: {
    gameId: String,
    questionId: String,
    resultMode: String
  },
  data() {
    return {
      rules: {
        title: [{ required: true, message: '请输入游戏名称', trigger: 'blur' }]
      },
      form: {
        title: undefined,
        optType: undefined,
        rightAnswer: undefined,
        gameId: undefined,
        questionId: undefined
      },
      // 答案列表（包括选项 内容 特征词列表）
      answerList: [],
      answerId: undefined,
      // 正确答案数据源
      rightList: [],
      dialog: false
    }
  },
  watch: {
    // 用于点击左边改变右边的页面
    questionId: function() {
      if (this.questionId) {
        this.rightList = []
        getQuestionDetail(this.questionId).then((res) => {
          this.form = res.data
          this.form.rightAnswer = res.data.rightAnswer?.split(',')
        })
        this.handleAnswerList()
      } else {
        this.form = {
          title: undefined,
          optType: undefined,
          gameId: undefined,
          rightAnswer: undefined,
          questionId: undefined
        }
        this.answerList = []
        this.rightList = []
      }
    }
  },
  methods: {
    // 添加答案
    onAddAnswer() {
      this.dialog = true
      this.answerId = undefined
    },
    // 编辑答案
    handleEdit(val) {
      this.dialog = true
      this.answerId = val.answerId
    },
    // 删除答案
    handleDelete(val) {
      deleteAnswer(val.answerId).then((res) => {
        this.$message('删除答案成功')
        this.handleAnswerList()
      })
    },
    // 关闭答案抽屉
    handleCloseDrawer() {
      this.dialog = false
      this.answerId = undefined
    },
    // 编辑答案抽屉成功重新查询列表
    handleEditDrawer(val) {
      this.handleCloseDrawer()
      this.handleAnswerList()
    },
    // 查询当前问题答案列表
    handleAnswerList() {
      getAnswerList({ questionId: this.questionId }).then((res) => {
        this.answerList = res.data.records
        // 给正确答按下拉菜单数据源赋值
        const list = []
        this.answerList.map(item => {
          list.push(item.option)
        })
        this.rightList = list
      })
    },
    // 转换特征数组数据格式
    handleToString(list) {
      const nameList = []
      list?.map(item => {
        nameList.push(item.name)
      })
      return nameList.toString()
    },
    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.form.optType) {
            const data = { ...this.form }
            data.gameId = this.gameId
            if (this.questionId) {
              if (data.rightAnswer) {
                data.rightAnswer = data.rightAnswer.toString()
              }
              UpdateQuestion(data, this.questionId).then((res) => {
                this.$message('修改问题成功')
                // 告诉父页面实例表需要刷新并且关闭当前组件
                this.$emit('handleRefreshQuestion', true)
              })
            } else {
              saveQuestion(data).then((res) => {
                this.$message('添加问题成功')
                // 告诉父页面实例表需要刷新并且关闭当前组件
                this.$emit('handleRefreshQuestion', true)
                this.$emit('handleEditQuestion', res.data.questionId)
              })
            }
          } else {
            this.$message('请选择题型')
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.answerli {
  width: 100%;
  overflow: hidden;
  display: flex;
  line-height:40px;
  background-color: white;
  border: 1px solid #f0f2f5;
}
.answerli:hover {
  background-color: rgb(230, 247, 255);
}
.answerli:nth-of-type(even) {
  background: #f0f2f5;
}
</style>
