<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { recommendJob } from '@/apiRc/jobRecommend.js';
import { appUserInfo } from '@/apiRc/user/user.js';

const props = defineProps({
    currentJobId: {
        type: [Number, String],
        default: null
    },
    currentJobName: {
        type: String,
        default: ''
    }
});

const emit = defineEmits(['job-card-click', 'skills-updated']);

// 数据状态
const skillTags = ref([]);
const recommendedJobs = ref([]);
const isLoadingSkillTags = ref(false);
const isLoadingRecommend = ref(false);

// 计算属性
const currentJobDisplay = computed(() => props.currentJobName || '市场专员');

// 从 appSkillsList 中提取技能名称
function extractSkillsFromAppSkillsList(appSkillsList = []) {
    return (Array.isArray(appSkillsList) ? appSkillsList : [])
        .map(item => item?.name || item?.nameStr || '')
        .filter(name => !!name && name.trim().length > 0);
}

// 从技能列表中提取技能名称用于显示（用于推荐职位数据）
function extractSkillNames(skillList = []) {
    return (Array.isArray(skillList) ? skillList : [])
        .map(item => item?.skillName || '')
        .filter(name => !!name && name.trim().length > 0);
}

// 获取当前职位的技能标签
async function fetchCurrentJobSkills() {
    isLoadingSkillTags.value = true;
    try {
        // 优先从 appUserInfo 接口获取技能标签
        const response = await appUserInfo();
        const userInfo = response?.data || {};

        // 从 appSkillsList 中提取技能名称
        const appSkillsList = Array.isArray(userInfo?.appSkillsList) ? userInfo.appSkillsList : [];
        const apiSkills = extractSkillsFromAppSkillsList(appSkillsList);

        // 如果接口返回了技能数据，使用接口数据
        if (apiSkills.length > 0) {
            skillTags.value = apiSkills;
        } else {
            // 如果接口没有返回技能数据，从缓存中读取
            const cachedUserInfo = uni.getStorageSync('userInfo') || {};
            const cachedAppSkills = Array.isArray(cachedUserInfo?.appSkillsList) ? cachedUserInfo.appSkillsList : [];
            const cachedSkills = extractSkillsFromAppSkillsList(cachedAppSkills);

            if (cachedSkills.length > 0) {
                skillTags.value = cachedSkills;
            } else {
                skillTags.value = [];
            }
        }

        // 通知父组件技能数据已更新
        emit('skills-updated', {
            currentJobSkills: skillTags.value,
            recommendedJobs: recommendedJobs.value
        });
    } catch (error) {
        // appUserInfo 接口调用失败时，从缓存中读取
        const cachedUserInfo = uni.getStorageSync('userInfo') || {};
        const cachedAppSkills = Array.isArray(cachedUserInfo?.appSkillsList) ? cachedUserInfo.appSkillsList : [];
        const cachedSkills = extractSkillsFromAppSkillsList(cachedAppSkills);

        if (cachedSkills.length > 0) {
            skillTags.value = cachedSkills;
        } else {
            skillTags.value = [];
        }

        emit('skills-updated', {
            currentJobSkills: skillTags.value,
            recommendedJobs: recommendedJobs.value
        });
    } finally {
        isLoadingSkillTags.value = false;
    }
}

// 获取推荐职位列表
async function fetchRecommendedJobs() {
    isLoadingRecommend.value = true;
    try {
        const response = await recommendJob({
            jobName: props.currentJobName
        });

        const list = Array.isArray(response?.data) ? response.data : [];

        recommendedJobs.value = list.map((item, index) => {
            const skillList = Array.isArray(item?.skillList) ? item.skillList : [];
            const skillNames = extractSkillNames(skillList);

            return {
                id: item?.jobId ?? index,
                jobId: item?.jobId ?? null,
                title: item?.jobName || `推荐职位${index + 1}`,
                jobName: item?.jobName || '',
                skills: skillNames,
                rawSkills: skillList
            };
        });

        // 通知父组件推荐职位数据已更新
        emit('skills-updated', {
            currentJobSkills: skillTags.value,
            recommendedJobs: recommendedJobs.value
        });
    } catch (error) {
        recommendedJobs.value = [];
        emit('skills-updated', {
            currentJobSkills: skillTags.value,
            recommendedJobs: []
        });
    } finally {
        isLoadingRecommend.value = false;
    }
}

// 组件挂载时检查并调用
onMounted(() => {
    setTimeout(() => {
        if (props.currentJobName) {
            fetchCurrentJobSkills();
            fetchRecommendedJobs();
        }
    }, 100);
});

// 监听 props 变化，自动获取推荐职位和技能标签
watch(
    () => [props.currentJobId, props.currentJobName],
    () => {
        if (props.currentJobName) {
            fetchCurrentJobSkills();
            fetchRecommendedJobs();
        }
    },
    { immediate: true }
);

// 事件处理
function handleJobCardClick(job) {
    emit('job-card-click', job);
}
</script>

<template>
    <div class="career-recommend">
        <!-- 当前职位信息卡片 -->
        <div class="info-card">
            <div class="card-title">当前职位信息</div>
            <div class="card-content">
                <text class="label">当前职位</text>
                <text class="value">{{ currentJobDisplay }}</text>
            </div>
        </div>

        <!-- 我的技能标签卡片 -->
        <div class="info-card">
            <div class="card-title">我的技能标签</div>
            <div class="skill-tags">
                <div
                    class="skill-tag"
                    v-for="(skill, index) in skillTags"
                    :key="index"
                >
                    {{ skill }}
                </div>
                <text v-if="!skillTags.length && !isLoadingSkillTags" class="empty-text">暂无技能数据</text>
                <text v-if="isLoadingSkillTags" class="empty-text">加载中...</text>
            </div>
        </div>

        <!-- 相似推荐职位 -->
        <div class="section-title">
            相似推荐职位
        </div>
        <div v-if="!isLoadingRecommend && recommendedJobs.length === 0" class="empty-text">暂无推荐职位</div>
        <div
            class="job-item-card"
            v-for="(job, index) in recommendedJobs"
            :key="index"
            @click="handleJobCardClick(job)"
        >
            <div class="job-header">
                <text class="job-title">{{ job.title }}</text>
            </div>
            <div class="job-skills">
                <div
                    class="job-skill-tag"
                    v-for="(skill, skillIndex) in job.skills"
                    :key="skillIndex"
                >
                    {{ skill }}
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.career-recommend {
    padding: 10rpx 28rpx 20rpx;
}

.info-card {
    background-color: #FFFFFF;
    border-radius: 16rpx;
    padding: 28rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.card-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #000000;
    margin-bottom: 24rpx;
}

.card-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .label {
        font-size: 24rpx;
        line-height: 34rpx;
        color: rgba(154, 154, 154, 1);
        text-align: left;
        font-family: 'PingFangSC-Bold', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif;
        font-weight: 600;
    }

    .value {
        font-size: 32rpx;
        line-height: 46rpx;
        color: rgb(16, 16, 16);
        font-weight: 600;
        text-align: left;
        font-family: 'PingFangSC-Bold', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif;
    }
}

.skill-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
}

.skill-tag {
    background-color: #EAEFFE;
    color: rgba(44, 101, 247, 1);
    padding: 8rpx 20rpx;
    border-radius: 0;
    font-size: 24rpx;
    white-space: nowrap;
}

.section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #000000;
    margin-bottom: 20rpx;
    margin-top: 8rpx;
}

.job-item-card {
    background-color: #FFFFFF;
    border-radius: 16rpx;
    padding: 28rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
    border-left: 6rpx solid #409EFF;
    position: relative;
    cursor: pointer;
}

.job-header {
    margin-bottom: 16rpx;
}

.job-title {
    font-size: 32rpx;
    font-weight: 600;
    color: rgb(16, 16, 16);
    text-align: left;
    font-family: 'PingFangSC-Bold', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif;
    line-height: 46rpx;
    width: 100%;
}

.job-skills {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
}

.job-skill-tag {
    width: 130rpx;
    height: 36rpx;
    line-height: 34rpx;
    background-color: rgba(49, 100, 239, 0.1);
    color: rgba(44, 101, 247, 1);
    font-size: 24rpx;
    text-align: center;
    font-family: 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif;
    border-radius: 8rpx;
    white-space: nowrap;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
}

.recommend-count {
    margin-left: 12rpx;
    font-size: 22rpx;
    color: #666666;
    font-weight: 400;
}

.empty-text {
    font-size: 24rpx;
    color: #999999;
    line-height: 34rpx;
}

button::after {
    border: none;
}
</style>
