<template>
  <ElDialog v-model="showDialog"
    :close-on-click-modal="false"
    destroy-on-close
    @close="dialogCloseHandler"
    width="25vw">
    <ElForm :model="dictItemFormData"
      class="sys_dict_item-form"
    >
      <ElFormItem label="值">
        <ElInput
          v-model="dictItemFormData.val"

          placeholder="值"/>
      </ElFormItem>
      <ElFormItem label="文本">
        <ElInput
          v-model="dictItemFormData.txt"

          placeholder="文本"/>
      </ElFormItem>
      <ElFormItem label="排序">
        <ElInputNumber
          v-model="dictItemFormData.sort"

          :min="1"
          placeholder="排序"
          style="width: 100%"/>
      </ElFormItem>
      <ElFormItem label="备注">
        <ElInput
          v-model="dictItemFormData.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 DictItemApi from '@/pages/sys/dict/dict-item-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 dictItemFormData = ref<DictItemTypes.SearchDictItemResult>({})
const dictItemFormData = ref<any>({})

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

function submitHandler() {
  if (status.value === 'view') return
  submiting.value = true
  if (dictItemFormData.value.id != null) {
    DictItemApi.modify(dictItemFormData.value)
      .then(() => {
        ElMessage.success('修改成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  } else {
    if (Strings.isBlank(dictItemFormData.value.dictId) || Strings.isBlank(dictItemFormData.value.dictKey)) {
      ElMessage.error('未指定字典')
      return
    }
    DictItemApi.add(dictItemFormData.value)
      .then(() => {
        ElMessage.success('添加成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  }
}

defineExpose({
  // open(data: DictItemTypes.SearchDictItemResult = {}) {
  open(data: any = {}) {
    showDialog.value = true
    if (!Strings.isBlank(data.id)) {
      status.value = 'modify'
      DictItemApi.detail(data.id!)
        .then(res => {
          dictItemFormData.value = res.data
        })
    } else {
      status.value = 'add'
      dictItemFormData.value = data
    }
  },
})
</script>
<style lang="stylus" scoped>
.sys_dict_item-form {
  padding 20px
}
</style>
