<template>
  <ElDialog v-model="showDialog"
    :close-on-click-modal="false"
    destroy-on-close
    @close="dialogCloseHandler"
    width="25vw">
    <ElForm :model="dictFormData"
      class="sys_dict-form"
    >
      <ElFormItem label="字典标识">
        <ElInput
          v-model="dictFormData.dictKey"
          placeholder="字典标识"/>
      </ElFormItem>
      <ElFormItem label="字典名称">
        <ElInput
          v-model="dictFormData.dictName"
          placeholder="字典名称"/>
      </ElFormItem>
      <ElFormItem label="备注">
        <ElInput
          v-model="dictFormData.memo"
          placeholder="备注"/>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="showDialog = false">{{ status === 'view' ? '关闭' : '取消' }}</ElButton>
      <ElButton v-if="status !== 'view'" :loading="submiting" type="primary" @click="submitHandler">提交</ElButton>
    </template>
  </ElDialog>
</template>
<script lang="ts" setup>
import DictApi from '@/pages/sys/dict/dict-api.ts'
import Strings from '@/common/utils/strings.ts'
import { ElMessage } from 'element-plus'

const emits = defineEmits([ 'editSucc' ])
const showDialog = ref(false)
const submiting = ref(false)
const status = ref<'add' | 'view' | 'modify'>('add')
const dictFormData = ref<DictTypes.SearchDictResult>({})

function dialogCloseHandler() {
  dictFormData.value = {}
}

function submitHandler() {
  if (status.value === 'view') return
  submiting.value = true
  if (dictFormData.value.id != null) {
    DictApi.modify(dictFormData.value)
      .then(() => {
        ElMessage.success('修改成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  } else {
    DictApi.add(dictFormData.value)
      .then(() => {
        ElMessage.success('添加成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  }
}

defineExpose({
  open(data: DictTypes.SearchDictResult = {}) {
    showDialog.value = true
    if (!Strings.isBlank(data.id)) {
      status.value = 'modify'
      DictApi.detail(data.id!)
        .then(res => {
          dictFormData.value = res.data
        })
    } else {
      status.value = 'add'
      dictFormData.value = data
    }
  },
})
</script>
<style lang="stylus" scoped>
.sys_dict-form {
  padding 20px
}
</style>
