<template>
  <view class="resume-container">
    <view class="loading-box" v-if="isLoading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    <scroll-view class="resume-scroll" scroll-y v-else>
      <!-- 个人基础卡片 -->
      <view class="section-card header-card">
        <view class="header-main">
          <view class="header-info">
            <view class="name-row">
              <text class="name">{{ studentData.name || '加载中...' }}</text>
              <text class="status-badge" v-if="jobTypeLabel && availabilityLabel">{{ jobTypeLabel }} · {{ availabilityLabel }}</text>
            </view>
            <view class="summary" v-if="workYears || studentData.education || studentData.schoolName">
              <text v-if="workYears">{{ workYears }}年经验</text>
              <text v-if="workYears && educationLabel"> / </text>
              <text v-if="educationLabel">{{ educationLabel }}</text>
              <text v-if="(workYears || educationLabel) && studentData.schoolName"> / </text>
              <text v-if="studentData.schoolName">{{ studentData.schoolName }}</text>
            </view>
          </view>
          <image class="avatar" :src="studentData.avatarUrl || '/static/images/hr_avatar.svg'" mode="aspectFill"></image>
        </view>
        <view class="contact-grid">
          <view class="contact-item" v-if="studentData.mobile">
            <image src="/static/icons/resume-phone.svg" class="mini-icon" mode="aspectFit"></image>
            <text>{{ maskPhone(studentData.mobile) }}</text>
          </view>
          <view class="contact-item" v-if="studentData.email">
            <image src="/static/icons/resume-mail.svg" class="mini-icon" mode="aspectFit"></image>
            <text>{{ studentData.email }}</text>
          </view>
        </view>
      </view>

      <!-- 个人信息 -->
      <view class="section-card" v-if="hasPersonalInfo">
        <view class="section-title">个人信息</view>
        <view class="info-list">
          <view class="info-row" v-if="studentData.gender">
            <text class="label">性别</text>
            <text class="value">{{ genderLabel }}</text>
          </view>
          <view class="info-row" v-if="birthDate">
            <text class="label">出生日期</text>
            <text class="value">{{ birthDate }}</text>
          </view>
          <view class="info-row" v-if="educationLabel">
            <text class="label">最高学历</text>
            <text class="value">{{ educationLabel }}</text>
          </view>
          <view class="info-row" v-if="studentData.schoolName">
            <text class="label">毕业院校</text>
            <text class="value">{{ studentData.schoolName }}</text>
          </view>
        </view>
      </view>

      <!-- 求职意向 -->
      <view class="section-card" v-if="jobIntentions.length > 0">
        <view class="section-title">求职意向</view>
        <view class="intent-box">
          <view class="tag-group">
            <text class="intent-tag" v-for="(intent, idx) in jobIntentions" :key="idx">{{ intent }}</text>
          </view>
        </view>
      </view>

      <!-- 工作经历 -->
      <view class="section-card" v-if="studentData.experienceList && studentData.experienceList.length > 0">
        <view class="section-title">工作经历</view>
        <view class="timeline">
          <view class="timeline-item" v-for="(exp, idx) in studentData.experienceList" :key="exp.id || idx">
            <view class="dot"></view>
            <view class="time-range">{{ formatTimeRange(exp.startTime, exp.endTime) }}</view>
            <view class="comp-name">{{ exp.isHidden === 1 ? '***（已屏蔽）' : exp.company }}</view>
            <view class="pos-name">{{ exp.jobTitle }}<text v-if="exp.isInternship === 1" style="font-size: 24rpx; margin-left: 8rpx;">(实习)</text></view>
            <view class="job-desc" v-if="exp.workContent">{{ exp.workContent }}</view>
          </view>
        </view>
      </view>

      <!-- 项目经历 -->
      <view class="section-card" v-if="studentData.projectList && studentData.projectList.length > 0">
        <view class="section-title">项目经历</view>
        <view class="project-item" v-for="(proj, idx) in studentData.projectList" :key="proj.id || idx">
          <view class="p-header">
            <text class="p-name">{{ proj.projectName }}</text>
            <text class="p-time">{{ formatTimeRange(proj.startTime, proj.endTime) }}</text>
          </view>
          <view class="p-role" v-if="proj.role">{{ proj.role }}</view>
          <view class="p-content" v-if="proj.description">{{ proj.description }}</view>
          <view class="p-content" v-if="proj.achievement" style="margin-top: 12rpx;">成果：{{ proj.achievement }}</view>
        </view>
      </view>

      <!-- 教育经历 -->
      <view class="section-card" v-if="studentData.educationList && studentData.educationList.length > 0">
        <view class="section-title">教育经历</view>
        <view class="edu-item" v-for="(edu, idx) in studentData.educationList" :key="edu.id || idx">
          <view class="edu-header">
            <text class="school">{{ edu.school }}</text>
            <text class="e-time">{{ formatTimeRange(edu.startTime, edu.endTime) }}</text>
          </view>
          <view class="major">
            <text v-if="edu.major">{{ edu.major }}</text>
            <text v-if="edu.major && (edu.education || edu.educationType)"> · </text>
            <text v-if="edu.education">{{ getEducationLabel(edu.education) }}</text>
            <text v-if="edu.education && edu.educationType"> · </text>
            <text v-if="edu.educationType">{{ edu.educationType }}</text>
          </view>
          <view class="p-content" v-if="edu.campusExperience" style="margin-top: 12rpx; font-size: 26rpx; color: #666;">{{ edu.campusExperience }}</view>
        </view>
      </view>

      <!-- 底部撑开 -->
      <view class="bottom-spacer"></view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="fixed-footer">
      <button class="edit-btn" @click="handleEditResume">编辑简历</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getStudent } from '../../api/student.js';

const studentData = ref({
    name: '',
    mobile: '',
    email: '',
    gender: '',
    genderLabel: '',
    idCardNumber: '',
    avatarUrl: '',
    schoolName: '',
    education: '',
    educationLabel: '',
    availabilityLabel: '',
    jobType: '',
    jobTypeLabel: '',
    availability: '',
    jobIntention: '',
    educationList: [],
    experienceList: [],
    projectList: []
});

const isLoading = ref(true);

// 学历字典映射
const educationMap = {
    '1': '初中及以下',
    '2': '高中/中专',
    '3': '大专',
    '4': '本科',
    '5': '硕士',
    '6': '博士',
};

// 求职类型映射
const jobTypeMap = {
    '1': '全职',
    '2': '实习',
    '3': '兼职',
};

// 性别映射
const genderMap = {
    '0': '男',
    '1': '女',
    '2': '未知'
};

const normalizeGenderValue = (value) => {
    if (value === undefined || value === null || value === '') return '';
    const gender = String(value).trim().toUpperCase();
    if (gender === 'M') return '0';
    if (gender === 'F') return '1';
    return gender;
};

// 计算属性
const educationLabel = computed(() => {
    if (studentData.value.educationList && studentData.value.educationList.length > 0) {
        const educationLevel = { '初中及以下': 1, '高中': 2, '中专': 2, '大专': 3, '本科': 4, '硕士': 5, '博士': 6 };
        let highestEdu = studentData.value.educationList[0];
        let maxLevel = educationLevel[highestEdu.education] || 0;
        for (const edu of studentData.value.educationList) {
            const level = educationLevel[edu.education] || 0;
            if (level > maxLevel) { maxLevel = level; highestEdu = edu; }
        }
        const label = highestEdu.education || '';
        return label + (highestEdu.educationType ? ' · ' + highestEdu.educationType : '');
    }
    if (studentData.value.educationLabel) return studentData.value.educationLabel;
    const val = studentData.value.education;
    if (!val || val === '0' || val === 0) return '';
    return educationMap[val] || (/^\d+$/.test(String(val)) ? '' : val);
});

const jobTypeLabel = computed(() => {
    if (studentData.value.jobTypeLabel) return studentData.value.jobTypeLabel;
    const val = studentData.value.jobType;
    if (!val) return '';
    return jobTypeMap[val] || val;
});

const availabilityLabel = computed(() => {
    return studentData.value.availabilityLabel || studentData.value.availability || '';
});

const genderLabel = computed(() => {
    if (studentData.value.genderLabel) return studentData.value.genderLabel;
    const g = normalizeGenderValue(studentData.value.gender);
    if (!g) return '';
    return genderMap[g] || g;
});

const jobIntentions = computed(() => {
    if (!studentData.value.jobIntention) return [];
    // jobIntention 可能存的是字典值(如 "1,2")，需要转换
    const items = studentData.value.jobIntention.split(',').filter(item => item.trim());
    const intentionMap = { '1': '审计', '2': '咨询', '3': '税务', '4': '财务', '5': '评估' };
    return items.map(item => intentionMap[item.trim()] || item.trim());
});

const birthDate = computed(() => {
    if (!studentData.value.idCardNumber || studentData.value.idCardNumber.length < 14) return '';
    const year = studentData.value.idCardNumber.substring(6, 10);
    const month = studentData.value.idCardNumber.substring(10, 12);
    const day = studentData.value.idCardNumber.substring(12, 14);
    return `${year}-${month}-${day}`;
});

const workYears = computed(() => {
    if (!studentData.value.experienceList || studentData.value.experienceList.length === 0) return 0;
    
    let totalMonths = 0;
    studentData.value.experienceList.forEach(exp => {
        if (exp.startTime && exp.endTime) {
            const start = new Date(exp.startTime);
            const end = exp.endTime === '至今' ? new Date() : new Date(exp.endTime);
            const months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth());
            totalMonths += months;
        }
    });
    
    return Math.floor(totalMonths / 12);
});

const hasPersonalInfo = computed(() => {
    return studentData.value.gender || birthDate.value || educationLabel.value || studentData.value.schoolName;
});

// 工具函数
const maskPhone = (phone) => {
    if (!phone || phone.length < 11) return phone;
    return phone.substring(0, 3) + '****' + phone.substring(7);
};

const formatTimeRange = (start, end) => {
    if (!start) return '';
    const formatDate = (dateStr) => {
        if (!dateStr) return '';
        if (dateStr === '至今') return '至今';
        const date = new Date(dateStr);
        return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}`;
    };
    return `${formatDate(start)} - ${formatDate(end) || '至今'}`;
};

const getEducationLabel = (education) => {
    return educationMap[education] || education || '';
};

const handleEditResume = () => {
    uni.navigateTo({ url: '/pages/profile/profile?editMode=1' });
};

// 页面加载时获取数据
const fetchResumeData = async () => {
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo || !userInfo.studentId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => {
            uni.reLaunch({ url: '/pages/login/login' });
        }, 1500);
        return;
    }

    try {
        isLoading.value = true;
        const res = await getStudent(userInfo.studentId);
        
        if (res && res.data) {
            studentData.value = {
                ...studentData.value,
                ...res.data,
                educationList: res.data.educationList || [],
                experienceList: res.data.experienceList || [],
                projectList: res.data.projectList || []
            };
        } else {
            uni.showToast({ title: '获取简历数据失败', icon: 'none' });
        }
    } catch (err) {
        console.error('获取简历数据异常', err);
        uni.showToast({ title: '网络异常，请重试', icon: 'none' });
    } finally {
        isLoading.value = false;
        uni.hideLoading();
    }
};

onMounted(() => {
    fetchResumeData();
});

onShow(() => {
    fetchResumeData();
});
</script>

<style lang="scss" scoped>
.resume-container {
  min-height: 100vh;
  background-color: #F6F8FB;
}

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #1F6CFF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.resume-scroll {
  height: 100vh;
}

.section-card {
  margin: 24rpx 30rpx;
  background: #FFF;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.03);
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #1A1A1A;
    margin-bottom: 24rpx;
    padding-left: 16rpx;
    border-left: 6rpx solid #1F6CFF;
  }
}

.header-card {
  margin-top: 30rpx;
  .header-main {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 30rpx;
    .name { font-size: 48rpx; font-weight: bold; color: #1A1A1A; margin-right: 20rpx; }
    .status-badge { font-size: 20rpx; color: #1F6CFF; background: #E9F1FF; padding: 4rpx 12rpx; border-radius: 4rpx; }
    .summary { font-size: 26rpx; color: #666; margin-top: 12rpx; }
    .avatar { width: 120rpx; height: 120rpx; border-radius: 50%; background: #F0F0F0; }
  }
  .contact-grid {
    display: flex; gap: 40rpx;
    .contact-item {
      display: flex; align-items: center; font-size: 24rpx; color: #999;
      .mini-icon { width: 28rpx; height: 28rpx; margin-right: 8rpx; }
    }
  }
}

.info-list {
  .info-row {
    display: flex; justify-content: space-between; margin-bottom: 20rpx;
    &:last-child { margin-bottom: 0; }
    .label { font-size: 28rpx; color: #999; }
    .value { font-size: 28rpx; color: #333; font-weight: 500; }
  }
}

.intent-box {
  .tag-group {
    display: flex; gap: 16rpx; margin-bottom: 16rpx;
    .intent-tag { font-size: 26rpx; color: #1F6CFF; border: 1rpx solid #1F6CFF; padding: 4rpx 20rpx; border-radius: 6rpx; }
  }
  .intent-detail { font-size: 26rpx; color: #666; }
}

.timeline {
  .timeline-item {
    position: relative;
    padding-left: 40rpx;
    padding-bottom: 40rpx;
    border-left: 2rpx dashed #DDD;
    &:last-child { padding-bottom: 0; border-left: none; }
    .dot {
      position: absolute; left: -7rpx; top: 10rpx;
      width: 12rpx; height: 12rpx; background: #1F6CFF; border-radius: 50%;
    }
    .time-range { font-size: 24rpx; color: #999; margin-bottom: 12rpx; }
    .comp-name { font-size: 30rpx; font-weight: bold; color: #333; margin-bottom: 8rpx; }
    .pos-name { font-size: 28rpx; color: #1F6CFF; margin-bottom: 12rpx; }
    .job-desc { font-size: 26rpx; color: #666; line-height: 1.6; }
  }
}

.project-item, .edu-item {
  .p-header, .edu-header {
    display: flex; justify-content: space-between; align-items: center; margin-bottom: 12rpx;
    .p-name, .school { font-size: 30rpx; font-weight: bold; color: #333; }
    .p-time, .e-time { font-size: 24rpx; color: #999; }
  }
  .p-role, .major { font-size: 28rpx; color: #1F6CFF; margin-bottom: 12rpx; }
  .p-content { font-size: 26rpx; color: #666; line-height: 1.6; }
}

.bottom-spacer { height: 180rpx; }

.fixed-footer {
  position: fixed; left: 0; right: 0; bottom: 0;
  background: rgba(255,255,255,0.9);
  backdrop-filter: blur(10px);
  padding: 24rpx 40rpx calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 16rpx rgba(0,0,0,0.05);
  .edit-btn {
    height: 72rpx; line-height: 72rpx; background: #1F6CFF; color: #FFF;
    font-size: 28rpx; font-weight: bold; border-radius: 36rpx;
    &::after { border: none; }
  }
}
</style>
