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

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, user_name: '', nick_name: '', password: '',
  dept_id: undefined as number | undefined, email: '', phonenumber: '',
  sex: '0', status: '0', remark: '',
})

const rules = {
  user_name: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  nick_name: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
}

const deptOptions = ref<{ value: number; label: string }[]>([])
const roleOptions = ref<{ value: number; label: string }[]>([])
const roleIds = ref<number[]>([])

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

function getInfo() {
  loading.value = true
  apiSysUser.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      user_name: d.user_name, nick_name: d.nick_name,
      dept_id: d.dept_id, email: d.email, phonenumber: d.phonenumber,
      sex: d.sex, status: d.status, remark: d.remark,
    })
    roleIds.value = d.role_ids || []
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiSysUser.save(form.value).then((res: any) => {
          const userId = form.value.id || res.data?.id
          if (userId && roleIds.value.length > 0) {
            apiSysUser.assignRoles({ id: userId as number, role_ids: roleIds.value })
          }
          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="user_name"><AInput v-model:value="form.user_name" placeholder="请输入登录账号" /></AFormItem>
    <AFormItem label="用户昵称" name="nick_name"><AInput v-model:value="form.nick_name" placeholder="请输入用户昵称" /></AFormItem>
    <AFormItem v-if="!form.id" label="密码" name="password"><AInput v-model:value="form.password" type="password" placeholder="请输入密码" /></AFormItem>
    <AFormItem label="部门" name="dept_id">
      <ASelect v-model:value="form.dept_id" placeholder="请选择部门" allow-clear show-search :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="deptOptions" />
    </AFormItem>
    <AFormItem label="角色" name="role_ids">
      <ASelect v-model:value="roleIds" mode="multiple" placeholder="请选择角色" :options="roleOptions" />
    </AFormItem>
    <AFormItem label="手机号" name="phonenumber"><AInput v-model:value="form.phonenumber" placeholder="请输入手机号" /></AFormItem>
    <AFormItem label="邮箱" name="email"><AInput v-model:value="form.email" placeholder="请输入邮箱" /></AFormItem>
    <AFormItem label="性别" name="sex">
      <ASelect v-model:value="form.sex" :options="[{ value: '0', label: '男' }, { value: '1', label: '女' }, { value: '2', label: '未知' }]" />
    </AFormItem>
    <AFormItem label="状态" name="status"><ASelect v-model:value="form.status" :options="[{ value: '0', label: '正常' }, { value: '1', label: '停用' }]" /></AFormItem>
    <AFormItem label="备注" name="remark"><ATextarea v-model:value="form.remark" placeholder="请输入备注" :rows="2" /></AFormItem>
  </AForm>
</template>
