<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :width="600" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="120px" v-loading="loading">
      <el-form-item label="类别名称" prop="categoryName">
        <el-input 
          v-model="form.categoryName" 
          placeholder="请输入类别名称" 
          clearable
          maxlength="30"
          show-word-limit
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="类别编码" prop="categoryCode">
        <el-input 
          v-model="form.categoryCode" 
          placeholder="请输入类别编码" 
          clearable
          maxlength="30"
          show-word-limit
          :disabled="!!form.id"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input 
          v-model="form.remarks" 
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          maxlength="250"
          show-word-limit
          style="width: 100%" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="OnlineBooksCategoryFormDialog">
import { ref, reactive, nextTick } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/onlinebookscategory'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const operType = ref('add') // add 或 edit

// 提交表单数据
const form = reactive({
  id: '',
  categoryName: '',
  categoryCode: '',
  remarks: ''
})

// 定义校验规则
const dataRules = {
  categoryName: [
    { required: true, message: '请输入类别名称', trigger: 'blur' },
    { max: 30, message: '类别名称不能超过30个字符', trigger: 'blur' }
  ],
  categoryCode: [
    { required: true, message: '请输入类别编码', trigger: 'blur' },
    { max: 30, message: '类别编码不能超过30个字符', trigger: 'blur' }
  ],
  remarks: [
    { max: 250, message: '备注不能超过250个字符', trigger: 'blur' }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.categoryName = ''
    form.categoryCode = ''
    form.remarks = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      loading.value = true
      getDetail(row.id)
        .then((res: any) => {
          if (res.data) {
            form.id = res.data.id || row.id
            form.categoryName = res.data.categoryName || ''
            form.categoryCode = res.data.categoryCode || ''
            form.remarks = res.data.remarks || ''
          }
        })
        .catch((err: any) => {
          useMessage().error(err.msg || '获取详情失败')
          visible.value = false
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      const submitData: any = {
        categoryName: form.categoryName,
        categoryCode: form.categoryCode,
        remarks: form.remarks
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        submitData.id = form.id
        await editObj(submitData)
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
    } finally {
      loading.value = false
    }
  })
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

