<!--
 * @Author: xiejiang
 * @Date: 2024-12-02 18:41:38
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-10 14:44:24
 * @Description: 新增编辑枚举值
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <Drawer
    :drawer-visible="drawerVisible"
    width="480px"
    :title="title"
    :loading="submitLoading"
    confirm-btn-text="保存"
    :cancel-btn="false"
    @confirm="handleConfirm"
    @close="close"
  >
    <t-form ref="formRef" label-align="top" class="login-form" :rules="rules" :data="formData">
      <t-form-item label="值名称" name="valueName">
        <t-input maxlength="20" v-model="formData.valueName" placeholder="请输入内容"> </t-input>
      </t-form-item>
      <t-form-item label="值编码" name="dataCode">
        <t-input v-model="formData.dataCode" maxlength="50" placeholder="请输入内容"> </t-input>
      </t-form-item>
      <t-form-item label="值备注" name="remark">
        <t-textarea :maxlength="200" v-model="formData.remark" placeholder="请输入内容"> </t-textarea>
      </t-form-item>
    </t-form>
  </Drawer>
</template>

<script setup lang="ts" name="dictionary-subset-edit">
import { FormProps, FormInstanceFunctions } from 'tdesign-vue-next'
import { ReqEditDictData, ResDictionary } from '@/api/interface/dectionory'
import { postEditDictData, postSaveDictData } from '@/api/modules/dectionory'

const drawerVisible = ref(false)
const submitLoading = ref(false)

const formRef = useTemplateRef<FormInstanceFunctions>('formRef')
const formData = reactive<ReqEditDictData>({
  dictId: '',
  dictDataId: '',
  dataCode: '',
  remark: '',
  valueName: ''
})

const rules: FormProps['rules'] = {
  valueName: [
    {
      required: true,
      message: '请填写值名称！',
      trigger: 'blur'
    }
  ],
  dataCode: [
    {
      required: true,
      message: '请填写值编码！',
      trigger: 'blur'
    }
  ]
}

const title = ref('新增枚举值')
const open = (val: ResDictionary) => {
  formData.dictId = val.dictId
  if (val?.dictDataId) {
    title.value = '编辑枚举值'
    for (const key in formData) {
      if (Object.prototype.hasOwnProperty.call(val, key)) {
        ;(formData as any)[key] = val[key]
      }
    }
  } else {
    title.value = '新增枚举值'
  }
  drawerVisible.value = true
}
const close = () => {
  formData.dictDataId = ''
  formRef.value?.reset()
  drawerVisible.value = false
}

// 确认
const handleConfirm = () => {
  formRef.value?.validate().then(val => {
    if (val === true) {
      submitLoading.value = true
      const sumit = formData.dictDataId ? postEditDictData : postSaveDictData
      sumit(formData)
        .then(() => {
          emit('success')
          close()
        })
        .finally(() => {
          submitLoading.value = false
        })
    }
  })
}

const emit = defineEmits<{
  success: []
}>()

defineExpose({
  open,
  close
})
</script>
