<script lang="ts" setup>
import { createCharacter, editCharacter } from '../../api'
import type { FormInstance, FormRules } from 'element-plus'
import { useMapStore } from '@/stores/map'
const store = useMapStore()
const emit = defineEmits<Emits>()
const ruleFormRef = ref<FormInstance>()
// 封面状态
const form = reactive({
  name: '',
  parent_id: '',
  resource_id: ''
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入章名称', trigger: 'blur' },
    { min: 1, max: 25, trigger: 'blur' }
  ]
})
const props = defineProps({
  isShowDialog: {
    type: Boolean,
    required: true
  },
  course_id: {
    type: String,
    required: true
  },
  isEdit: {
    type: Boolean,
    required: true
  },
  chapterName: {
    type: String,
    required: true
  },
  chapterID: {
    type: String,
    required: true
  }
})
interface Emits {
  (e: 'update:isShowDialog', isShowDialog: boolean): void
  (e: 'create'): void
}

// 取消
const handleCancel = () => {
  emit('update:isShowDialog', false)
}
// 确定
const handleConfirm = () => {
  const type = store.mapList
    .filter(item => item.key === 'system_chapter_resource_type')[0]
    ?.values.filter(it => it.label === '章节')[0]?.value
  if (props.isEdit) {
    const params = Object.assign({ id: props.chapterID, course_id: props.course_id }, form)
    editCharacter(params).then(() => {
      emit('update:isShowDialog', false)
      emit('create')
    })
  } else {
    const params = Object.assign({ course_id: props.course_id, resource_type: type }, form)
    createCharacter(params).then(() => {
      emit('update:isShowDialog', false)
      emit('create')
    })
  }
}
onMounted(() => {
  if (props.isEdit) {
    form.name = props.chapterName
  }
})
</script>
<template>
  <el-dialog
    :model-value="isShowDialog"
    draggable
    :before-close="handleCancel"
    width="25%"
    :title="isEdit ? '编辑:章' : '新增:章'"
  >
    <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="100px" label-suffix="：">
      <el-form-item label="章-名称" prop="name">
        <el-input v-model="form.name" maxlength="25" onkeydown="if (event.keyCode===13){return false;}"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
