<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? $t('page.form.titleAdd') : $t('page.form.titleEdit')"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item :label="$t('page.form.labelDeptName')" prop="name">
        <el-input v-model="formData.name" :placeholder="$t('page.form.placeholderDeptName')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelDeptCode')" prop="code">
        <el-input v-model="formData.code" :placeholder="$t('page.form.placeholderDeptCode')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelLeader')">
        <sa-user v-model="formData.leader_id" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelRemark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          :placeholder="$t('page.form.placeholderRemark')"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelSort')" prop="sort">
        <el-input-number v-model="formData.sort" :placeholder="$t('page.form.placeholderSort')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelStatus')" prop="status">
        <sa-radio v-model="formData.status" dict="data_status" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('table.form.submit') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '@/api/system/dept'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useI18n } from 'vue-i18n'

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, any>
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    data: undefined
  })

  const emit = defineEmits<Emits>()
  const { t } = useI18n()

  const formRef = ref<FormInstance>()

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const rules = computed<FormRules>(() => ({
    name: [{ required: true, message: t('page.form.ruleDeptNameRequired'), trigger: 'blur' }],
    code: [{ required: true, message: t('page.form.ruleDeptCodeRequired'), trigger: 'blur' }]
  }))

  const initialFormData = {
    id: null,
    parent_id: 0,
    level: '0',
    name: '',
    code: '',
    leader_id: null,
    remark: '',
    sort: 100,
    status: 1
  }

  const formData = reactive({ ...initialFormData })

  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        initPage()
      }
    }
  )

  const initPage = async () => {
    Object.assign(formData, initialFormData)
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  const initForm = () => {
    if (props.data) {
      for (const key in formData) {
        if (props.data[key] != null && props.data[key] != undefined) {
          ;(formData as any)[key] = props.data[key]
        }
      }
    }
  }

  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      formData.parent_id = 0
      formData.level = '0'
      if (props.dialogType === 'add') {
        await api.save(formData)
        ElMessage.success(t('page.form.addSuccess'))
      } else {
        await api.update(formData)
        ElMessage.success(t('page.form.editSuccess'))
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
