<route lang="yaml">
meta:
  enabled: false
</route>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createGroupCat, getGroupCatById, updateGroupCat } from '@/api/system/groupCatApi'
const emit = defineEmits(['success'])

const formRef = ref<FormInstance>()
const formRules = ref<FormRules>({
  groupCatTitle: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  groupCatDesc: [
    { required: false, message: '请输入描述', trigger: 'blur' },
  ],
})

const state = reactive({
  title: '',
  dialogVisible: false,
  loading: false,
  formData: {
    groupCatId: 0,
    groupCatTitle: '',
    groupCatDesc: '',
  },
  actionType: 1,
})

onMounted(() => {})

const getData = async (groupCatId: number) => {
  state.loading = true
  const { data } = await getGroupCatById(groupCatId)
  state.loading = false
  state.formData = data
}

function onSubmit() {
  formRef.value && formRef.value.validate(async (valid) => {
    if (valid) {
      if (state.actionType === 1) {
        const { msg } = await createGroupCat(state.formData)
        ElMessage.success(msg)
        state.dialogVisible = false
        emit('success')
      }
      else {
        const { msg } = await updateGroupCat(state.formData)
        ElMessage.success(msg)
        state.dialogVisible = false
        emit('success')
      }
    }
  })
}

function onCancel() {
  state.dialogVisible = false
}

function resetFormData() {
  state.formData = {
    groupCatId: 0,
    groupCatTitle: '',
    groupCatDesc: '',
  }
}

defineExpose({
  showAddModel() {
    resetFormData()
    state.title = '新增'
    state.actionType = 1
    state.dialogVisible = true
  },
  showEditModel(groupCatId: number) {
    resetFormData()
    state.title = '编辑'
    state.actionType = 2
    state.dialogVisible = true
    getData(groupCatId)
  },
})
</script>

<template>
  <el-drawer v-model="state.dialogVisible" :title="state.title" width="600px" :close-on-click-modal="false" append-to-body destroy-on-close>
      <el-form ref="formRef" :model="state.formData" :rules="formRules" label-width="120px" label-suffix="：">
      <el-form-item label="分类名称" prop="groupCatTitle">
        <el-input v-model="state.formData.groupCatTitle" placeholder="请输入标题" />
      </el-form-item>

      <el-form-item label="简要说明" prop="groupCatDesc">
        <el-input v-model="state.formData.groupCatDesc" type="textarea" rows="10" placeholder="请输入简要说明" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button size="large" @click="onCancel">
        取消
      </el-button>
      <el-button type="primary" size="large" @click="onSubmit">
        保存
      </el-button>
    </template>
  </el-drawer>
</template>
