<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="年级">
            <el-select v-model="formData.grade" placeholder="请选择">
              <el-option
                v-for="year in gradeOptions"
                :key="year"
                :label="year"
                :value="year"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="userNumber">
            <el-input v-model="formData.userNumber" placeholder="请输入学号"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="专业" prop="major">
            <!-- <el-input v-model="formData.major" placeholder="请输入专业" /> -->
            <el-select v-model="formData.major" placeholder="请选择专业">
              <el-option
                v-for="option in majorOptions"
                :key="option.value"
                :label="option.value"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="硕士类型" prop="masterType">
            <!-- <el-input v-model="formData.masterType" placeholder="请输入学位类型" /> -->
            <el-select v-model="formData.masterType" placeholder="请选择硕士类型">
              <el-option
                v-for="option in masterTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <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>
        <!-- <el-col :span="12">
          <el-form-item label="工作间" prop="deptId" v-if="userInfo.userType === '4'">
            <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="userType">
            <!-- <span style="margin-left: 10px;">毕业生</span>
            <input v-model="formData.userType" value="2" hidden /> -->
            <el-input v-model="userTypeG" value="毕业生" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作地点" prop="workPlace">
            <el-input v-model="formData.workPlace" maxlength="11" placeholder="请输入工作地点" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <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 label="导师名称" prop="supervisorId" v-if="userInfo.userType === '4'">
            <el-select
              v-model="formData.supervisor"
              @change="handleSupervisorChange"
              placeholder="请选择导师名称"
              clearable
              filterable
              class="!w-full"
            >
              <el-option
                v-for="user in users"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </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>
        <el-col :span="24">
          <el-form-item label="导师电话" prop="supervisorMobile" v-if="userInfo.userType === '4'">
            <el-input v-model="formData.supervisorMobile" maxlength="11" placeholder="请输入导师电话" />
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <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 lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { FormRules } from 'element-plus'
import { computed } from 'vue';
import { getUserProfile, ProfileVO } from '@/api/system/user/profile'

defineOptions({ name: 'SystemUserForm' })

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

const userInfo = ref({} as ProfileVO)
const getUserInfo = async () => {
  const users = await getUserProfile()
  console.log(users)
  userInfo.value = users
}


const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  nickname: '',
  deptId: '',
  grade: '',
  userNumber: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: [],
  userType: '',
  supervisor:'',
  supervisorId:'',
  supervisorMobile: '',
  workPlace:"",
  major: "",
  masterType: undefined,
})
const formRules = reactive<FormRules>({
  nickname: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  userNumber: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
  userType: [{ required: true, message: '用户类型不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([] as PostApi.PostVO[]) // 岗位列表


//用户类型
// const userTypes = ref([
//   { label: '本校生', value: "1" },
//   { label: '毕业生', value: "2" },
//   // { label: '导师', value: "3" },
//   // { label: '学院', value: "4" }
// ]);
const userTypeG = ref('2')

const currentYear = new Date().getFullYear(); // 获取当前年份
const gradeOptions = computed(() => {
  return [
    currentYear +'级',          // 今年
    currentYear - 1 +'级',      // 去年
    currentYear - 2 +'级',      // 前年
    currentYear - 3 +'级',      // 大前年
    currentYear - 4 +'级',      // 大大前年
  ];
});

// 获取所有专业
const majorOptions = [
  { value: '测绘工程' },
  { value: '测绘科学与技术' },
  { value: '资源与环境' },
]

// 获取所有学位类型
const masterTypeOptions = [
  { value: 1, label:"学硕" },
  { value: 2 , label:"专硕"},
]

//获取所有导师
const users = ref()
const getSupervisor= async () => {
  try {
    const response = await UserApi.getSupervisor()
    users.value = response
  } catch (error) {
    console.error('Error fetching user data:', error)
  }
}
//传supervisorId给formData.supervisorId
const handleSupervisorChange = (value: number) => {
  const selectedUser = users.value.find(user => user.id === value);
  if (selectedUser) {
    formData.value.supervisorId = selectedUser.id;
    formData.value.supervisor = selectedUser.nickname;
  }
}


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // dialogTitle.value = t('action.' + type)
  if (type === 'create') {
    dialogTitle.value = '创建毕业生'
  } else {
    dialogTitle.value = '修改'
  }
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 加载岗位列表
  postList.value = await PostApi.getSimplePostList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    deptId: '',
    grade: '',
    userNumber: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: [],
    userType: '',
    supervisor:'',
    supervisorId:'',
    supervisorMobile: '',
    workPlace:"",
    major: "",
    masterType: undefined,
  }
  formRef.value?.resetFields()
}
onMounted(() => {
  getSupervisor()
  getUserInfo()
})
</script>
