<template>
  <el-dialog v-model='dialogVisible' :title='dialogTitle' v-bind='dialogSmall' @close="close">
    <div>
      <el-form :model='formContent' ref='dialogFormRef' :rules='rules'>
        <el-form-item label='类型名称' :label-width='100' prop='name'>
          <el-input v-model='formContent.name' placeholder='请输入' autocomplete='off' />
        </el-form-item>
        <el-form-item label='类型编码' :label-width='100' prop='code'>
          <el-input v-model='formContent.code' placeholder='请输入' autocomplete='off' />
        </el-form-item>
        <el-form-item label="开启等级" :label-width="100">
          <el-radio-group v-model="formContent.openLevel" >
            <el-radio-button label="开启" :value="1"></el-radio-button>
            <el-radio-button label="关闭" :value="0"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开启描述" :label-width="100">
          <el-radio-group v-model="formContent.openDescribe" >
            <el-radio-button label="开启" :value="1"></el-radio-button>
            <el-radio-button label="关闭" :value="0"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='排序' :label-width='100'>
          <el-input-number v-model='formContent.sort' :min='1' :max='999'/>
        </el-form-item>
        <el-form-item label='备注' :label-width='100'>
          <el-input v-model='formContent.remark' placeholder='请输入备注' autocomplete='off' :rows='2'
                    type='textarea' />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class='dialog-footer'>
        <el-button @click='close()'>取消</el-button>
        <el-button type='primary' @click='save()'>
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import { dialogSmall } from '@/utils/elementBind'
import { Dict } from '@/api/system/dictionary/interface'
import { FormItemRule } from 'element-plus'
import { addDictType, updateDictType } from '@/api/system/dictionary/dictType'

// 定义弹出组件元信息
const dialogFormRef = ref()


function useMetaInfo() {
  const dialogVisible = ref(false)
  const titleType = ref('add')
  const formContent = ref<Dict.ResDictType>({
    id: '',
    name: '',
    code: '',
    sort: 100,
    openLevel: 0,
    openDescribe: 0,
    remark: '',
    state: 1,
  })
  return { dialogVisible, titleType, formContent }
}

const { dialogVisible, titleType, formContent } = useMetaInfo()

// 清空formContent
const resetFormContent = () => {
  formContent.value = {
    id: '',
    name: '',
    code: '',
    sort: 100,
    openLevel: 0,
    openDescribe: 0,
    remark: '',
    state: 1,
  }
}

let dialogTitle = computed(() => {
  return titleType.value === 'add' ? '新增字典类型' : '编辑字典类型'
})

// 定义表单校验规则
const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
  name: [{ required: true, message: '类型名称必填！', trigger: 'blur' }],
  code: [{ required: true, message: '类型编码必填！', trigger: 'blur' }],
})


// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  // 清空dialogForm中的值
  resetFormContent()
  // 重置表单
  dialogFormRef.value?.resetFields()
}

// 保存数据
const save = () => {
  try {
    dialogFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        if (formContent.value.id) {
          await updateDictType(formContent.value)
        } else {
          await addDictType(formContent.value)
        }
        ElMessage.success({ message: `${dialogTitle.value}成功！` })
        close()
        // 刷新表格
        await props.refreshTable!()
      }
    })
  } catch (err) {
    console.error('验证过程中出现错误', err)
  }
}

// 打开弹窗，可能是新增，也可能是编辑
const open = (sign: string, data: Dict.ResDictType) => {
  titleType.value = sign
  dialogVisible.value = true
  if (data.id) {
    formContent.value = { ...data }
  } else {
    resetFormContent()
  }
}

// 对外映射
defineExpose({ open })
const props = defineProps<{
  refreshTable: (() => Promise<void>) | undefined;
}>()

</script>