<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 800px">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入员工姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-radio-group v-model="formData.sex">
              <el-radio :value="1"> 男 </el-radio>
              <el-radio :value="2"> 女 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="组织部门" prop="dept">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="post">
            <el-input v-model="formData.post" placeholder="请输入职位" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="考勤方案" prop="attendanceSettingId">
            <el-select
              v-model="formData.attendanceSettingId"
              placeholder="选择考勤方案"
              clearable
              filterable
            >
              <el-option
                v-for="item in attendanceSettingIdOptions"
                :key="item.attendanceSettingId"
                :label="item.name"
                :disabled="item.status == 1"
                :value="item.attendanceSettingId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="开通系统" prop="instanceIds">
            <el-select
              v-model="formData.instanceIds"
              placeholder="选择开通系统"
              multiple
              collapse-tags
              clearable
              filterable
            >
              <el-option
                v-for="item in instanceIdsOptions"
                :key="item.instanceId"
                :label="item.instanceName"
                :disabled="item.status == 1"
                :value="item.instanceId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="登录账号" prop="username">
            <el-input v-model="formData.username" placeholder="请输入登录账号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="用户密码" prop="password">
            <el-input
              v-model="formData.password"
              placeholder="请输入用户密码"
              show-password
              type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker
              v-model="formData.hireDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="离职日期" prop="retireDate">
            <el-date-picker
              v-model="formData.retireDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="钉钉手机号">
            <el-input
              v-model="formData.ddPhone"
              placeholder="请输入钉钉手机号"
              clearable
              @blur="getDingdingUserId"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="钉钉Id" prop="dingUserId">
            <el-input v-model="formData.dingUserId" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="微信号" prop="wxAlias">
            <el-input v-model="formData.wxAlias" placeholder="请输入微信号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="绩效考核人" prop="meritsExamineUserList">
            <el-select
              v-model="formData.meritsExamineUserList"
              placeholder="选择绩效考核人"
              clearable
              filterable
              multiple
              collapse-tags
            >
              <el-option
                v-for="item in employeeOptions"
                :key="item.id"
                :disabled="item.status == 1"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script name="DialogEmployee" setup>
import { CommonStatusEnum } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { defaultProps, handleTree } from '@/utils/tree'
import { getPlanSimpleList } from '@/api/pers/attendancePlan'
import { getSimpleAppList } from '@/api/system/app'
import * as DeptApi from '@/api/system/dept'

import * as EmployeeApi from '@/api/pers/employee'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({})
const formRules = ref({
  name: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  post: { required: true, message: '职位不能为空', trigger: 'blur' },
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const attendanceSettingIdOptions = ref([])
const instanceIdsOptions = ref([])
const employeeOptions = ref([])

const deptList = ref([])

/** 打开弹窗 */
const open = async (type, id) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await EmployeeApi.getEmployeeDetail(id)
    } finally {
      formLoading.value = false
    }
  }
  deptList.value = handleTree(await DeptApi.getSimpleDeptList({ allFlag: true }))
  getOptions()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

function getOptions() {
  getSimpleAppList().then((data) => {
    instanceIdsOptions.value = data
  })
  getPlanSimpleList().then((data) => {
    attendanceSettingIdOptions.value = data
  })
  EmployeeApi.getEmployeeSimpleList().then((data) => {
    employeeOptions.value = data
  })
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await EmployeeApi.createEmployee(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeApi.updateEmployee(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    post: undefined,
    dept: undefined,
    sex: 1,
    remark: '',
    status: CommonStatusEnum.ENABLE,
    hireDate: formatDate(new Date(), 'YYYY-MM-DD'),
    retireDate: undefined,
    attendanceSettingId: undefined,
    instanceIds: [],
    wxAlias: '',
    meritsExamineUserList: []
  }
  formRef.value?.resetFields()
}

async function getDingdingUserId() {
  try {
    if (!formData.value.ddPhone) {
      formData.value.dingUserId = undefined
      return
    }
    const data = await EmployeeApi.getDingUserId({ mobile: formData.value.ddPhone })
    formData.value.dingUserId = data
  } finally {
  }
}
</script>
