Files
ks-app-employment-service/packageA/pages/personalInfo/personalInfo.vue
2025-11-10 15:27:34 +08:00

608 lines
21 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<AppLayout
title="个人信息"
:sub-title="`完成度${percent}`"
border
back-gorund-color="#ffffff"
:show-bg-image="false"
>
<template #headerleft>
<view class="btn mar_le20 button-click" @click="navBack">取消</view>
</template>
<template #headerright>
<view class="btn mar_ri20 button-click" @click="confirm">确认</view>
</template>
<view class="content">
<view class="content-input">
<view class="input-titile">姓名</view>
<input class="input-con" v-model="fromValue.name" placeholder="请输入您的姓名" />
</view>
<view class="content-sex">
<view class="sex-titile">性别</view>
<view class="sext-ri">
<view class="sext-box" :class="{ 'sext-boxactive': fromValue.sex === 0 }" @click="changeSex(0)">
</view>
<view class="sext-box" :class="{ 'sext-boxactive': fromValue.sex === 1 }" @click="changeSex(1)">
</view>
</view>
</view>
<view class="content-input" @click="changeDateBirt">
<view class="input-titile">出生年月</view>
<input
class="input-con triangle"
v-model="fromValue.birthDate"
disabled
placeholder="请选择您的出生年月"
/>
</view>
<view class="content-input" @click="changeEducation">
<view class="input-titile">学历</view>
<input class="input-con triangle" v-model="state.educationText" disabled placeholder="请选择您的学历" />
</view>
<view class="content-input" @click="changePoliticalAffiliation">
<view class="input-titile">政治面貌</view>
<input
class="input-con triangle"
v-model="state.politicalAffiliationText"
disabled
placeholder="请选择您的政治面貌"
/>
</view>
<view class="content-input">
<view class="input-titile">身份证</view>
<input class="input-con" v-model="fromValue.idCard" placeholder="请输入身份证号码" />
</view>
<view class="content-input">
<view class="input-titile">手机号码</view>
<input class="input-con" v-model="fromValue.phone" placeholder="请输入您的手机号码" />
</view>
</view>
<SelectPopup ref="selectPopupRef"></SelectPopup>
</AppLayout>
</template>
<script setup>
import { reactive, inject, watch, ref, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
const { $api, navTo, navBack, checkingPhoneRegExp } = inject('globalFunction');
import { storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
import useDictStore from '@/stores/useDictStore';
import SelectPopup from '@/components/selectPopup/selectPopup.vue';
const { userInfo } = storeToRefs(useUserStore());
const { getUserResume } = useUserStore();
const dictStore = useDictStore();
const { dictLabel, oneDictData, complete: dictComplete, getDictSelectOption } = dictStore;
// #ifdef H5
const injectedOpenSelectPopup = inject('openSelectPopup', null);
// #endif
// #ifdef MP-WEIXIN
const selectPopupRef = ref();
// #endif
// 创建本地的 openSelectPopup 函数,兼容 H5 和微信小程序
const openSelectPopup = (config) => {
// #ifdef MP-WEIXIN
if (selectPopupRef.value) {
selectPopupRef.value.open(config);
}
// #endif
// #ifdef H5
if (injectedOpenSelectPopup) {
injectedOpenSelectPopup(config);
}
// #endif
};
const percent = ref('0%');
const state = reactive({
educationText: '',
politicalAffiliationText: '',
});
const fromValue = reactive({
name: '',
sex: 0,
birthDate: '',
education: '',
politicalAffiliation: '',
idCard: '',
});
onLoad(() => {
initLoad();
});
// 监听 userInfo 变化,确保数据及时更新
watch(() => userInfo.value, (newVal) => {
if (newVal && Object.keys(newVal).length > 0) {
initLoad();
}
}, { deep: true, immediate: false });
// 监听字典数据加载完成,自动更新学历显示
watch(() => dictComplete.value, (newVal) => {
if (newVal) {
console.log('字典数据加载完成,更新学历显示');
// 确保有学历值(如果没有则使用默认值"4"本科)
if (!fromValue.education) {
fromValue.education = '4';
}
// 直接遍历字典数据查找对应标签
const eduValue = String(fromValue.education);
const eduItem = dictStore.state.education.find(item => String(item.value) === eduValue);
if (eduItem && eduItem.label) {
console.log('从字典数据中找到学历标签:', eduItem.label);
state.educationText = eduItem.label;
}
}
});
// 监听学历字典数据变化
watch(() => dictStore.state.education, (newVal) => {
if (newVal && newVal.length > 0) {
console.log('学历字典数据变化,更新显示');
// 确保有学历值(如果没有则使用默认值"4"本科)
if (!fromValue.education) {
fromValue.education = '4';
}
// 直接遍历字典数据查找对应标签
const eduValue = String(fromValue.education);
const eduItem = newVal.find(item => String(item.value) === eduValue);
if (eduItem && eduItem.label) {
console.log('从字典数据中找到学历标签:', eduItem.label);
state.educationText = eduItem.label;
}
}
}, { deep: true });
function initLoad() {
// 优先从 store 获取,如果没有则从本地缓存获取
const cachedUserInfo = uni.getStorageSync('userInfo') || {};
const currentUserInfo = userInfo.value && Object.keys(userInfo.value).length > 0 ? userInfo.value : cachedUserInfo;
fromValue.name = currentUserInfo.name || '';
fromValue.sex = currentUserInfo.sex !== undefined ? Number(currentUserInfo.sex) : 0;
fromValue.phone = currentUserInfo.phone || '';
fromValue.birthDate = currentUserInfo.birthDate || '';
// 将学历转换为字符串类型,确保类型一致
// 如果没有学历值,默认设置为本科(值为"4"
fromValue.education = currentUserInfo.education ? String(currentUserInfo.education) : '4';
fromValue.politicalAffiliation = currentUserInfo.politicalAffiliation || '';
fromValue.idCard = currentUserInfo.idCard || '';
// 初始化学历显示文本(需要等待字典数据加载完成)
initEducationText();
// 回显政治面貌
if (currentUserInfo.politicalAffiliation) {
state.politicalAffiliationText = dictLabel('affiliation', currentUserInfo.politicalAffiliation);
}
const result = getFormCompletionPercent(fromValue);
percent.value = result;
}
// 初始化学历显示文本
function initEducationText() {
// 确保有学历值(如果没有则使用默认值"4"本科)
if (!fromValue.education) {
fromValue.education = '4';
}
console.log('初始化学历显示,当前学历值:', fromValue.education);
// 直接遍历字典数据查找对应标签不依赖dictLabel函数确保准确性
const findLabelFromDict = () => {
if (dictStore.state.education && dictStore.state.education.length > 0) {
const eduValue = String(fromValue.education);
const eduItem = dictStore.state.education.find(item => String(item.value) === eduValue);
if (eduItem && eduItem.label) {
console.log('从字典数据中找到学历标签:', eduItem.label);
state.educationText = eduItem.label;
return true;
} else {
console.log('字典数据中未找到匹配的学历标签');
}
}
return false;
};
// 立即尝试查找
if (!findLabelFromDict() && dictComplete.value) {
// 如果字典数据已加载完成但未找到标签,尝试重新获取字典数据
loadEducationDictAndUpdate();
}
// 等待字典数据加载完成
const checkDictData = () => {
if (dictComplete.value && dictStore.state.education && dictStore.state.education.length > 0) {
findLabelFromDict();
} else {
// 如果字典数据未加载,等待一段时间后重试
setTimeout(() => {
if (dictComplete.value && dictStore.state.education && dictStore.state.education.length > 0) {
findLabelFromDict();
} else {
// 尝试主动加载字典数据
loadEducationDictAndUpdate();
}
}, 500);
}
};
// 主动加载学历字典数据并更新显示
function loadEducationDictAndUpdate() {
getDictSelectOption('education').then((data) => {
console.log('主动加载学历字典数据:', data);
dictStore.state.education = data;
findLabelFromDict();
}).catch((error) => {
console.error('加载学历字典数据失败:', error);
});
}
checkDictData();
}
const confirm = () => {
if (!fromValue.name) {
return $api.msg('请输入姓名');
}
if (!fromValue.birthDate) {
return $api.msg('请选择出生年月');
}
if (!fromValue.education) {
return $api.msg('请选择学历');
}
if (!fromValue.politicalAffiliation) {
return $api.msg('请选择政治面貌');
}
if (!checkingPhoneRegExp(fromValue.phone)) {
return $api.msg('请输入正确手机号');
}
const params = {
...fromValue,
age: calculateAge(fromValue.birthDate),
};
$api.createRequest('/app/user/resume', params, 'post').then((resData) => {
$api.msg('完成');
state.disbleDate = true;
getUserResume().then(() => {
navBack();
});
});
};
const changeDateBirt = () => {
const datearray = generateDatePickerArrays();
const defaultIndex = getDatePickerIndexes(fromValue.birthDate);
openSelectPopup({
title: '年龄段',
maskClick: true,
data: datearray,
defaultIndex,
success: (_, value) => {
const [year, month, day] = value;
const dateStr = `${year.value}-${month.value}-${day.value}`;
if (isValidDate(dateStr)) {
fromValue.birthDate = dateStr;
} else {
$api.msg('没有这一天');
}
},
});
};
async function changeEducation() {
// 确保字典数据已加载
if (!dictComplete.value || !dictStore.state.education || dictStore.state.education.length === 0) {
// 如果字典数据未加载,先加载数据
try {
await getDictSelectOption('education').then((data) => {
dictStore.state.education = data;
});
} catch (error) {
console.error('加载学历字典数据失败:', error);
}
}
// 等待数据加载完成后再获取数据
let educationData = oneDictData('education');
// 如果数据还是为空,等待一下再试
if (!educationData || educationData.length === 0) {
await new Promise(resolve => setTimeout(resolve, 100));
educationData = oneDictData('education');
if (!educationData || educationData.length === 0) {
$api.msg('学历数据加载中,请稍后再试');
return;
}
}
// 确保有默认值
if (!fromValue.education) {
fromValue.education = '4'; // 默认设置为本科
}
// 将当前学历值转换为字符串,用于查找默认索引
const currentEducation = String(fromValue.education);
// 查找当前学历在数据中的索引
let defaultIndex = [0];
if (currentEducation && educationData && educationData.length > 0) {
// 同时支持字符串和数字类型的匹配
const index = educationData.findIndex(item => {
const itemValue = String(item.value);
return itemValue === currentEducation;
});
if (index >= 0) {
defaultIndex = [index];
console.log('找到学历默认索引:', index, '当前值:', currentEducation);
} else {
// 如果字符串匹配失败,尝试数字匹配
const currentNum = Number(currentEducation);
if (!isNaN(currentNum)) {
const numIndex = educationData.findIndex(item => {
const itemValue = Number(item.value);
return !isNaN(itemValue) && itemValue === currentNum;
});
if (numIndex >= 0) {
defaultIndex = [numIndex];
console.log('通过数字匹配找到学历默认索引:', numIndex, '当前值:', currentNum);
} else {
console.warn('未找到匹配的学历值:', currentEducation, '可用值:', educationData.map(item => item.value));
}
}
}
}
openSelectPopup({
title: '学历',
maskClick: true,
data: [educationData],
defaultIndex: defaultIndex,
success: (_, [value]) => {
console.log('切换学历选择,新值:', value.value);
fromValue.education = String(value.value); // 确保存储为字符串
// 使用相同的字典数据查找逻辑
const eduValue = String(value.value);
const eduItem = dictStore.state.education.find(item => String(item.value) === eduValue);
if (eduItem && eduItem.label) {
console.log('从字典数据中找到学历标签:', eduItem.label);
state.educationText = eduItem.label;
} else {
// 如果没找到,尝试重新加载字典数据
console.log('字典中未找到对应标签,尝试重新加载字典数据');
getDictSelectOption('education').then((data) => {
dictStore.state.education = data;
const newEduItem = data.find(item => String(item.value) === eduValue);
if (newEduItem && newEduItem.label) {
state.educationText = newEduItem.label;
}
});
}
},
});
}
const changeSex = (sex) => {
fromValue.sex = sex;
};
const changePoliticalAffiliation = () => {
openSelectPopup({
title: '政治面貌',
maskClick: true,
data: [oneDictData('affiliation')],
success: (_, [value]) => {
fromValue.politicalAffiliation = value.value;
state.politicalAffiliationText = value.label;
},
});
};
function generateDatePickerArrays(startYear = 1975, endYear = new Date().getFullYear()) {
const years = [];
const months = [];
const days = [];
for (let y = startYear; y <= endYear; y++) {
years.push(y.toString());
}
for (let m = 1; m <= 12; m++) {
months.push(m.toString().padStart(2, '0'));
}
for (let d = 1; d <= 31; d++) {
days.push(d.toString().padStart(2, '0'));
}
return [years, months, days];
}
function isValidDate(dateString) {
// 添加空值检查
if (!dateString || typeof dateString !== 'string' || dateString.trim() === '') {
return false;
}
const dateParts = dateString.split('-');
if (dateParts.length !== 3) {
return false;
}
const [year, month, day] = dateParts.map(Number);
// 检查是否为有效数字
if (isNaN(year) || isNaN(month) || isNaN(day)) {
return false;
}
const date = new Date(year, month - 1, day); // 月份从0开始
return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
}
const calculateAge = (birthDate) => {
// 添加空值检查
if (!birthDate) {
return '';
}
const birth = new Date(birthDate);
// 检查日期是否有效
if (isNaN(birth.getTime())) {
return '';
}
const today = new Date();
let age = today.getFullYear() - birth.getFullYear();
const monthDiff = today.getMonth() - birth.getMonth();
const dayDiff = today.getDate() - birth.getDate();
// 如果生日的月份还没到,或者刚到生日月份但当天还没过,则年龄减 1
if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
age--;
}
return age;
};
function getFormCompletionPercent(form) {
let total = Object.keys(form).length;
let filled = 0;
for (const key in form) {
const value = form[key];
if (value !== '' && value !== null && value !== undefined) {
if (typeof value === 'number') {
filled += 1;
} else if (typeof value === 'string' && value.trim() !== '') {
filled += 1;
}
}
}
if (total === 0) return '0%';
const percent = (filled / total) * 100;
return percent.toFixed(0) + '%'; // 取整,不要小数点
}
// 主函数
function getDatePickerIndexes(dateStr) {
// 添加空值检查如果dateStr为空或null返回默认值当前日期
if (!dateStr || typeof dateStr !== 'string' || dateStr.trim() === '') {
const today = new Date();
const year = today.getFullYear().toString();
const month = (today.getMonth() + 1).toString().padStart(2, '0');
const day = today.getDate().toString().padStart(2, '0');
dateStr = `${year}-${month}-${day}`;
}
const dateParts = dateStr.split('-');
if (dateParts.length !== 3) {
// 如果分割后不是3部分使用当前日期作为默认值
const today = new Date();
const year = today.getFullYear().toString();
const month = (today.getMonth() + 1).toString().padStart(2, '0');
const day = today.getDate().toString().padStart(2, '0');
dateStr = `${year}-${month}-${day}`;
dateParts = dateStr.split('-');
}
const [year, month, day] = dateParts;
const [years, months, days] = generateDatePickerArrays();
const yearIndex = years.indexOf(year) >= 0 ? years.indexOf(year) : 0;
const monthIndex = months.indexOf(month) >= 0 ? months.indexOf(month) : 0;
const dayIndex = days.indexOf(day) >= 0 ? days.indexOf(day) : 0;
return [yearIndex, monthIndex, dayIndex];
}
</script>
<style lang="stylus" scoped>
.btn{
margin-top: -30rpx
}
.content{
padding: 28rpx;
display: flex;
flex-direction: column;
justify-content: flex-start
height: calc(100% - 120rpx)
}
.content-input
margin-bottom: 52rpx
.input-titile
font-weight: 400;
font-size: 28rpx;
color: #6A6A6A;
.input-con
font-weight: 400;
font-size: 32rpx;
color: #333333;
line-height: 80rpx;
height: 80rpx;
border-bottom: 2rpx solid #EBEBEB
position: relative;
.triangle::before
position: absolute;
right: 20rpx;
top: calc(50% - 2rpx);
content: '';
width: 4rpx;
height: 18rpx;
border-radius: 2rpx
background: #697279;
transform: translate(0, -50%) rotate(-45deg) ;
.triangle::after
position: absolute;
right: 20rpx;
top: 50%;
content: '';
width: 4rpx;
height: 18rpx;
border-radius: 2rpx
background: #697279;
transform: rotate(45deg)
.content-sex
height: 110rpx;
display: flex
justify-content: space-between;
align-items: flex-start;
border-bottom: 2rpx solid #EBEBEB
margin-bottom: 52rpx
.sex-titile
line-height: 80rpx;
.sext-ri
display: flex
align-items: center;
.sext-box
height: 76rpx;
width: 152rpx;
text-align: center;
line-height: 80rpx;
border-radius: 12rpx 12rpx 12rpx 12rpx
border: 2rpx solid #E8EAEE;
margin-left: 28rpx
font-weight: 400;
font-size: 28rpx;
.sext-boxactive
color: #256BFA
background: rgba(37,107,250,0.1);
border: 2rpx solid #256BFA;
.next-btn
width: 100%;
height: 90rpx;
background: #256BFA;
border-radius: 12rpx 12rpx 12rpx 12rpx;
font-weight: 500;
font-size: 32rpx;
color: #FFFFFF;
text-align: center;
line-height: 90rpx
</style>