<template>
  <el-dialog
    :model-value="visible"
    title="新建人员"
    @closed="onClose"
    @open="onOpen"
    :destroy-on-close="true"
    :append-to-body="true"
  >
    <el-form :model="formUserData" ref="formRef" :rules="rules" label-position="left">
      <el-form-item label="人员名称" prop="userName">
        <el-input v-model="formUserData.userName"></el-input>
      </el-form-item>
      <el-form-item label="人员代码" prop="userCode">
        <CacpAutocomplete v-model="formUserData.userCode"></CacpAutocomplete>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="onUserSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'

import type { DialogInfo } from './types'
import { CacpAutocomplete } from '@cacp/ui'

const props = defineProps<{
  visible: boolean
  info: DialogInfo
}>()
const emits = defineEmits<{
  (e: 'on-close'): void
  (e: 'on-save', info: DialogInfo): void
}>()

const formUserData = ref({ id: '', userName: '', userCode: '' })
const formRef = ref()
const rules = {
  userName: [{ required: true, message: '请输入人员名称' }],
  userCode: [{ required: true, message: '请输入人员代码' }]
}

async function onUserSubmit() {
  if (await formRef.value?.validate()) {
    emits('on-save', formUserData.value)
  }
}

function onOpen() {
  formUserData.value = cloneDeep(props.info)
}

function onClose() {
  emits('on-close')
}
</script>
