<template>
  <el-dialog
    v-model="showDialog"
    class="add-person-dialog"
    title="添加人员"
    width="800"
    destroy-on-close
    @close="initForm()"
  >
    <el-form :model="formData" ref="ruleFormRef" :rules="rules" label-position="top" class="add-person-dialog__form">
      <el-form-item prop="positionId" label="岗位职责">
        <el-select v-model="formData.positionId" placeholder="请选择职位">
          <el-option
            v-for="position in props.positionOptions"
            :key="position.positionLevel"
            :label="position.title"
            :value="position.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="realname" label="姓名">
        <el-select
          v-model="formData.realname"
          filterable
          remote
          reserve-keyword
          placeholder="输入名字搜索"
          :remote-method="getUsers"
          :loading="loading"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.realname"
            :value="user.realname"
            @click="setUserInfo(user)"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="staffNo" label="员工号">
        <el-input v-model="formData.staffNo" />
      </el-form-item>
      <el-form-item prop="mobile" label="联系电话">
        <el-input v-model="formData.mobile" type="number" />
      </el-form-item>
      <el-form-item prop="deptName" label="部门">
        <el-input v-model="formData.deptName" />
      </el-form-item>
      <el-form-item prop="jobName" label="职务">
        <el-input v-model="formData.jobName" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm"> 提交 </el-button>
        <el-button @click="showDialog = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { storeToRefs } from 'pinia';
  import type { FormInstance, FormRules } from 'element-plus';
  import useTeamStore from '../../store/userTeam';
  import { UserType, queryUserListByUsername } from '@/api/user/user';
  import { PositionType, saveTeamPersonnel } from '@/api/emergency-organization/teams';

  const props = defineProps<{ positionOptions: PositionType[] }>();

  type PersonInfo = {
    userId: number;
    positionId: string;
    realname: string;
    staffNo: string;
    mobile: string;
    deptName: string;
    jobName: string;
  };

  const showDialog = ref(false);
  const loading = ref(false);
  const userOptions = ref<UserType[]>([]);

  const { curTeam, loadingTeamInfo } = storeToRefs(useTeamStore());
  const { refreshCurTeamInfo } = useTeamStore();

  const formData = ref<PersonInfo>({
    userId: 0,
    positionId: '',
    realname: '',
    staffNo: '',
    mobile: '',
    deptName: '',
    jobName: '',
  });
  const ruleFormRef = ref<FormInstance>();
  const rules = ref<FormRules<PersonInfo>>({
    positionId: [{ required: true, message: '请选择岗位', trigger: 'blur' }],
    realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    staffNo: [{ required: true, message: '请输入员工号', trigger: 'blur' }],
    mobile: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  });

  function initForm() {
    formData.value = {
      userId: 0,
      positionId: '',
      realname: '',
      staffNo: '',
      mobile: '',
      deptName: '',
      jobName: '',
    };
  }

  function dialogShow() {
    showDialog.value = true;
  }

  async function getUsers(username: string) {
    if (username) {
      loading.value = true;
      userOptions.value = await queryUserListByUsername(username);
      loading.value = false;
    } else {
      userOptions.value = [];
    }
  }

  function setUserInfo(user: UserType) {
    formData.value.userId = user.id;
    formData.value.staffNo = user.staffNo;
    formData.value.mobile = user.mobile;
    formData.value.deptName = user.deptName;
    formData.value.jobName = user.jobName;
  }

  async function submitForm() {
    await ruleFormRef.value!.validate(async (valid) => {
      if (valid) {
        loadingTeamInfo.value = true;
        showDialog.value = false;

        const data = {
          teamId: curTeam.value!.teamId,
          department: formData.value.deptName,
          jobTitle: formData.value.jobName,
          ...formData.value,
        };
        saveTeamPersonnel(data)
          .then(() => {
            refreshCurTeamInfo();
          })
          .finally(() => {
            loadingTeamInfo.value = false;
          });
      }
    });
  }

  defineExpose({
    dialogShow,
  });
</script>

<style scoped lang="scss">
  .add-person-dialog__header {
  }
  .add-person-dialog__form {
    display: grid;
    grid-template-columns: repeat(2, 45%);
    justify-content: space-around;

    // 去掉el input右侧的小箭头
    :deep(input::-webkit-outer-spin-button),
    :deep(input::-webkit-inner-spin-button) {
      -webkit-appearance: none;
    }
  }

  :deep(.el-dialog__header) {
    text-align: left;
    font-weight: bold;
  }
</style>

<style>
  .add-person-dialog {
    min-height: 0;
  }
</style>
