<template>
  <view class="container">
    <!-- ① 固定返回按钮：适配状态栏，带阴影层确保白图标可见 -->
    <view class="custom-nav" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-back-wrap" @click="goBack">
        <image src="/static/icons/back_white.svg" class="back-icon" mode="aspectFit"></image>
      </view>
    </view>

    <!-- ② 核心滑动容器：显式关闭滚动条，设定 flex: 1 确保可滑动 -->
    <scroll-view 
      class="scroll-body" 
      scroll-y 
      :show-scrollbar="false" 
      :enhanced="true"
    >
      <!-- 轮播图区域 -->
      <view class="banner-section">
        <swiper class="banner-swiper" circular autoplay interval="3000" indicator-dots indicator-active-color="#FFFFFF">
          <swiper-item v-for="(img, index) in bannerImages" :key="index">
            <image :src="img" class="banner-img" mode="aspectFill"></image>
          </swiper-item>
        </swiper>
      </view>

      <!-- 内容主体：还原单一白底背板 -->
      <view class="content-panel">
        <view class="header-info" v-if="!loading">
          <text class="title">{{ assessmentData.evaluationName || '测评详情' }}</text>
          <view class="meta-list">
            <view class="meta-item" v-if="assessmentData.startTime && assessmentData.endTime">
              <text class="label">参与时间：</text>
              <text class="value">{{ formatDateRange(assessmentData.startTime, assessmentData.endTime) }}</text>
            </view>
            <view class="meta-item" v-if="assessmentData.questionTypes">
              <text class="label">考题题型：</text>
              <text class="value">{{ assessmentData.questionTypes }}</text>
            </view>
            <view class="meta-item" v-if="assessmentData.questionCount">
              <text class="label">考题数量：</text>
              <text class="value">{{ assessmentData.questionCount }}题</text>
            </view>
            <view class="meta-item" v-if="assessmentData.duration">
              <text class="label">考试时间：</text>
              <text class="value">{{ assessmentData.duration }}分钟</text>
            </view>
          </view>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading-state" v-if="loading">
          <text class="loading-text">加载中...</text>
        </view>

        <view class="divider-line"></view>

        <view class="detail-section" v-if="!loading">
          <text class="section-title">测评详情</text>
          <view class="tag-cloud" v-if="tags.length > 0">
            <text class="detail-tag" v-for="tag in tags" :key="tag">{{ tag }}</text>
          </view>
          <view class="description" v-if="displayDescription">
            <text class="desc-label">测评描述：</text>
            <text class="desc-content">
              {{ displayDescription }}
            </text>
          </view>
        </view>

        <!-- 富文本内容 (严格控制侧边距) -->
        <view class="diagram-section" v-if="assessmentData.detail && assessmentData.detail.includes('<')">
          <rich-text :nodes="assessmentData.detail"></rich-text>
        </view>

        <!-- ③ 到底啦提示 -->
        <view class="end-of-page">
          <view class="line"></view>
          <text class="end-text">已到底啦~</text>
          <view class="line"></view>
        </view>

        <!-- 底部撑开，预留按钮位置 -->
        <view class="bottom-placeholder"></view>
      </view>
    </scroll-view>

    <!-- ④ 底部固定操作栏 -->
    <view class="bottom-bar">
      <view class="action-item" @click="toggleFavorite">
        <image :src="isFavorited ? '/static/icons/star_filled.svg' : '/static/icons/star_hollow.svg'" class="action-icon"></image>
        <text :class="['action-text', isFavorited ? 'active' : '']">{{ isFavorited ? '已收藏' : '收藏' }}</text>
      </view>
      <button v-if="!hasPaid && !hasRecord" class="small-consult-btn" @click="handleConsult">咨询</button>
      <button v-if="hasPaid && !hasRecord" class="start-exam-btn" @click="goToRemind">开始测评</button>
      <button 
        v-if="hasRecord"
        class="report-btn" 
        :class="{ disabled: !isAllCompleted }" 
        @click="viewReport"
      >查看报告</button>
      <button v-if="hasRecord && !isPassed" class="start-exam-btn" @click="goToRemind">重新测评</button>
      <button v-if="isPassed && !isApplied" class="apply-btn" @click="handleApply">投递简历</button>
      <button v-if="isPassed && isApplied" class="applied-btn">已投递</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { addCollection, delCollection, checkCollection } from '../../api/collection.js';
import { createOrGetSession } from '../../api/message.js';
import { getAssessmentDetail, getAssessmentRecordList } from '../../api/assessment.js';

const statusBarHeight = ref(20);
const isFavorited = ref(false);
const collectionId = ref(null);
const assessmentId = ref(null);
const loading = ref(true);
const assessmentData = ref({});
const bannerImages = ref([
    '/static/images/assess_cover.svg',
    '/static/images/assess_cover.svg'
]);
const tags = ref([]);
// 测评记录相关
const hasRecord = ref(false);       // 是否有测评记录
const isAllCompleted = ref(false);   // 是否全部考完（finalResult 有值）
const hasPaid = ref(false);         // 是否已付款
const isPassed = ref(false);        // 是否测评通过
const isApplied = ref(false);       // 是否已投递简历

const decodeBase64Utf8 = (value) => {
    if (!value || typeof value !== 'string') return '';
    try {
        const binary = atob(value);
        const bytes = Array.from(binary, char => char.charCodeAt(0));
        return decodeURIComponent(bytes.map(byte => `%${byte.toString(16).padStart(2, '0')}`).join(''));
    } catch (e) {
        return value;
    }
};

const displayDescription = computed(() => {
    const data = assessmentData.value || {};
    if (data.remark || data.description) {
        return data.remark || data.description;
    }
    if (data.detail) {
        return /^[A-Za-z0-9+/=]+$/.test(data.detail) ? decodeBase64Utf8(data.detail) : data.detail;
    }
    return '暂无描述';
});

onMounted(() => {
    // #ifdef MP-WEIXIN
    const sysInfo = uni.getSystemInfoSync();
    statusBarHeight.value = (sysInfo.statusBarHeight || 20);
    // #endif
});

onLoad((options) => {
    if (options.id) {
        assessmentId.value = options.id;
        loadAssessmentDetail(options.id);
        checkCollectionStatus(options.id);
        checkExamRecord(options.id);
    }
});

// 加载测评详情数据
const loadAssessmentDetail = async (id) => {
    try {
        loading.value = true;
        const res = await getAssessmentDetail(id);
        if (res.code === 200 && res.data) {
            assessmentData.value = res.data;
            // 处理标签数据
            if (res.data.tags) {
                tags.value = res.data.tags.split(',').filter(tag => tag.trim());
            }
            // 处理轮播图
            if (res.data.imageAlbumUrls) {
                const urls = res.data.imageAlbumUrls.split(',');
                bannerImages.value = urls.length > 0 ? urls : ['/static/images/assess_cover.svg'];
            } else if (res.data.mainImageUrl) {
                bannerImages.value = [res.data.mainImageUrl];
            } else {
                bannerImages.value = ['/static/images/assess_cover.svg'];
            }
            
            // 检查是否已投递简历（基于关联的岗位ID）
            if (res.data.positionId) {
                isApplied.value = uni.getStorageSync(`candidate_applied_${res.data.positionId}`) === true;
            }
        } else {
            uni.showToast({ title: '获取测评详情失败', icon: 'none' });
        }
    } catch (err) {
        console.error('获取测评详情失败:', err);
        uni.showToast({ title: '网络错误，请重试', icon: 'none' });
    } finally {
        loading.value = false;
    }
};

// 检查收藏状态
const checkCollectionStatus = async (id) => {
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo || !userInfo.studentId) return;
    
    try {
        const res = await checkCollection(userInfo.studentId, id, 'assessment');
        if (res.code === 200 && res.data) {
            isFavorited.value = true;
            collectionId.value = res.data.id;
        } else {
            isFavorited.value = false;
            collectionId.value = null;
        }
    } catch (err) {
        console.error('检查收藏状态失败', err);
    }
};

// 格式化日期范围
const formatDateRange = (startTime, endTime) => {
    if (!startTime || !endTime) return '';
    
    const formatDate = (dateStr) => {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}.${month}.${day} ${hours}:${minutes}`;
    };
    
    return `${formatDate(startTime)}—${formatDate(endTime)}`;
};

const goBack = () => uni.navigateBack();

// 跳转到测评提醒页面
const goToRemind = () => {
    if (!assessmentId.value) {
        uni.showToast({ title: '测评信息加载中', icon: 'none' });
        return;
    }
    uni.navigateTo({
        url: `/pages/assessment/remind?id=${assessmentId.value}`
    });
};

// 查看考试报告
const viewReport = () => {
    if (!assessmentId.value || !isAllCompleted.value) return;
    uni.navigateTo({
        url: `/pages/assessment/report?id=${assessmentId.value}`
    });
};

// 检查是否有测评记录
const checkExamRecord = async (id) => {
    const userInfo = uni.getStorageSync('userInfo') || {};
    const studentId = userInfo.studentId;
    if (!studentId) return;
    
    // 检查是否已付款
    hasPaid.value = uni.getStorageSync(`audit_paid_${id}`) === true;
    
    try {
        const res = await getAssessmentRecordList(studentId);
        if (res.code === 200 && res.data) {
            // 找到当前测评的记录
            const records = res.data.filter(r => String(r.evaluationId) === String(id));
            if (records.length > 0) {
                hasRecord.value = true;
                // 检查是否全部考完（finalResult 有值表示已完成评分）
                const completedRecords = records.filter(r => r.finalResult === '1' || r.finalResult === '2');
                isAllCompleted.value = completedRecords.length > 0;
                // 检查是否通过
                const passedRecords = records.filter(r => r.finalResult === '1');
                isPassed.value = passedRecords.length > 0;
            }
        }
        
        // 检查是否已投递（需要等 assessmentData 加载完成后才有 positionId）
        if (assessmentData.value.positionId) {
            isApplied.value = uni.getStorageSync(`candidate_applied_${assessmentData.value.positionId}`) === true;
        }
    } catch (err) {
        console.error('检查测评记录失败', err);
    }
};

const handleConsult = async () => {
    try {
        uni.showLoading({ title: '正在连接客服...' });
        const userInfo = uni.getStorageSync('userInfo') || {};
        const userId = userInfo.studentId || null;
        const userName = userInfo.name || '用户';
        const userAvatar = userInfo.avatarUrl || '/static/images/user_avatar.svg';
        console.log('创建会话参数:', {
          sessionType: 1,
          fromUserId: userId,
          fromUserName: userName,
          fromUserAvatar: userAvatar,
          sourceId: 'assessment_' + (assessmentData.value?.id || assessmentId.value)
        });
        const res = await createOrGetSession({
          sessionType: 1,
          fromUserId: userId,
          fromUserName: userName,
          fromUserAvatar: userAvatar,
          sourceId: 'assessment_' + (assessmentData.value?.id || assessmentId.value)
        });
        uni.hideLoading();
        if (res.data) {
            const session = res.data;
            const title = encodeURIComponent(assessmentData.value.evaluationName || '测评详情'); 
            const cover = encodeURIComponent(bannerImages.value[0] || '');
            const price = assessmentData.value.price || '0.00';
            uni.navigateTo({
                url: `/pages/chat/chat?sessionId=${session.sessionId}&sessionNo=${session.sessionNo || ''}&fromUserId=${userId || ''}&userName=${encodeURIComponent(userName)}&type=assessment&title=${title}&cover=${cover}&assessmentId=${assessmentId.value || ''}&price=${price}`
            });
        } else {
            uni.showToast({ title: '创建会话失败', icon: 'none' });
        }
    } catch (err) {
        uni.hideLoading();
        console.error('创建会话失败:', err);
        uni.showToast({ title: '连接失败，请重试', icon: 'none' });
    }
};

// 投递简历：跳转到选择简历页面
const handleApply = () => {
    const postId = assessmentData.value.positionId;
    if (!postId) {
        uni.showToast({ title: '该测评未关联岗位，无法投递', icon: 'none' });
        return;
    }
    const userInfo = uni.getStorageSync('userInfo') || {};
    if (!userInfo.studentId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
    }
    uni.navigateTo({
        url: `/pages/my/select-resume?postId=${postId}`
    });
};

const toggleFavorite = async () => {
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo || !userInfo.studentId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => {
            uni.navigateTo({ url: '/pages/login/login' });
        }, 1000);
        return;
    }
    
    if (!assessmentId.value) return;
    
    uni.showLoading({ title: isFavorited.value ? '取消收藏中...' : '收藏中...' });
    
    try {
        if (isFavorited.value) {
            // 取消收藏
            if (collectionId.value) {
                const res = await delCollection(collectionId.value);
                if (res.code === 200) {
                    isFavorited.value = false;
                    collectionId.value = null;
                    uni.showToast({ title: '已取消收藏', icon: 'none' });
                }
            }
        } else {
            // 添加收藏
            const res = await addCollection({
                studentId: userInfo.studentId,
                targetId: assessmentId.value,
                type: 'assessment'
            });
            if (res.code === 200) {
                isFavorited.value = true;
                checkCollectionStatus(assessmentId.value);
                uni.showToast({ title: '收藏成功', icon: 'success' });
            }
        }
    } catch (err) {
        console.error('操作收藏失败', err);
        uni.showToast({ title: '操作失败', icon: 'none' });
    } finally {
        uni.hideLoading();
    }
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  background-color: #FFFFFF;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止页面整体滚动，交给 scroll-view */
}

/* 返回按钮 */
.custom-nav {
  position: fixed; top: 0; left: 0; width: 100%; z-index: 999;
  padding-left: 30rpx;
  .nav-back-wrap {
    width: 64rpx; height: 64rpx; background: rgba(0,0,0,0.35); border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    margin-top: 10px;
    .back-icon { width: 44rpx; height: 44rpx; }
  }
}

/* 滑动主体 */
.scroll-body {
  flex: 1; /* 撑满剩余空间 */
  height: 0; /* 触发 flex 计算 */
}

/* 轮播图 */
.banner-section {
  width: 100%; height: 500rpx;
  .banner-swiper { width: 100%; height: 100%; }
  .banner-img { width: 100%; height: 100%; }
}

/* 内容板块 */
.content-panel {
  background: #FFF;
  border-radius: 40rpx 40rpx 0 0;
  margin-top: -40rpx;
  position: relative;
  z-index: 10;
  padding: 50rpx 40rpx 0;
  
  .header-info {
    margin-bottom: 40rpx;
    .title { font-size: 44rpx; font-weight: bold; color: #1A1A1A; display: block; margin-bottom: 30rpx; }
    .meta-list {
        display: flex; flex-direction: column; gap: 16rpx;
        .meta-item {
            display: flex; font-size: 28rpx;
            .label { color: #666; width: 160rpx; flex-shrink: 0; }
            .value { color: #333; font-weight: 500; }
        }
    }
  }

  .divider-line {
      height: 1rpx; background: #F0F0F0; margin: 40rpx 0;
  }

  .detail-section {
    margin-bottom: 40rpx;
    .section-title { font-size: 34rpx; font-weight: bold; color: #1A1A1A; display: block; margin-bottom: 30rpx; }
    .tag-cloud {
        display: flex; flex-wrap: wrap; gap: 16rpx; margin-bottom: 32rpx;
        .detail-tag { font-size: 24rpx; color: #666; background: #F5F7FA; padding: 10rpx 24rpx; border-radius: 10rpx; }
    }
    .description {
        margin-bottom: 40rpx;
        .desc-label { font-size: 28rpx; color: #1A1A1A; font-weight: bold; display: block; margin-bottom: 12rpx; }
        .desc-content { font-size: 28rpx; color: #666; line-height: 1.6; }
    }
  }

  .diagram-section {
    width: 100%; margin-top: 20rpx;
    .diagram-img { width: 100%; border-radius: 12rpx; }
  }

  .loading-state {
    display: flex; justify-content: center; align-items: center; 
    padding: 80rpx 0;
    .loading-text { font-size: 28rpx; color: #999; }
  }
}

.end-of-page {
  display: flex; align-items: center; justify-content: center; padding: 60rpx 0 40rpx;
  .line { width: 60rpx; height: 1rpx; background: #EEE; margin: 0 20rpx; }
  .end-text { font-size: 24rpx; color: #BBB; }
}

.bottom-placeholder {
    height: calc(140rpx + env(safe-area-inset-bottom));
}

.bottom-bar {
  position: fixed; bottom: 0; left: 0; right: 0; background: #FFF; 
  padding: 20rpx 40rpx; padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.05); z-index: 1000;
  display: flex; align-items: center; gap: 40rpx;
  
  .action-item {
    display: flex; flex-direction: column; align-items: center; min-width: 100rpx;
    .action-icon { width: 44rpx; height: 44rpx; margin-bottom: 4rpx; }
    .action-text { font-size: 22rpx; color: #666; &.active { color: #FFB700; } }
  }

  .small-consult-btn {
    flex: 1; height: 84rpx; line-height: 84rpx;
    background: #FFB700; color: #FFF; border-radius: 42rpx; 
    font-size: 30rpx; font-weight: bold;
    box-shadow: 0 6rpx 12rpx rgba(255, 183, 0, 0.2);
    &::after { border: none; }
    &:active { opacity: 0.9; }
  }

  .report-btn {
    flex: 1; height: 84rpx; line-height: 84rpx;
    background: #E8F0FF; color: #2B5CFF; border-radius: 42rpx;
    font-size: 30rpx; font-weight: bold;
    &::after { border: none; }
    &:active { opacity: 0.9; }
    &.disabled {
      background: #F0F2F5; color: #C0C4CC; pointer-events: none;
    }
  }

  .start-exam-btn {
    flex: 1.5; height: 84rpx; line-height: 84rpx;
    background: linear-gradient(135deg, #1F6CFF 0%, #0056FF 100%); color: #FFF; border-radius: 42rpx;
    font-size: 30rpx; font-weight: bold;
    box-shadow: 0 6rpx 16rpx rgba(31, 108, 255, 0.3);
    &::after { border: none; }
    &:active { opacity: 0.9; transform: scale(0.98); }
  }

  .apply-btn {
    flex: 1.5; height: 84rpx; line-height: 84rpx;
    background: #1F6CFF; color: #FFF; border-radius: 42rpx;
    font-size: 30rpx; font-weight: bold;
    box-shadow: 0 6rpx 16rpx rgba(31, 108, 255, 0.3);
    &::after { border: none; }
    &:active { opacity: 0.9; transform: scale(0.98); }
  }

  .applied-btn {
    flex: 1.5; height: 84rpx; line-height: 84rpx;
    background: #E0E0E0; color: #999; border-radius: 42rpx;
    font-size: 30rpx; font-weight: bold;
    &::after { border: none; }
  }
}
</style>

<style>
/* 针对所有 scroll-view 隐藏滚动条 */
::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
    background: transparent;
}
</style>
