<template>
  <view class="container">
    <!-- 状态栏与胶囊位占位：确保内容不下压至标题栏重合 -->
    <view class="nav-placeholder" :style="{ height: navFullHeight + 'px' }"></view>

    <!-- 顶部用户信息区 -->
    <view class="user-card-wrap">
      <view class="user-main">
        <view class="avatar-wrap">
          <image class="avatar" :src="studentInfo.avatarUrl || '/static/images/hr_avatar.svg'" mode="aspectFill"></image>
        </view>
        <view class="info-content">
          <view class="name-box">
            <text class="user-name">{{ studentInfo.name || '加载中...' }}</text>
            <image class="diamond-icon" src="/static/icons/diamond.svg" mode="aspectFit"></image>
            <view class="flex-spacer"></view>
            <view class="resume-link" @click="handleOnlineResume">
              <text>在线简历</text>
              <image class="link-arrow" src="/static/icons/chevron-right-blue.svg" mode="aspectFit"></image>
            </view>
          </view>
          <view class="badge-row">
            <text class="profile-tag" v-if="schoolNameLabel">{{ schoolNameLabel }}</text>
            <text class="profile-tag" v-if="educationLabel">{{ educationLabel }}</text>
            <text class="profile-tag" v-if="jobTypeLabel">{{ jobTypeLabel }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 磁贴功能区 -->
    <view class="feature-grid">
      <view class="grid-cell" @click="navigateTo('collection')">
        <view class="icon-wrap-premium">
          <image src="/static/my/fav_premium.svg" mode="aspectFit"></image>
        </view>
        <text class="cell-label">我的收藏</text>
      </view>
      <view class="grid-cell" @click="navigateTo('intention')">
        <view class="icon-wrap-premium">
          <image src="/static/my/intent_premium.svg" mode="aspectFit"></image>
        </view>
        <text class="cell-label">意向岗位</text>
      </view>
      <view class="grid-cell" @click="navigateTo('assessment')">
        <view class="icon-wrap-premium">
          <image src="/static/my/test_premium.svg" mode="aspectFit"></image>
        </view>
        <text class="cell-label">我的测评</text>
      </view>
      <view class="grid-cell" @click="navigateTo('order')">
        <view class="icon-wrap-premium">
          <image src="/static/my/order_premium.svg" mode="aspectFit"></image>
        </view>
        <text class="cell-label">我的订单</text>
      </view>
    </view>

    <!-- 服务列表区 -->
    <view class="service-panel">
      <view class="panel-header">
        <text class="panel-title">我的服务</text>
      </view>

      <!-- 附件简历区块 -->
      <view class="service-item resume-section">
        <view class="res-head">
          <text class="res-title">附件简历 ({{ resumeList.length }}/3)</text>
          <view class="upload-links">
            <text class="link-btn active" @click="uploadFromWechat">从微信聊天文件上传</text>
            <text class="link-btn" @click="uploadFromLocal">从手机本地上传</text>
          </view>
        </view>
        
        <!-- 动态简历列表 -->
        <view class="resume-list-container" v-if="resumeList.length > 0">
          <view class="file-card card-anim" v-for="(file, idx) in resumeList" :key="file.id">
            <view class="file-info-main">
              <view class="file-icon-box">
                <image src="/static/icons/pdf.svg" mode="aspectFit" class="pdf-thumb"></image>
              </view>
              <text class="file-display-name text-ellipsis">{{ file.name }}</text>
            </view>
            <view class="remove-action" @click.stop="removeResume(idx)">
              <image class="remove-icon" src="/static/icons/close_gray.svg" mode="aspectFit"></image>
            </view>
          </view>
        </view>
        
        <!-- 空状态提示 -->
        <view class="empty-resume" v-else>
          <text>暂无附件简历，最多可上传3份</text>
        </view>
      </view>

      <!-- 普通功能条 -->
      <view class="list-item" @click="handleOffer">
        <text class="list-label">我的offer/签约</text>
        <image class="list-arrow" src="/static/icons/chevron-right.svg" mode="aspectFit"></image>
      </view>

      <view class="list-item" @click="handlePrivacy">
        <text class="list-label">隐私政策</text>
        <image class="list-arrow" src="/static/icons/chevron-right.svg" mode="aspectFit"></image>
      </view>
    </view>

    <!-- 底部登出与信息 -->
    <view class="bottom-area">
      <view class="logout-action" @click="handleLogout">
        <text>退出登录</text>
      </view>
      <view class="contact-info">
        <text>电话：400-XXXX-XX9   工作时间：8:00-22:00</text>
      </view>
    </view>

    <!-- 页面底部垫高 -->
    <view class="bottom-pad"></view>

    <!-- 自定义提示弹窗 -->
    <view class="modal-mask" v-if="showResumeModal" @touchmove.stop.prevent>
      <view class="modal-content confirm-modal">
        <view class="confirm-title">提示</view>
        <view class="confirm-desc">您当前还未填写在线简历，是否去填写？</view>
        <view class="confirm-footer">
          <button class="btn-cancel" @click="showResumeModal = false">取消</button>
          <button class="btn-primary" @click="confirmToFill">去填写</button>
        </view>
      </view>
    </view>

    <!-- 自定义导航栏 -->
    <custom-tabbar :activeIndex="3"></custom-tabbar>
  </view>
</template>

<script setup lang="js">
import { ref, computed, onMounted } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import CustomTabbar from '../../components/custom-tabbar/custom-tabbar.vue';
import { getStudent, getAppendixList, addAppendix, removeAppendix } from '../../api/student.js';
import { UPLOAD_URL } from '../../utils/request';

const navFullHeight = ref(80); // 默认高度
const showResumeModal = ref(false);

// 学生详细信息（从后端获取）
const studentInfo = ref({
    id: null,
    name: '',
    avatarUrl: '',
    schoolName: '',
    education: '',
    educationLabel: '',
    jobType: '',
    jobTypeLabel: '',
    resumeFile: null,
    educationList: [], // 教育经历列表
});

// 计算学历展示标签（从教育经历列表中获取最高学历）
const educationLabel = computed(() => {
    if (studentInfo.value.educationList && studentInfo.value.educationList.length > 0) {
        const educationLevel = { '初中及以下': 1, '高中': 2, '中专': 2, '大专': 3, '本科': 4, '硕士': 5, '博士': 6 };
        let highestEdu = studentInfo.value.educationList[0];
        let maxLevel = educationLevel[highestEdu.education] || 0;
        for (const edu of studentInfo.value.educationList) {
            const level = educationLevel[edu.education] || 0;
            if (level > maxLevel) { maxLevel = level; highestEdu = edu; }
        }
        return highestEdu.education || '';
    }
    if (studentInfo.value.educationLabel) return studentInfo.value.educationLabel;
    const val = studentInfo.value.education;
    if (!val || val === '0' || val === 0) return '';
    return /^\d+$/.test(String(val)) ? '' : val;
});

// 计算求职类型展示标签（通过字典值转换）
const jobTypeMap = { '1': '全职', '2': '实习', '3': '兼职', '全职': '全职', '实习': '实习', '兼职': '兼职' };
const jobTypeLabel = computed(() => {
    if (studentInfo.value.jobTypeLabel) return studentInfo.value.jobTypeLabel;
    const val = studentInfo.value.jobType;
    return jobTypeMap[val] || val || '';
});

// 计算院校名称展示标签（从教育经历中获取最高学历的学校）
const schoolNameLabel = computed(() => {
    if (studentInfo.value.educationList && studentInfo.value.educationList.length > 0) {
        const educationLevel = { '初中及以下': 1, '高中': 2, '中专': 2, '大专': 3, '本科': 4, '硕士': 5, '博士': 6 };
        let highestEdu = studentInfo.value.educationList[0];
        let maxLevel = educationLevel[highestEdu.education] || 0;
        for (const edu of studentInfo.value.educationList) {
            const level = educationLevel[edu.education] || 0;
            if (level > maxLevel) { maxLevel = level; highestEdu = edu; }
        }
        return highestEdu.school || '';
    }
    const val = studentInfo.value.schoolName;
    if (!val || /^\d+$/.test(val)) return '';
    return val;
});

// 是否有在线简历（有 resumeFile 字段值则判断为有）
const hasResume = computed(() => !!studentInfo.value.resumeFile);

// 加载用户信息
const loadUserInfo = async () => {
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo || !userInfo.studentId) return;
    try {
        const res = await getStudent(userInfo.studentId);
        if (res && res.data) {
            const data = res.data;
            studentInfo.value = {
                id: data.id,
                name: data.name || userInfo.name || '',
                avatarUrl: data.avatarUrl || userInfo.avatarUrl || '',
                schoolName: data.schoolName || '',
                education: data.education || '',
                educationLabel: data.educationLabel || '',
                jobType: data.jobType || '',
                jobTypeLabel: data.jobTypeLabel || '',
                resumeFile: data.resumeFile || null,
                educationList: data.educationList || [],
            };
        }
    } catch (err) {
        console.error('获取用户详情失败', err);
    }
    fetchAppendixList();
};

onMounted(async () => {
    // #ifdef MP-WEIXIN
    try {
        const menuButton = uni.getMenuButtonBoundingClientRect();
        if (menuButton) {
            navFullHeight.value = menuButton.bottom + 10;
        }
    } catch (e) {
        console.error('导航栏高度计算失败', e);
    }
    // #endif

    // 从本地缓存读取登录信息
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo || !userInfo.studentId) {
        // 未登录，跳转登录页
        uni.reLaunch({ url: '/pages/login/login' });
        return;
    }

    // 先用登录时缓存的基本信息快速展示
    studentInfo.value.id = userInfo.studentId;
    studentInfo.value.name = userInfo.name || '';
    studentInfo.value.avatarUrl = userInfo.avatarUrl || '';

    // 再从后端拉取完整学员信息
    await loadUserInfo();
});

onShow(async () => {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.studentId) {
        await loadUserInfo();
    }
});

onPullDownRefresh(async () => {
    await loadUserInfo();
    uni.stopPullDownRefresh();
});

// 获取附件简历列表
const fetchAppendixList = async () => {
    try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo && userInfo.studentId) {
            const res = await getAppendixList(userInfo.studentId);
            if (res && res.code === 200) {
                resumeList.value = res.data.map(item => ({
                    id: item.id,
                    name: item.fileName,
                    url: item.url,
                    ossId: item.ossId
                }));
            }
        }
    } catch (err) {
        console.error('获取附件列表失败', err);
    }
};


const handleOnlineResume = () => {
    if (!hasResume.value) {
        showResumeModal.value = true;
    } else {
        uni.navigateTo({ url: '/pages/my/resume_view' });
    }
};

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

const navigateTo = (type) => {
    const routes = {
        'collection': '/pages/my/favorites',
        'intention': '/pages/intention/intention?editMode=1',
        'assessment': '/pages/my/assessment-records',
        'order': '/pages/my/orders'
    };
    if (routes[type]) {
        uni.navigateTo({ url: routes[type] });
    }
};

const handleOffer = () => {
    uni.navigateTo({ url: '/pages/my/offer' });
};

const handlePrivacy = () => {
    uni.navigateTo({ url: '/pages/my/privacy_policy' });
};

// 附件简历列表（本地维护，最多3份）
const resumeList = ref([]);

const uploadFromWechat = () => {
    if (resumeList.value.length >= 3) {
        uni.showToast({ title: '最多上传3份简历', icon: 'none' });
        return;
    }
    // #ifdef MP-WEIXIN
    // 微信小程序中，从聊天记录选择文件是唯一支持PDF等文档的官方接口
    uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['pdf'],
        success: (res) => {
            const file = res.tempFiles[0];
            processUpload(file.name, file.path, file.size);
        }
    });
    // #endif
};

const uploadFromLocal = () => {
    // 在微信小程序中，uni.chooseFile 兼容性极差且非官方推荐
    // 实际上的“本地上传”在小程序内也往往需要通过 chooseMessageFile 调起（微信提供了从相册/文件选择的入口）
    // 为了用户体验一致，这里我们统一调用 uploadFromWechat
    uploadFromWechat();
};

const processUpload = (name, path, size) => {
    if (!name.toLowerCase().endsWith('.pdf')) {
        uni.showToast({ title: '仅支持 PDF 格式文件', icon: 'none' });
        return;
    }
    
    uni.showLoading({ title: '上传中...' });

    // 1. 先调用通用的 OSS 上传接口
    // 注意：如果是生产环境，请确保 baseUrl 正确
    const baseUrl = UPLOAD_URL;
    uni.uploadFile({
        url: baseUrl + '/portal/oss/upload',
        filePath: path,
        name: 'file',
        header: {
            'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : '',
            'PLATFORM_CODE': 'PINGTAIDUAN'
        },
        success: async (uploadRes) => {
            const uploadData = JSON.parse(uploadRes.data);
            if (uploadData.code === 200) {
                const ossId = uploadData.data.ossId;
                
                // 2. 将 OSS 关联到学员附件表
                try {
                    const userInfo = uni.getStorageSync('userInfo');
                    const saveRes = await addAppendix({
                        studentId: userInfo.studentId,
                        ossId: ossId,
                        fileName: name,
                        fileSize: size
                    });
                    
                    uni.hideLoading();
                    if (saveRes.code === 200) {
                        uni.showToast({ title: '上传成功', icon: 'success' });
                        fetchAppendixList(); // 刷新列表
                    } else {
                        uni.showToast({ title: saveRes.msg || '保存失败', icon: 'none' });
                    }
                } catch (e) {
                    uni.hideLoading();
                    uni.showToast({ title: '服务器异常', icon: 'none' });
                }
            } else {
                uni.hideLoading();
                uni.showToast({ title: uploadData.msg || '上传失败', icon: 'none' });
            }
        },
        fail: (err) => {
            uni.hideLoading();
            uni.showToast({ title: '网络上传失败', icon: 'none' });
        }
    });
};

const removeResume = (index) => {
    const target = resumeList.value[index];
    uni.showModal({
        title: '提示',
        content: '确定要删除这份简历吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    uni.showLoading({ title: '删除中...' });
                    const delRes = await removeAppendix(target.id);
                    uni.hideLoading();
                    if (delRes.code === 200) {
                        resumeList.value.splice(index, 1);
                        uni.showToast({ title: '已删除', icon: 'none' });
                    } else {
                        uni.showToast({ title: delRes.msg || '删除失败', icon: 'none' });
                    }
                } catch (e) {
                    uni.hideLoading();
                    uni.showToast({ title: '网络异常', icon: 'none' });
                }
            }
        }
    });
};

const handleLogout = () => {
    uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
            if (res.confirm) {
                // 清除本地登录信息
                uni.removeStorageSync('token');
                uni.removeStorageSync('userInfo');
                uni.reLaunch({ url: '/pages/login/login' });
            }
        }
    });
};
</script>

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

.nav-placeholder {
    width: 100%;
    background-color: #FFF;
}

.user-card-wrap {
  padding: 20rpx 40rpx 10rpx;
  background-color: #FFF;
  .user-main {
    display: flex;
    align-items: center;
    .avatar-wrap {
      width: 140rpx; height: 140rpx; border-radius: 50%; overflow: hidden;
      margin-right: 24rpx; background: #F0F0F0; border: 4rpx solid #F8F9FB;
      image { width: 100%; height: 100%; }
    }
    .info-content {
      flex: 1;
      .name-box {
        display: flex; align-items: center; margin-bottom: 24rpx;
        .user-name { font-size: 42rpx; font-weight: bold; color: #1A1A1A; margin-right: 12rpx; }
        .diamond-icon { width: 36rpx; height: 36rpx; }
        .flex-spacer { flex: 1; }
        .resume-link {
          display: flex; align-items: center; font-size: 26rpx; color: #1F6CFF;
          .link-arrow { width: 24rpx; height: 24rpx; margin-left: 4rpx; }
        }
      }
      .badge-row {
        display: flex; flex-wrap: wrap; gap: 12rpx;
        .profile-tag {
          font-size: 22rpx; color: #666; background: #F4F6F9;
          padding: 8rpx 22rpx; border-radius: 20rpx;
        }
      }
    }
  }
}

.feature-grid {
  display: flex; justify-content: space-around;
  padding: 40rpx 20rpx; background: #FFF;
  margin-top: 20rpx;
  .grid-cell {
    display: flex; flex-direction: column; align-items: center;
    .icon-wrap-premium {
      width: 80rpx; height: 80rpx;
      display: flex; align-items: center; justify-content: center;
      margin-bottom: 24rpx;
      position: relative;
      &::after {
        content: ''; position: absolute; left: 10%; right: 10%; bottom: -4rpx; height: 8rpx;
        background: rgba(0,0,0,0.06); filter: blur(6rpx); border-radius: 50%; z-index: -1;
      }
      image { width: 100%; height: 100%; }
      &:active { transform: translateY(2rpx) scale(0.96); opacity: 0.9; }
    }
    .cell-label { font-size: 26rpx; color: #333; font-weight: 500; }
  }
}

.service-panel {
  background: #FFF; margin-top: 20rpx; padding: 40rpx 40rpx 20rpx;
  .panel-header {
    margin-bottom: 40rpx;
    .panel-title { font-size: 32rpx; font-weight: bold; color: #1A1A1A; }
  }

  .resume-section {
    display: flex; flex-direction: column; align-items: stretch; margin-bottom: 20rpx;
    .res-head {
       display: flex; align-items: center; justify-content: space-between; margin-bottom: 30rpx;
       .res-title { font-size: 28rpx; color: #333; font-weight: 500; }
       .upload-links {
          display: flex; gap: 24rpx;
          .link-btn { font-size: 24rpx; color: #999; &.active { color: #1F6CFF; } }
       }
    }
    .file-card {
      background: #F8F9FA; display: flex; align-items: center; justify-content: space-between;
      padding: 14rpx 30rpx; border-radius: 20rpx; margin-bottom: 20rpx; border: 1rpx solid #F0F2F5;
      .file-info-main {
          display: flex; align-items: center; flex: 1; overflow: hidden;
          .file-icon-box { 
              width: 44rpx; height: 44rpx; margin-right: 16rpx; display: flex; align-items: center; flex-shrink: 0;
              image { width: 100%; height: 100%; }
          }
          .file-display-name { 
              font-size: 24rpx; color: #1F6CFF; font-weight: 500;
              overflow: hidden; white-space: nowrap; text-overflow: ellipsis; 
          }
      }
      .remove-action {
          padding: 10rpx; margin-right: -10rpx; flex-shrink: 0;
          image { width: 32rpx; height: 32rpx; opacity: 0.2; }
      }
    }
  }
  
  .empty-resume {
      padding: 40rpx 0; text-align: center; border: 2rpx dashed #EAECEF; border-radius: 20rpx;
      text { font-size: 24rpx; color: #BBB; }
  }

  .list-item {
    display: flex; align-items: center; justify-content: space-between;
    height: 110rpx; border-top: 1rpx solid #F7F8FA;
    .list-label { font-size: 28rpx; color: #333; }
    .list-arrow { width: 32rpx; height: 32rpx; opacity: 0.3; }
  }
}

.bottom-area {
  padding: 80rpx 0 100rpx; text-align: center;
  .logout-action { margin-bottom: 30rpx; text { font-size: 30rpx; color: #AAA; } }
  .contact-info { text { font-size: 22rpx; color: #CCC; } }
}

.modal-mask {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.6); z-index: 2000;
  display: flex; align-items: center; justify-content: center;
}

.confirm-modal {
  background: #FFF; border-radius: 32rpx; width: 540rpx; padding: 60rpx 40rpx; text-align: center;
  .confirm-title { font-size: 36rpx; font-weight: bold; margin-bottom: 20rpx; color: #1A1A1A; }
  .confirm-desc { font-size: 28rpx; color: #888; margin-bottom: 60rpx; }
  .confirm-footer {
    display: flex; gap: 20rpx;
    button {
      flex: 1; height: 68rpx; line-height: 68rpx; border-radius: 34rpx; font-size: 26rpx;
      &::after { border: none; }
      &.btn-cancel { background: #F5F5F7; color: #666; }
      &.btn-primary { background: #1F6CFF; color: #FFF; }
    }
  }
}

.bottom-pad { height: 160rpx; }

.card-anim {
  animation: slideIn 0.4s ease-out;
}
@keyframes slideIn { from { opacity: 0; transform: translateY(10rpx); } to { opacity: 1; transform: translateY(0); } }
</style>
