<template>
  <el-select filterable allow-create default-first-option clearable v-model="knowledgeId" placeholder="选择或输入添加知识点"
    @change="createKnowledges" :loading="loading">
    <!-- value-key="id" -->
    <el-option v-for="item in knowledgesOptions" :key="item.id" :label="item.name" :value="item.id">
      <span style="float: left">{{ item.name }}</span>
      <span
        style="float: right; color: #8492a6; font-size: 13px;height:100%;display:flex;align-items:center;justify-content:center"
        class="el-icon-delete" @click.stop="deleteKnowledge(item)"></span>
    </el-option>
  </el-select>
</template>

<script>
import { getAllknowledgePointApi, createKnowledgePointApi, deleteKnowledgePointApi } from '@/api/assessment-evaluation/questions'
export default {
  data: _ => ({
    knowledgeId: null,
    knowledgesOptions: [],
    loading: false
  }),
  mounted () {
    this.findAllKnowledges()
  },
  activated () {
    this.findAllKnowledges()
  },
  props: {
    value: {
      default: null
    }
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler (nv) {
        this.knowledgeId = nv
      }
    },
    knowledgeId: {
      immediate: false,
      deep: true,
      handler (nv) {
        this.$emit('input', nv)
      }

    }
  },
  methods: {
    /*
      请求api获取所有知识点
    */
    findAllKnowledges () {
      // 获取知识点
      this.loading = true
      getAllknowledgePointApi().then(({ data: knowledges }) => {
        this.knowledgesOptions = knowledges
      }).finally(_ => {
        this.loading = false
      })
    },
    /*
      删除某个知识点
    */
    deleteKnowledge (item) {
      this.loading = true

      deleteKnowledgePointApi(item.id).finally(_ => {
        this.loading = false
        this.findAllKnowledges()
        if (this.knowledgeId === item.id) {
          this.knowledgeId = null
        }
      })
    },
    /*
      创建知识点回调
    */
    createKnowledges (e) {
      if (typeof e === 'string' && e !== '') {
        this.loading = true
        createKnowledgePointApi(e).then(res => {
          this.knowledgesOptions.push(res.data)
          this.$nextTick(() => {
            this.knowledgeId = res.data.id
          })
        }).finally(_ => {
          this.loading = false
        })
      }
    }
  }
}
</script>

<style>

</style>
