<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: '',
  resource_id: ''
})
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入节名称', trigger: 'blur' }]
})
const props = defineProps({
  isShowSectionDialog: {
    type: Boolean,
    required: true
  },
  course_id: {
    type: String,
    required: true
  },
  chapterName: {
    type: String,
    required: true
  },
  sectionName: {
    type: String,
    required: true
  },
  chapterID: {
    type: String,
    required: true
  },
  isEdit: {
    type: Boolean,
    required: true
  }
})
interface Emits {
  (e: 'update:isShowSectionDialog', isShowSectionDialog: boolean): void
  (e: 'create'): void
}

// 取消
const handleCancel = () => {
  emit('update:isShowSectionDialog', 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:isShowSectionDialog', false)
      emit('create')
    })
  } else {
    const params = Object.assign({ course_id: props.course_id, resource_type: type, parent_id: props.chapterID }, form)
    createCharacter(params).then(() => {
      emit('update:isShowSectionDialog', false)
      emit('create')
    })
  }
}
onMounted(() => {
  if (props.isEdit) {
    form.name = props.sectionName
  }
})
</script>
<template>
  <el-dialog
    :model-value="isShowSectionDialog"
    draggable
    :before-close="handleCancel"
    width="30%"
    :title="props.isEdit === true ? '编辑:节' : '新增:节'"
  >
    <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="100px" label-suffix="：">
      <el-form-item label="所属章" prop="chapterName">
        <p>{{ chapterName }}</p>
      </el-form-item>
      <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>
