<template>
    <NavBar :showIcon="true" backgroundBox="#ffffff" :showTitle="true" title="我的简历"></NavBar>
    <div class="resume-page">
        <!-- 个人信息 -->
        <view  class="user-info flex-between" @click="navigateTo('/pages/user/resume/essentialInformation/index')">
            <view>
                <view class="name"
                    >{{ resumeData.realName || "未实名" }}
                    <img src="@/static/image/icon/edit.png" />
                </view>
                <view class="other"
                    >{{ resumeData.workExperienceYear }}年经验·{{ resumeData.age }}岁·{{ resumeData.educationLevel }}</view
                >
            </view>
            <image v-if="resumeData.avatarPath" class="avatar" :src="evn.APP_IMAGE_BASE_API + resumeData.avatarPath" mode="" />
            <image v-else class="avatar" src="@/static/image/user/default-avatar.png" mode="" />
        </view>
        <!-- 个人信息 -->
        <view class="basics" v-if="userInfoActive">
            <text class="gradient-title">个人信息</text>
            <view class="basics-top">
                <view class="item" >
                    <img v-show="resumeData.sex===1" src="@/static/image/user/man.png" alt="">
                    <img v-show="resumeData.sex===2" src="@/static/image/user/woman.png" alt="">
                    <text>{{resumeData.sex===1?'男':'女'}}</text>
                </view>
				<view class="item">
                    <img src="@/static/image/user/birth.png" alt="">
                    <text>{{resumeData.birthday}}</text>
                </view> 
				<view class="item">
                    <img src="@/static/image/user/bag.png" alt="">
                    <text>{{resumeData.workExperienceYear}}年</text>
                </view> 
            </view>
            <view class="information">
                <text class="label">身份</text>
                <text class="value">{{resumeData.identityTypes}}</text>
            </view>
            <view class="information">
                <text class="label">专业</text>
                <text class="value">{{resumeData.major || '无'}}</text>
            </view>
            <view class="information">
                <text class="label">专业技术职称</text>
                <text class="value">{{resumeData.positionalTitle || '无'}}</text>
            </view>
            <view class="information">
                <text class="label">职业资格/技能等级证书</text>
                <text class="value">{{resumeData.professionalCertificates ||'无'}}</text>
            </view>
            <view class="information">
                <text class="label">特种作业证</text>
                <text class="value">{{resumeData.specialCertificates || '无'}}</text>
            </view>
            <view class="information">
                <text class="label">户籍地</text>
                <text class="value">{{resumeData.residenceAddress}}</text>
            </view>
            <view class="information">
                <text class="label">常住地</text>
                <text class="value">{{resumeData.birthAddress}}</text>
            </view>
        </view>
        <!-- 求职状态 -->
        <view class="state">
            <text class="gradient-title">求职状态</text>
            <wd-picker
                :columns="jobStatusColumns"
                label-key="text"
                value-key="code"
                @confirm="changeJobStatus"
                v-model="value"
                use-default-slot
            >
                <view class="flex-between">
                    <text>{{ resumeData.jobStatusText }}</text>
                    <view class="arrow"></view>
                </view>
            </wd-picker>
        </view>
        <!-- 求职意向 -->
        <view
            class="intention"
            @click="toPage(1)"
        >
            <view class="flex-between">
                <text class="gradient-title">求职意向</text>
                <view class="arrow"></view>
            </view>
            <view class="postion">{{ resumeData.positionNames }}</view>
            <view class="salary-postion">
                <view class="salary"
                    >{{ resumeData.minSalary }}{{ resumeData.minSalary ? "-" : "" }}{{ resumeData.maxSalary
                    }}{{ resumeData.districtCode ? " | " : "" }} {{ resumeData.districtCode }}</view
                >
                <view>
                    <text class="text" style="margin-right: 30rpx">{{ resumeData.workModeText }}</text>
                    <text class="text">{{ resumeData.needAccommodationText }}</text> 
                </view>
            </view>
        </view>
        <!-- 教育经历 -->
        <view class="experience">
            <view class="flex-between">
                <text class="gradient-title">教育经历</text>
                <wd-icon
                    name="add"
                    size="24rpx"
                    @click="toPage(3)"
                ></wd-icon>
            </view>
            <view class="list">
                <view
                    class="item"
                    v-for="(item, index) in resumeData.educationExperience"
                    :key="index"
                    @tap="
                        navigateTo(
                            `/pages/user/resume/educationExperience/index?data=${encodeURIComponent(
                                JSON.stringify(resumeData.educationExperience)
                            )}&index=${index}`
                        )
                    "
                >
                    <view class="name-date flex-between">
                        <text class="name">·{{ item.schoolName }}</text>
                        <text class="date">{{ item.startDate }}~{{ item.endDate }}</text>
                    </view>
                    <view class="flex-between">
                        <view class="postion">·{{ item.major }}</view>
                        <wd-icon name="error-fill" size="36rpx" style="color: red" @tap.stop="deleteItemTwo(index)"></wd-icon>
                    </view>
                    <!-- <view class="content">
                ·内容：预计，建筑工程将在今年底竣工。宿舍会在明年8月启用，让多达600名学生入住。
                国大学生事务处处长何汉杰说，国大的宿舍都各有特色，并解释为何要兴建以体育为主题的宿舍。
            </view> -->
                </view>
            </view>
        </view>
        <!-- 工作经历 -->
        <view class="experience">
            <view class="flex-between">
                <text class="gradient-title">工作经历</text>
                <wd-icon
                    name="add"
                    size="24rpx"
                    @click="toPage(2)"
                ></wd-icon>
            </view>
            <view class="list">
                <view
                    class="item"
                    v-for="(item, index) in resumeData.workExperience"
                    :key="index"
                    @tap="
                        navigateTo(
                            `/pages/user/resume/workExperience/index?data=${encodeURIComponent(
                                JSON.stringify(resumeData.workExperience)
                            )}&index=${index}`
                        )
                    "
                >
                    <view class="name-date flex-between">
                        <text class="name">·{{ item.companyName }}</text>
                        <text class="date">{{ item.startDate }} ~ {{ item.endDate }}</text>
                    </view>
                    <view class="flex-between">
                        <view>
                            <view class="postion">·{{ item.position }}</view>
                            <textarea auto-height class="content" :value="item.content"/>
                        </view>
                        <wd-icon name="error-fill" size="36rpx" style="color: red" @tap.stop="deleteItem(index)"></wd-icon>
                    </view>
                </view>
            </view>
        </view>
        <!-- 个人优势 -->
        <view class="advantage" @click="toPage(0)">
            <view class="flex-between">
                <text class="gradient-title">个人优势</text>
                <view class="arrow"></view>
            </view>
            <view class="content">
                {{ resumeData.personalAdvantage }}
            </view>
        </view>
        <wd-toast />
    </div>
</template>

<script setup>
import { reactive } from "vue";
import {
    getUserResumeApi,
    getLoginUserApi,
    saveJobStatusApi,
    saveWorkExperienceApi,
    saveEducationExperienceApi,
    getCityNameByCodeApi
} from "@/api/user";
import { getEnumText,getEnumText2, getEumData } from "@/utils/utils.js";
import { useToast } from "wot-design-uni";
import { navigateTo } from "@/utils/utils.js";
import evn from "@/utils/config.js";
const toast = useToast();
const userInfoActive = ref(null)
const resumeData = reactive({
    preferredCityName: "",
    personalAdvantage: "",
    preferredPosition: "",
    maxSalary: "",
    minSalary: "",
    workExperience: [],
    educationExperience: [],
    workExperience: "",
    workExperienceYear: "",
    jobStatusText: "",
    education: "",
    realName: "",
    username: "",
    avatarPath: "",
    birthDate: "",
    jobStatus: "",
    age: "",
    needAccommodationText:''
});
function calculateAge(birthday) {
    var birthdayDate = new Date(birthday); // 将时间戳转换为日期对象
    var today = new Date(); // 获取当前日期
    var age = today.getFullYear() - birthdayDate.getFullYear(); // 计算年份差
    // 检查生日是否已经过去
    var m = today.getMonth() - birthdayDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthdayDate.getDate())) {
        age--;
    }
    return age;
}
// 时间戳转为年月日
function formatTimestamp(timestampInMilliseconds) {
    // 创建日期对象
    var date = new Date(timestampInMilliseconds);
    // 获取年月日
    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以加1，并确保两位数
    var day = ("0" + date.getDate()).slice(-2); // 确保两位数
    return `${year}.${month}.${day}`;
}
// 数据回显
const getUserResume = () => {
    getUserResumeApi().then(async res => {
        // console.log(res);
        const {
            personalAdvantages,
            positionNames,
            positionIds,
            positionParentIds,
            maxSalary,
            minSalary,
            workExperience,
            educationExperience,
            currentStatus,
            districtCode,
            provinceCode,
            cityCode,
            needAccommodation,
            preferredCityName,
            workMode
        } = res.data;
        resumeData.jobStatusText = await getEnumText("EnumUserJobStatus", currentStatus);
        resumeData.preferredCityName = preferredCityName;
        resumeData.citySelectedItems = [provinceCode,cityCode,districtCode];
        resumeData.personalAdvantage = personalAdvantages; // 求职状态回
        resumeData.positionNames = positionNames;
        resumeData.positionIds = positionIds.split(",");
        resumeData.positionParentIds = positionParentIds.split(",");
        resumeData.districtCodeId = districtCode;
        getCityNameByCodeApi(districtCode).then(res => {
            resumeData.districtCode = res.data.cityName;
        })
        resumeData.needAccommodationText = await getEnumText("EnumAccommodation", needAccommodation);
        resumeData.needAccommodation = needAccommodation
        resumeData.workModeText = await getEnumText("EnumWorkMode", workMode);
        resumeData.workMode = workMode
        resumeData.maxSalary = maxSalary && maxSalary / 1000 + "k";
        resumeData.minSalary = minSalary && minSalary / 1000 + "k";
        resumeData.workExperience = JSON.parse(workExperience || "[]");
        resumeData.educationExperience = JSON.parse(educationExperience || "[]");
    });
    // 获取用户基本信息
    getLoginUserApi().then(async res => {
        userInfoActive.value = res.data
        if (res.code === 200) {
            const {residenceAddress,birthAddress,specialCertificates,positionalTitle,professionalCertificates,major,identityTypes,sex,workAge, education, name, username, avatarPath, birthday, jobStatus } = res.data;
            /*       this.setData({
                realName,
                workExperienceYear: workExperience,
                educationLevel: getEnumText("EnumEducation", educationLevel),
                jobStatusText: getEnumText("EnumUserJobStatus", jobStatus), // 求职状态回显
                username,
                avatarPath,
                age: calculateAge(birthDate)
            }); */
            resumeData.realName = name;
            resumeData.workExperienceYear = workAge;
            resumeData.educationLevel = await getEnumText("EnumEducation", education);
            resumeData.username = username;
            resumeData.avatarPath = avatarPath;
            resumeData.age = calculateAge(birthday);
            resumeData.sex = sex;
            resumeData.identityTypes = await getEnumText2("EnumIdentityType", identityTypes.split(","));;
            resumeData.birthday = formatTimestamp(birthday);
            resumeData.major = major;
            resumeData.positionalTitle = positionalTitle;
            resumeData.professionalCertificates = professionalCertificates;
            resumeData.specialCertificates = specialCertificates;
            resumeData.residenceAddress = residenceAddress;
            resumeData.birthAddress = birthAddress;
            // getCityNameByCodeApi(residenceCodes.split(",")[2]).then(res => {
            //     resumeData.residenceCodes = res.data.provinceName+res.data.cityName+res.data.districtName;
            // })
            // getCityNameByCodeApi(birthCodes.split(",")[2]).then(res => {
            //     resumeData.birthCodes = res.data.provinceName+res.data.cityName+res.data.districtName;
            // })
        }
    });
};
onShow(() => {
    getUserResume();
    getOpstion();
});
// 获取求职状态数据
const value = ref();
const jobStatusColumns = ref([]);
const getOpstion = async () => {
    jobStatusColumns.value = await getEumData("EnumUserJobStatus");
    console.log(jobStatusColumns.value);
};

const toPage = (index) => {
    if (!userInfoActive.value) {
        uni.showToast({
            title: "请先完善个人基本信息",
            icon: "none"
        });
        return
    }
    switch (index) {
        case 0:
            navigateTo(`/pages/user/resume/introduce/index?data=${resumeData.personalAdvantage}`)
            break;
        case 1:
            navigateTo(`/pages/user/resume/jobIntention/index?data=${encodeURIComponent(JSON.stringify(resumeData))}`)
            break;
        case 2:
            navigateTo(`/pages/user/resume/workExperience/index?data=${encodeURIComponent(
                                JSON.stringify(resumeData.workExperience)
                            )}`
                        )
            break;
        case 3:
            navigateTo(`/pages/user/resume/educationExperience/index?data=${encodeURIComponent(
                                JSON.stringify(resumeData.educationExperience)
                            )}`
                        )
            break;    
    }
}

const changeJobStatus = async e => {
    if (!userInfoActive.value) {
        uni.showToast({
            title: "请先完善个人基本信息",
            icon: "none"
        });
        return
    }
    const { code, message } = await saveJobStatusApi({ jobStatus: e.value });
    if (code == 200) {
        resumeData.jobStatusText = e.selectedItems.text;
        // uni.showToast({
        //     message: "保存成功",
        //     icon: "none"
        // });
    }
};

const deleteItem = index => {
    uni.showModal({
        title: "删除",
        content: "是否删除该条记录？",
        success: async res => {
            if (res.confirm) {
                console.log("resumeData.workExperience", resumeData.workExperience);
                resumeData.workExperience.splice(index, 1);
                saveWorkExperienceApi(JSON.stringify(resumeData.workExperience)).then(res => {
                    if (res.code == 200) {
                        uni.showToast({
                            title: "删除成功",
                            icon: "success"
                        });
                    }
                });
            }
        }
    });
};

const deleteItemTwo = index => {
    uni.showModal({
        title: "删除",
        content: "是否删除该条记录？",
        success: async res => {
            if (res.confirm) {
                console.log("resumeData.workExperience", resumeData.workExperience);
                resumeData.educationExperience.splice(index, 1);
                saveEducationExperienceApi(JSON.stringify(resumeData.educationExperience)).then(res => {
                    if (res.code == 200) {
                        uni.showToast({
                            title: "删除成功",
                            icon: "success"
                        });
                    }
                });
            }
        }
    });
};
</script>

<style lang="scss" scoped>
.resume-page {
    padding-top: 50rpx;
}
.user-info {
    padding-bottom: 30rpx;
    margin: 0 32rpx;
    border-bottom: 2rpx solid #f3f4f8;
    .name {
        margin-bottom: 16rpx;
        font-size: 36rpx;
        font-weight: 600;
        line-height: 36rpx;
        color: #1b2026;
        img {
            width: 28rpx;
            height: 28rpx;
        }
    }
    .other {
        font-size: 24rpx;
        font-weight: normal;
        line-height: 36rpx;
        color: #77818f;
    }
    .avatar {
        width: 88rpx;
        height: 88rpx;
        border-radius: 50%;
    }
}
.basics {
    padding: 0 32rpx 32rpx;
    margin-top: 32rpx;
    border-bottom: 16rpx solid #f3f4f8;
    .basics-top{
       display: flex; 
       align-items: center;
       .item{
        display: flex;
        align-items: center;
				margin-right: 96rpx;
					img{
						width: 28rpx;
						height: 28rpx;
						margin-right: 16rpx;
					}
					text{
						font-size: 24rpx;
						color: #1B2026;
					}
       }
    }
		.information{
			.label{
				font-size: 24rpx;
				color: #77818F;
				margin-right: 16rpx;
			}
			.value{
				font-size: 24rpx;
				color: #1B2026;
			}
		}
    view {
        margin-top: 16rpx;
        font-size: 24rpx;
        line-height: 36rpx;
        color: #1b2026;
    }
    .arrow {
        border-color: #1b2026;
    }
}
.state {
    padding: 0 32rpx 32rpx;
    margin-top: 32rpx;
    border-bottom: 16rpx solid #f3f4f8;
    view {
        margin-top: 16rpx;
        font-size: 24rpx;
        line-height: 36rpx;
        color: #1b2026;
    }
    .arrow {
        border-color: #1b2026;
    }
}
.advantage {
    padding: 32rpx;
    border-bottom: 16rpx solid #f3f4f8;
    .content {
        margin-top: 16rpx;
        font-size: 24rpx;
        line-height: 36rpx;
        color: #1b2026;
    }
}
.intention {
    padding: 32rpx;
    border-bottom: 16rpx solid #f3f4f8;
    view {
        margin-top: 16rpx;
        font-size: 24rpx;
        line-height: 36rpx;
        color: #1b2026;
    }
    .salary-postion{
        display: flex;
        align-items: center;
        justify-content: space-between;
        .text{
            margin-top: 16rpx;
        }
    }
}
.experience {
    padding: 32rpx;
    border-bottom: 16rpx solid #f3f4f8;
    .list {
        .item {
            padding: 32rpx 0;
            &:not(:last-child) {
                border-bottom: 2rpx solid #f3f4f8;
            }
            .name-date {
                line-height: 36rpx;
                color: #1b2026;
                .name {
                    font-size: 28rpx;
                    font-weight: 600;
                }
                .date {
                    font-size: 24rpx;
                }
            }
            .postion {
                margin-top: 16rpx;
                font-size: 24rpx;
                line-height: 36rpx;
                color: #1b2026;
            }
            .content {
                font-size: 24rpx;
                line-height: 36rpx;
                color: #77818f;
            }
        }
    }
}
</style>
