<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
// import api from '@/api'

const props = withDefaults(
  defineProps<{
    modelValue: boolean
    dictionaryId: string | number
    id?: string | number
    tree: any[]
  }>(),
  {
    modelValue: false,
    dictionaryId: '',
    id: '',
  },
)

const emit = defineEmits(['update:modelValue', 'success'])
const myVisible = ref(props.modelValue)
const title = computed(() => props.id === '' ? '新增字典项' : '编辑字典项')

const formRef = ref<FormInstance>()
const form = ref({
  dictionaryId: props.dictionaryId,
  id: props.id,
  name: '',
  value: '',
  enable: true,
})
const formRules = ref<FormRules>({
  dictionaryId: [
    { required: true, message: '请选择所属字典' },
  ],
  name: [
    { required: true, message: '请输入字典项名称' },
  ],
  value: [
    { required: true, message: '请输入字典项键值' },
  ],
})

onMounted(() => {
  if (props.id !== '') {
    // api.get('pages_example/dictionary/item/detail', {
    //   params: {
    //     id: props.id,
    //   },
    //   baseURL: '/mock/',
    // }).then((res) => {
    //   // form.value.dictionaryId = res.data.dictionaryId
    //   form.value.id = res.data.id
    //   form.value.name = res.data.name
    //   form.value.value = res.data.value
    //   form.value.enable = res.data.enable
    // })
  }
})

function onSubmit() {
  if (form.value.id === '') {
    formRef.value && formRef.value.validate((valid) => {
      if (valid) { /* empty */ }
    })
  }
  else {
    formRef.value && formRef.value.validate((valid) => {
      if (valid) { /* empty */ }
    })
  }
}

function onCancel() {
  myVisible.value = false
}
</script>

<template>
  <el-dialog v-model="myVisible" :title="title" width="400px" :close-on-click-modal="false" append-to-body destroy-on-close @closed="emit('update:modelValue', false)">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
      <el-form-item label="所属字典" prop="dictionaryId">
        <el-cascader v-model="form.dictionaryId" :options="tree" :props="{ value: 'id', emitPath: false, checkStrictly: true }" :show-all-levels="false" placeholder="请选择所属字典" />
      </el-form-item>
      <el-form-item label="字典项名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入字典项名称" clearable />
      </el-form-item>
      <el-form-item label="字典项键值" prop="value">
        <el-input v-model="form.value" placeholder="请输入字典项键值" clearable />
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-switch v-model="form.enable" inline-prompt active-text="启用" inactive-text="禁用" />
      </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-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-cascader) {
  width: 100%;
}
</style>
