/* eslint-disable vue/no-mutating-props */
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import AddExamDialog from './AddExamDialog.vue'
const emit = defineEmits<Emits>()
interface Emits {
  (e: 'change', examList: any): void
}
const props = defineProps({
  data: {
    type: Array,
    required: true
  }
})
const examList: any = ref([])
watch(
  () => props.data,
  value => {
    if (value?.length > 0) {
      examList.value = [...props.data]
    } else {
      examList.value = []
    }
  },
  { immediate: true }
)
const isShowExamDialog = ref(false)
const listOptions = computed(() => {
  return {
    data: examList.value,
    columns: [
      {
        label: '试卷名称',
        prop: 'paper_title',
        minWidth: 200,
        align: 'center'
      },
      {
        label: '组卷模式',
        prop: 'paper_type',
        computed: (row: any) => {
          return row.row.paper_type === 1 ? '选题组卷' : '自动组卷'
        },
        align: 'center'
      },
      {
        label: '试卷用途',
        prop: 'paper_uses',
        computed: (row: any) => {
          if (row.row.paper_type === 1) {
            return '考试'
          } else if (row.row.paper_type === 2) {
            return '课后作业'
          } else if (row.row.paper_type === 3) {
            return '课程测试'
          }
        },
        align: 'center'
      },
      { label: '总分', prop: 'paper_total_score', align: 'center' },
      { label: '及格分数', prop: 'pass_score', align: 'center' },
      { label: '操作', slots: 'table-operate', align: 'center', fixed: 'right' }
    ]
  }
})
// // 删除考试
const removeLectuter = (id: string) => {
  const index = examList.value.findIndex((item: any) => item.id === id)
  examList.value.splice(index, 1)
  emit('change', examList.value)
}
const handleAddExam = (val: any) => {
  let flag = false
  examList.value.forEach((item: any) => {
    val.value.forEach((it: any) => {
      if (item.id === it.id) {
        ElMessage.warning('不能重复添加同一张试卷')
        flag = true
        return false
      }
    })
  })
  if (!flag) {
    examList.value = [...val.value, ...examList.value]
    emit('change', examList.value)
  }
}
</script>

<template>
  <div>
    <el-button type="primary" @click="isShowExamDialog = true">添加课程考试</el-button>
    <AppList v-bind="listOptions" ref="appList">
      <template #table-avatar="{ row }">
        <img :src="row.avatar" style="width: 50px; height: 50px; display: block; margin: 0 auto" />
      </template>
      <template #table-summarize="{ row }">
        <div v-html="row.summarize"></div>
      </template>
      <template #table-operate="{ row }">
        <el-button type="primary" plain @click="removeLectuter(row.id)">删除</el-button>
      </template>
    </AppList>
    <AddExamDialog
      v-if="isShowExamDialog === true"
      v-model:isShowExamDialog="isShowExamDialog"
      @create="handleAddExam"
      :examList="examList"
    />
  </div>
</template>
