<script setup>
import { ref } from 'vue'
import { hotAddService, hotUpdateService } from '@/api/hot'
const dialogVisible = ref(false)
const formModel = ref({
  id: '',
  description: ''
})
const formRef = ref()

const rules = {
  id: [{ required: true, message: '请输入费用', trigger: 'blur' }],
  description: [{ required: true, message: '请输入费用', trigger: 'blur' }]
}

// 组件对外暴露一个方法 open
const open = (row) => {
  if (row.id != 0) {
    formModel.value = { ...row }
  } else {
    formModel.value.id = 0
  }
  dialogVisible.value = true
}
// 向外暴露
defineExpose({
  open
})

const emit = defineEmits(['success'])

const onSubmit = async () => {
  await formRef.value.validate()
  ElMessageBox.confirm('确认提交修改？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      console.log(formModel.value)

      formModel.value.id === 0
        ? await hotAddService(formModel.value)
        : await hotUpdateService(formModel.value)
      ElMessage.success('编辑成功')
      onClose()
      emit('success')
    })
    .catch(() => {})
}

const onClose = () => {
  dialogVisible.value = false
  formModel.value = {}
  formRef.value.clearValidate()
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑' : '添加'"
    width="25%"
    :before-close="onClose"
  >
    <div v-if="formModel.id && formModel.id !== 0">
      <img :src="formModel.imgUrl" style="width: 400px; height: 300px" alt="" />
      <hr />
    </div>
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="40px">
      <el-form-item label="描述" prop="description" width="40px">
        <el-input
          v-model="formModel.description"
          :rows="2"
          type="textarea"
          show-word-limit
          placeholder="Please input"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
