<script setup lang="ts">
import type { FormInstance } from 'antdv-next'
import apiSysDept from '@/api/modules/sysDept'

export interface Props { id?: number | string }
const props = withDefaults(defineProps<Props>(), { id: '' })

const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  id: props.id as number | string, parent_id: undefined as number | undefined,
  dept_name: '', order_num: 0, leader: '', phone: '', email: '', status: '0',
})

const rules = { dept_name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }] }

// Parent dept options
const deptOptions = ref<{ value: number; label: string }[]>([])

onMounted(() => {
  apiSysDept.list().then((res: any) => { deptOptions.value = res.data.map((i: any) => ({ value: i.id, label: i.name })) })
  if (form.value.id !== '') getInfo()
})

function getInfo() {
  loading.value = true
  apiSysDept.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      parent_id: d.parent_id, dept_name: d.dept_name, order_num: d.order_num,
      leader: d.leader, phone: d.phone, email: d.email, status: d.status,
    })
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiSysDept.save(form.value).then(() => { faToast.success(form.value.id ? '编辑成功' : '新增成功'); resolve() })
      }).catch(() => {})
    })
  },
})
</script>

<template>
  <div v-if="loading" class="flex-center py-12"><ASpin /></div>
  <AForm v-else ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
    <AFormItem label="部门名称" name="dept_name"><AInput v-model:value="form.dept_name" placeholder="请输入部门名称" /></AFormItem>
    <AFormItem label="上级部门" name="parent_id">
      <ASelect v-model:value="form.parent_id" placeholder="无（根部门）" allow-clear :options="deptOptions" />
    </AFormItem>
    <AFormItem label="排序" name="order_num"><AInputNumber v-model:value="form.order_num" class="w-full" /></AFormItem>
    <AFormItem label="负责人" name="leader"><AInput v-model:value="form.leader" placeholder="请输入负责人" /></AFormItem>
    <AFormItem label="电话" name="phone"><AInput v-model:value="form.phone" placeholder="请输入电话" /></AFormItem>
    <AFormItem label="邮箱" name="email"><AInput v-model:value="form.email" placeholder="请输入邮箱" /></AFormItem>
    <AFormItem label="状态" name="status"><ASelect v-model:value="form.status" :options="[{ value: '0', label: '正常' }, { value: '1', label: '停用' }]" /></AFormItem>
  </AForm>
</template>
