<template>
  <div class="personal-info-container">
    <PageTitle title="个人信息" />

    <el-form ref="formRef" :model="formData" :rules="rules" label-position="top" class="info-form">
      <div class="form-row">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="formData.userId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入" />
          <div class="form-tip">手机号码用于登录账号、重置密码或其他安全认证 <el-button type="danger" link>更换手机号</el-button></div>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="办公电话" prop="officePhone">
          <el-input v-model="formData.officePhone" placeholder="请输入" />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择" style="width: 100%">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择" style="width: 100%">
            <el-option v-for="role in roleList" :key="role.roleId" :label="role.roleName" :value="role.roleId.toString()" />
          </el-select>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="formData.birthday" type="date" placeholder="请选择日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="formData.wechat" placeholder="请输入" />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-select v-model="formData.department" placeholder="请选择" style="width: 100%">
            <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId.toString()" />
          </el-select>
        </el-form-item>
      </div>

      <div class="form-row single">
        <el-form-item label="所在地区" prop="subDepartment">
          <el-input v-model="formData.subDepartment" placeholder="请输入省市区" />
        </el-form-item>
      </div>

      <div class="form-row single">
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入" maxlength="50" show-word-limit />
        </el-form-item>
      </div>

      <div class="form-row single">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入" maxlength="50" show-word-limit />
        </el-form-item>
      </div>

      <div class="form-actions">
        <el-button type="danger" @click="handleSave">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { PageTitle } from '@/components';
import { getCurrentUserInfo, updateContact, getDeptList, getDeptTree, getRoleList } from '@/api/pc/organization';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sex'));

const formRef = ref();
const deptList = ref<any[]>([]);
const roleList = ref<any[]>([]);

const formData = reactive({
  id: 0,
  userId: '',
  phone: '',
  realName: '',
  officePhone: '',
  gender: '',
  role: '',
  birthday: '',
  wechat: '',
  email: '',
  department: '',
  subDepartment: '',
  address: '',
  remark: ''
});

const rules = {
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }]
};

// 获取当前用户信息
const loadUserInfo = async () => {
  try {
    const res = await getCurrentUserInfo();
    if (res.code === 200 && res.data) {
      // 映射后端字段到前端字段
      formData.id = res.data.id;
      formData.userId = res.data.id?.toString() || '';
      formData.phone = res.data.phone || '';
      formData.realName = res.data.contactName || '';
      formData.officePhone = res.data.officePhone || '';
      formData.gender = res.data.gender || '';
      formData.role = res.data.roleId?.toString() || '';
      formData.birthday = res.data.birthday || '';
      formData.wechat = res.data.customLoginName || ''; // 微信号映射到customLoginName
      formData.email = res.data.email || '';
      formData.department = res.data.deptId?.toString() || ''; // 部门ID
      formData.subDepartment = res.data.provincialCityCounty || ''; // 省市区
      formData.address = res.data.addressDetail || '';
      formData.remark = res.data.remark || '';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

const handleSave = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;

  try {
    // 映射前端字段到后端字段
    const data = {
      id: formData.id,
      contactName: formData.realName,
      phone: formData.phone,
      officePhone: formData.officePhone,
      gender: formData.gender,
      roleId: formData.role || undefined,
      deptId: formData.department || undefined,
      birthday: formData.birthday,
      customLoginName: formData.wechat,
      email: formData.email,
      provincialCityCounty: formData.subDepartment,
      addressDetail: formData.address,
      remark: formData.remark
    };

    await updateContact(data);
    ElMessage.success('保存成功');
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};

// 加载部门列表
const loadDeptList = async () => {
  try {
    const res = await getDeptTree();
    console.log('部门列表响应:', res);
    if (res.code === 200 && res.data) {
      deptList.value = res.data;
      console.log('部门列表加载成功:', deptList.value);
    }
  } catch (error) {
    console.error('获取部门列表失败:', error);
  }
};

// 加载角色列表
const loadRoleList = async () => {
  try {
    const res = await getRoleList();
    if (res.code === 200 && res.data) {
      roleList.value = res.data;
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
  }
};

// 页面加载时获取用户信息、部门列表和角色列表
onMounted(async () => {
  // 先加载部门和角色列表，再加载用户信息
  await Promise.all([loadDeptList(), loadRoleList()]);
  await loadUserInfo();
});
</script>

<style scoped lang="scss">
.personal-info-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
}

.info-form {
  max-width: 900px;

  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px 40px;

    &.single {
      grid-template-columns: 1fr;
    }
  }

  .form-tip {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }

  :deep(.el-form-item__label) {
    font-size: 14px;
    color: #333;
    padding-bottom: 8px;
  }

  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper),
  :deep(.el-textarea__inner) {
    background: #f5f5f5;
    box-shadow: none;
    border: none;
  }

  .form-actions {
    margin-top: 30px;
    text-align: center;
  }
}
</style>
