<template>
  <view class="container">
    <!-- 固定顶部区域 -->
    <view class="fixed-header">
      <!-- ① 蓝色渐变搜索区域 -->
      <view class="gradient-section" :style="{ paddingTop: (statusBarHeight + titleBarMargin) + 'px' }">
        <view class="search-wrap" :style="{ height: menuButtonHeight + 'px' }">
          <view class="search-bar">
            <image src="/static/icons/search.svg" class="search-icon" mode="aspectFit"></image>
            <input 
              type="text" 
              v-model="searchQuery"
              placeholder="请输入关键字" 
              class="search-input" 
              placeholder-class="ph-color"
              confirm-type="search"
              @confirm="fetchAssessments"
            />
          </view>
        </view>
      </view>

      <!-- ② 白色区域 -->
      <view class="white-section">
        <view class="horizontal-tabs-wrap">
          <view class="main-tabs">
            <view 
              class="main-tab" 
              :class="{ active: currentTab === 0 }"
              @click="handleTabChange(0)"
            >测评</view>
            <view 
              class="main-tab" 
              :class="{ active: currentTab === 1 }"
              @click="handleTabChange(1)"
            >培训</view>
          </view>
          <view class="record-btn" @click="goToRecords">
            <text class="record-text">{{ recordText }}</text>
          </view>
        </view>

        <view class="filter-row">
          <view 
            v-for="(filter, index) in currentFilters" 
            :key="index" 
            class="filter-item"
            :class="{ active: activeFilterIndex === index }"
            @click="toggleFilter(index)"
          >
            {{ filter.selectedLabel || filter.label }}
            <image 
              class="arrow-down" 
              :class="{ rotate: activeFilterIndex === index }"
              src="/static/icons/arrow-down.svg"
            ></image>
          </view>
        </view>
      </view>

      <!-- 下拉面板 -->
      <view class="dropdown-wrapper" v-if="activeFilterIndex !== -1">
        <view class="mask" @click="closeFilter"></view>
        <view class="dropdown-content">
          <view 
            v-for="(opt, idx) in currentOptions" 
            :key="idx" 
            class="option-item"
            :class="{ selected: (currentFilters[activeFilterIndex].selectedValue === opt.value) }"
            @click="selectOption(opt)"
          >
            <text>{{ opt.label }}</text>
            <image v-if="currentFilters[activeFilterIndex].selectedValue === opt.value" src="/static/icons/check.svg" class="check-icon"></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 可滚动的列表内容 (测评) -->
    <view class="loading-box" v-if="loading && assessments.length === 0 && currentTab === 0">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    <scroll-view 
      v-if="currentTab === 0 && (!loading || assessments.length > 0)"
      class="scroll-body" 
      scroll-y 
      :style="{ top: scrollTop + 'px' }"
      :show-scrollbar="false"
      :enhanced="true"
    >
      <view class="assessment-list">
        <view 
          class="job-card card-anim" 
          v-for="(item, index) in filteredAssessments" 
          :key="index" 
          @click="goToDetail(item)"
        >
          <view class="card-left">
            <image :src="item.cover" class="cover-img" mode="aspectFill"></image>
          </view>
          <view class="card-right">
            <view class="top-line">
              <text class="job-title">{{ item.title }}</text>
              <text class="job-level-tag">{{ item.level }}</text>
            </view>
            <view class="tag-row">
              <text class="tag-badge type-tag">{{ getTypeLabel(item.type) }}</text>
              <text class="tag-badge category-tag">{{ getCategoryLabel(item.category) }}</text>
              <text class="tag-badge" v-for="(tag, tIdx) in item.tags" :key="tIdx">{{ tag }}</text>
            </view>
            <view class="desc-text text-ellipsis-2">
              {{ item.desc }}
            </view>
            <view class="btn-wrap">
              <button v-if="item.isPassed && !item.isApplied" class="apply-btn" @click.stop="handleApply(item)">投递简历</button>
              <button v-if="item.isPassed && item.isApplied" class="applied-btn">已投递</button>
              <button v-if="item.hasRecord && !item.isPassed" class="report-btn" :class="{ disabled: !item.isCompleted }" @click.stop="viewAssessmentReport(item)">查看报告</button>
              <button v-if="item.hasRecord && !item.isPassed" class="retry-btn" @click.stop="goToDetail(item)">重新测评</button>
              <button v-if="!item.hasRecord" class="consult-btn" @click.stop="handleConsult(item)">咨询</button>
              <button v-if="item.hasPaid && !item.hasRecord" class="start-btn" @click.stop="goToDetail(item)">开始测评</button>
            </view>
          </view>
        </view>
        
        <view class="no-data" v-if="filteredAssessments.length === 0">
          <image src="/static/icons/empty.svg" class="empty-icon"></image>
          <text>暂无符合条件的测评内容</text>
        </view>
        
        <view class="no-more">—— 已到底啦~ ——</view>
        <view class="tabbar-placeholder"></view>
      </view>
    </scroll-view>

    <!-- 可滚动的列表内容 (培训) -->
    <view class="loading-box" v-if="trainingLoading && trainings.length === 0 && currentTab === 1">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    <scroll-view 
      v-if="currentTab === 1 && (!trainingLoading || trainings.length > 0)"
      class="scroll-body" 
      scroll-y 
      :style="{ top: scrollTop + 'px' }"
      :show-scrollbar="false"
      :enhanced="true"
    >
      <view class="training-list">
        <view v-for="(item, index) in filteredTrainings" :key="index">
          <!-- 1. 线下培训卡片 -->
          <view v-if="item.trainingType === 'offline'" class="training-card offline card-anim" @click="goToTrainingDetail(item)">
            <view class="card-header">
              <text class="t-title">{{ item.title }}</text>
            </view>
            <view class="tag-row">
              <text class="tag-badge type-tag">{{ getTypeLabel(item.type) }}</text>
              <text class="tag-badge category-tag">{{ getCategoryLabel(item.category) }}</text>
              <text class="tag-badge" v-for="(tag, tIdx) in item.tags" :key="tIdx">{{ tag }}</text>
            </view>
            <view class="info-list">
              <view class="info-item">
                <image src="/static/icons/location.svg" class="i-icon"></image>
                <text class="i-text">{{ item.location }}</text>
              </view>
              <view class="info-item">
                <image src="/static/icons/user.svg" class="i-icon"></image>
                <text class="i-text">主办单位：{{ item.organizer }}</text>
              </view>
              <view class="info-item">
                <image src="/static/icons/time.svg" class="i-icon"></image>
                <text class="i-text">培训时间：{{ item.trainingTime }}</text>
              </view>
              <view class="info-item">
                <image src="/static/icons/time.svg" class="i-icon"></image>
                <text class="i-text">截止时间：{{ item.deadline }}</text>
                <text v-if="item.isEnding" class="ending-tag">即将截止</text>
              </view>
            </view>
          </view>

          <!-- 2. 视频/直播培训卡片 -->
          <view v-else class="video-card card-anim" @click="goToTrainingDetail(item)">
            <view class="video-cover-wrap">
              <image :src="item.cover" mode="aspectFill" class="v-cover"></image>
              <view class="play-overlay">
                <image src="/static/icons/play_circle.svg" class="play-icon"></image>
              </view>
              <view class="v-bottom-info">
                <view class="v-info-left">
                  <view class="play-mini-icon"></view>
                  <text>{{ item.views }}</text>
                </view>
                <view class="v-info-right">
                  <image src="/static/icons/clock_mini.svg" class="m-icon"></image>
                  <text>{{ item.duration }}</text>
                </view>
              </view>
              <!-- 直播状态标签 -->
              <view v-if="item.trainingType === 'live'" class="live-status" :class="item.status">
                {{ 
                  item.status === 'streaming' ? '直播中' : 
                  item.status === 'upcoming' ? '即将开始' : 
                  item.status === 'not-started' ? '未开始' : 
                  item.status === 'finished' ? '已结束' : '直播'
                }}
              </view>
            </view>
            <view class="v-content">
              <view class="v-title-row">
                <text class="v-title">{{ item.title }}</text>
                <view v-if="item.trainingType === 'live'" class="spectators">
                   <image src="/static/icons/users_mini.svg" class="s-icon"></image>
                   <text>{{ item.spectators }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="no-data" v-if="filteredTrainings.length === 0">
          <image src="/static/icons/empty.svg" class="empty-icon"></image>
          <text>暂无符合条件的培训内容</text>
        </view>

        <view class="no-more">—— 已到底啦~ ——</view>
        <view class="tabbar-placeholder"></view>
      </view>
    </scroll-view>

    <custom-tabbar :activeIndex="1"></custom-tabbar>
  </view>

</template>

<script setup lang="js">
import { ref, computed, onMounted, watch } from 'vue';
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import CustomTabbar from '../../components/custom-tabbar/custom-tabbar.vue';
import { getAssessmentList, getTrainingList, getAssessmentRecordList } from '../../api/assessment.js';
import { getDicts } from '../../api/dict.js';
import { createOrGetSession } from '../../api/message.js';

const statusBarHeight = ref(20);
const titleBarMargin = ref(8);
const menuButtonHeight = ref(32);
const currentTab = ref(0);
const searchQuery = ref('');
const assessments = ref([]);
const trainings = ref([]); 
const loading = ref(false);
const trainingLoading = ref(false);

const passedEvaluationIds = ref(new Set());
// 所有有记录的测评ID（不管通过与否）
const hasRecordEvaluationIds = ref(new Set());
// 有记录且全部考完的测评ID（finalResult 有值）
const completedEvaluationIds = ref(new Set());

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 resolveDescription = (item, fallback = '') => {
  let desc = item.remark || item.description || item.desc;
  if (!desc && item.detail) {
    desc = /^[A-Za-z0-9+/=]+$/.test(item.detail)
      ? decodeBase64Utf8(item.detail)
      : item.detail;
  }
  return desc || fallback;
};

// 根据当前Tab显示对应的记录按钮文字
const recordText = computed(() => {
  return currentTab.value === 0 ? '测评记录' : '培训记录';
});

const fetchAssessments = async () => {
  if (loading.value) return;
  loading.value = true;
  try {
    // 检查是否有通过的记录
    const userInfo = uni.getStorageSync('userInfo') || {};
    const userId = userInfo.studentId || null;
    if (userId) {
      const recordRes = await getAssessmentRecordList(userId);
      if (recordRes.code === 200 && recordRes.data) {
        const records = recordRes.data;
        // 通过的测评
        passedEvaluationIds.value = new Set(
          records.filter(r => r.finalResult === '1').map(r => r.evaluationId)
        );
        // 所有有记录的测评
        hasRecordEvaluationIds.value = new Set(records.map(r => r.evaluationId));
        // 已完成评分的测评（finalResult 为 1 或 2）
        completedEvaluationIds.value = new Set(
          records.filter(r => r.finalResult === '1' || r.finalResult === '2').map(r => r.evaluationId)
        );
      }
    }

    const typeFilter = assessmentFilterList.value[0].selectedValue;
    const levelFilter = assessmentFilterList.value[1].selectedValue;
    const params = {
      pageNum: 1,
      pageSize: 20,
    };
    if (searchQuery.value) params.evaluationName = searchQuery.value;
    if (typeFilter) params.positionType = typeFilter;
    if (levelFilter) params.grade = levelFilter;

    const res = await getAssessmentList(params);
    if (res.code === 200 && res.rows) {
      console.log('测评API返回数据:', res.rows[0]); // 调试信息
      // 过滤掉已下架或删除的数据 (status !== '1' 的不显示)
      assessments.value = res.rows
        .filter(item => item.status === '1')
        .map(item => {
          // 处理标题显示
          let title = item.evaluationName || item.name || item.title || '未知测评';
          const desc = resolveDescription(item, '专业技能评估，助力职业发展');
          
          // 判断是否已付款（从localStorage读取支付状态）
          const hasPaid = uni.getStorageSync(`audit_paid_${item.id}`) === true;
          
          // 检查是否已投递过该岗位
          const postId = item.positionId;
          const isApplied = postId ? uni.getStorageSync(`candidate_applied_${postId}`) === true : false;

          return {
            id: item.id,
            title: title,
            level: item.gradeLabel || item.grade || '',
            type: item.positionTypeLabel || item.positionType || '',
            category: item.positionLabel || item.position || '',
            desc: desc,
            cover: item.mainImageUrl || item.coverImage || '/static/images/assessment_default.svg',
            tags: item.tags ? item.tags.split(',') : [],
            price: item.price || '',
            isCollected: false,
            collectionId: null,
            isPassed: passedEvaluationIds.value.has(item.id),
            hasRecord: hasRecordEvaluationIds.value.has(item.id),
            isCompleted: completedEvaluationIds.value.has(item.id),
            hasPaid: hasPaid,
            postId: postId,
            isApplied: isApplied,
          };
        });
    }
  } catch (err) {
    console.error('获取测评列表失败', err);
    uni.showToast({ title: '加载失败，请重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 获取培训列表
const fetchTrainings = async () => {
  if (trainingLoading.value) return;
  trainingLoading.value = true;
  try {
    const trainingTypeFilter = trainingFilterList.value[0].selectedValue;
    const jobTypeFilter = trainingFilterList.value[1].selectedValue;
    const jobNameFilter = trainingFilterList.value[2].selectedValue;
    
    const params = {
      pageNum: 1,
      pageSize: 20,
      status: 1 // 只查询已发布的
    };
    if (trainingTypeFilter) params.trainingType = trainingTypeFilter;
    if (jobTypeFilter) params.jobType = jobTypeFilter;
    if (jobNameFilter) params.job = jobNameFilter;
    if (searchQuery.value) params.name = searchQuery.value;

    const res = await getTrainingList(params);
    if (res.code === 200 && res.rows) {
      console.log('培训API返回数据:', res.rows[0]); // 调试信息
      trainings.value = res.rows.map(item => {
        console.log('培训单项数据:', item); // 调试单个培训项
        
        // 处理标题显示
        let title = item.name || item.trainingName || item.title;
        // 如果标题不存在、为空、或者是测试数据（以test_开头），则生成友好标题
        if (!title || title.trim() === '' || title.startsWith('test_')) {
          // 根据岗位生成友好标题
          const job = item.job || item.position || '专业技能';
          title = `${job}培训课程`;
        }
        const desc = resolveDescription(item, '提升专业技能，助力职业发展');
        
        // 处理培训地点
        let location = '';
        if (item.trainingType === 'offline') {
          // 线下培训拼接地址
          const city = item.city || '';
          const area = item.area || '';
          const addressDetail = item.addressDetail || '';
          location = `${city}${area}${addressDetail}`.replace(/undefined|null/g, '').trim();
          if (!location) location = '线下培训';
        } else {
          location = '线上培训';
        }
        
        // 处理培训时间
        const trainingTime = item.trainingStartTime ? 
          item.trainingStartTime.split(' ')[0] + (item.trainingEndTime ? ' 至 ' + item.trainingEndTime.split(' ')[0] : '') : 
          '';
        
        // 处理报名截止时间
        const deadline = item.applyEndTime ? item.applyEndTime.split(' ')[0] : '';
        
        return {
          id: item.id,
          title: title,
          trainingType: item.trainingType || 'offline',
          type: item.jobType || '',
          category: item.job || '',
          tags: item.tags ? item.tags.split(',') : [],
          location: location,
          organizer: item.organizer || '平台推荐',
          trainingTime: trainingTime,
          deadline: deadline,
          isEnding: false, // 可以根据applyEndTime判断是否即将截止
          cover: item.thumbnailUrl || '/static/images/training_default.svg',
          views: item.learnCount || '0',
          duration: item.duration || '',
          status: item.status === 1 ? 'published' : 'not-started',
          spectators: item.participantCount || '0',
          desc: desc,
        };
      });
    }
  } catch (err) {
    console.error('获取培训列表失败', err);
  } finally {
    trainingLoading.value = false;
  }
};

const handleTabChange = (index) => {
  currentTab.value = index;
  if (index === 0 && assessments.value.length === 0) {
    fetchAssessments();
  } else if (index === 1 && trainings.value.length === 0) {
    fetchTrainings();
  }
};

watch(currentTab, (newTab) => {
  if (newTab === 0 && assessments.value.length === 0) {
    fetchAssessments();
  } else if (newTab === 1 && trainings.value.length === 0) {
    fetchTrainings();
  }
});

const goToRecords = () => {
  uni.showToast({ title: recordText.value, icon: 'none' });
};

const goToDetail = (item) => {
  uni.navigateTo({ url: `/pages/assessment/detail?id=${item.id}` });
};

const viewAssessmentReport = (item) => {
  if (!item.isCompleted) return; // 未考完不可点击
  uni.navigateTo({ url: `/pages/assessment/report?id=${item.id}` });
};

// 投递简历：跳转到选择简历页面
const handleApply = (item) => {
  if (!item.postId) {
    uni.showToast({ title: '该测评未关联岗位，无法投递', icon: 'none' });
    return;
  }

  const userInfo = uni.getStorageSync('userInfo') || {};
  if (!userInfo.studentId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' });
    }, 1000);
    return;
  }
  
  uni.navigateTo({
      url: `/pages/my/select-resume?postId=${item.postId}`
  });
};

/**
 * 点击咨询按钮：创建/获取会话后跳转聊天页
 * @param {Object} item - 当前测评项目信息
 */
const handleConsult = async (item) => {
  // 检查登录
  const userInfo = uni.getStorageSync('userInfo') || {};
  const userId = userInfo.studentId || null;
  if (!userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' });
    }, 1000);
    return;
  }

  try {
    uni.showLoading({ title: '正在连接客服...' });
    const userName = userInfo.name || '用户';
    const userAvatar = userInfo.avatarUrl || '/static/images/user_avatar.svg';

    const res = await createOrGetSession({
      sessionType: 1,
      fromUserId: userId,
      fromUserName: userName,
      fromUserAvatar: userAvatar,
      sourceId: 'assessment_' + (item?.id || '')
    });
    uni.hideLoading();

    if (res.data) {
      const session = res.data;
      
      // 将测评信息编码后传入聊天页面，供初始卡片展示
      const assessmentTitle = encodeURIComponent(item ? (item.title || '') : '');
      const assessmentCover = encodeURIComponent(item ? (item.cover || '') : '');
      const assessmentId = item ? (item.id || '') : '';
      const assessmentLevel = encodeURIComponent(item ? (item.level || '') : '');
      const assessmentPrice = item ? (item.price || '') : '';

      uni.navigateTo({
        url: `/pages/chat/chat?sessionId=${session.sessionId}&sessionNo=${session.sessionNo || ''}&fromUserId=${userId}&userName=${encodeURIComponent(userName)}&type=assessment&title=${assessmentTitle}&cover=${assessmentCover}&assessmentId=${assessmentId}&level=${assessmentLevel}&price=${assessmentPrice}`
      });
    } else {
      uni.showToast({ title: '创建会话失败', icon: 'none' });
    }
  } catch (err) {
    uni.hideLoading();
    console.error('创建会话失败:', err);
    uni.showToast({ title: '连接失败，请重试', icon: 'none' });
  }
};

const activeFilterIndex = ref(-1);

const assessmentFilterList = ref([
  { 
    label: '岗位类型', 
    selectedLabel: '', 
    selectedValue: '',
    options: [{ label: '全部', value: '' }]
  },
  { 
    label: '岗位等级', 
    selectedLabel: '', 
    selectedValue: '',
    options: [{ label: '全部', value: '' }]
  },
  { 
    label: '岗位名称', 
    selectedLabel: '', 
    selectedValue: '',
    options: [
      { label: '全部', value: '' },
      { label: '审计岗位', value: 'audit' },
      { label: '咨询岗位', value: 'consult' },
      { label: '税务岗位', value: 'tax' }
    ]
  }
]);

const loadDicts = async () => {
  try {
    const [typeRes, levelRes] = await Promise.all([
      getDicts('main_position_type'),
      getDicts('main_position_level')
    ]);
    
    if (typeRes.code === 200) {
      const options = [
        { label: '全部', value: '' },
        ...typeRes.data.map(d => ({ label: d.dictLabel, value: d.dictValue }))
      ];
      assessmentFilterList.value[0].options = options;
      trainingFilterList.value[1].options = options;
    }
    
    if (levelRes.code === 200) {
      assessmentFilterList.value[1].options = [
        { label: '全部', value: '' },
        ...levelRes.data.map(d => ({ label: d.dictLabel, value: d.dictValue }))
      ];
    }
  } catch (e) {
    console.error('加载字典失败', e);
  }
};

const trainingFilterList = ref([
  { 
    label: '培训类型', 
    selectedLabel: '线下培训', 
    selectedValue: 'offline',
    options: [
      { label: '线下培训', value: 'offline' },
      { label: '视频培训', value: 'video' },
      { label: '直播培训', value: 'live' }
    ]
  },
  { 
    label: '职位类型', 
    selectedLabel: '', 
    selectedValue: '',
    options: [
      { label: '全部', value: '' },
      { label: '全职', value: 'full-time' },
      { label: '兼职', value: 'part-time' },
      { label: '实习', value: 'intern' }
    ]
  },
  { 
    label: '岗位', 
    selectedLabel: '', 
    selectedValue: '',
    options: [
      { label: '全部', value: '' },
      { label: '审计', value: 'audit' },
      { label: '咨询', value: 'consult' },
      { label: '税务', value: 'tax' }
    ]
  }
]);

const currentFilters = computed(() => {
    return currentTab.value === 0 ? assessmentFilterList.value : trainingFilterList.value;
});

const currentOptions = computed(() => {
  if (activeFilterIndex.value === -1) return [];
  return currentFilters.value[activeFilterIndex.value].options;
});

const toggleFilter = (index) => {
  if (activeFilterIndex.value === index) {
    activeFilterIndex.value = -1;
  } else {
    activeFilterIndex.value = index;
  }
};

const closeFilter = () => {
  activeFilterIndex.value = -1;
};

const selectOption = (opt) => {
  const filter = currentFilters.value[activeFilterIndex.value];
  filter.selectedValue = opt.value;
  filter.selectedLabel = opt.value === '' ? '' : opt.label;
  closeFilter();
  
  // 过滤变化后重新加载
  if (currentTab.value === 0) {
      fetchAssessments();
  } else {
      fetchTrainings();
  }
};

const getTypeLabel = (type) => {
  const map = { 'full-time': '全职', 'part-time': '兼职', 'intern': '实习' };
  return map[type] || type;
};

const getCategoryLabel = (cat) => {
  const map = { 'audit': '审计', 'consult': '咨询', 'tax': '税务' };
  return map[cat] || cat;
};

const filteredAssessments = computed(() => assessments.value);
const filteredTrainings = computed(() => trainings.value);

const goToTrainingDetail = (item) => {
    uni.navigateTo({ 
      url: `/pages/assessment/training-detail?type=${item.trainingType}&title=${item.title}&status=${item.status || ''}&views=${item.views || ''}&duration=${item.duration || ''}&spectators=${item.spectators || ''}` 
    });
};

const scrollTop = computed(() => {
  // 顶部渐变区：状态栏 + 胶囊栏 + 20rpx 底部间距
  const gradientHeight = statusBarHeight.value + titleBarMargin.value + menuButtonHeight.value + uni.upx2px(20);
  // 白色内容区：Tabs(84rpx) + 筛选栏(74rpx) = 158rpx
  const whiteAreaHeight = uni.upx2px(158);
  return gradientHeight + whiteAreaHeight;
});

onMounted(() => {
  // #ifdef MP-WEIXIN
  try {
    const sysInfo = uni.getSystemInfoSync();
    const menuInfo = uni.getMenuButtonBoundingClientRect();
    if (sysInfo && menuInfo) {
      statusBarHeight.value = sysInfo.statusBarHeight || 20;
      titleBarMargin.value = menuInfo.top - sysInfo.statusBarHeight;
      menuButtonHeight.value = menuInfo.height;
    }
  } catch (e) {}
  // #endif

  console.log('assessment onMounted triggered');
  loadDicts();
});

onLoad(() => {
  console.log('assessment onLoad triggered');
});

onShow(() => {
  console.log('assessment onShow triggered');
  fetchAssessments();
  fetchTrainings();
});

onPullDownRefresh(async () => {
  // 禁止下拉刷新，直接停止
  uni.stopPullDownRefresh();
});
</script>

<style lang="scss" scoped>
.container {
  width: 100%; height: 100vh; background-color: #F8F9FB; position: relative; overflow: hidden;
}

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
  padding-top: 200rpx;
  .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); }
}

.fixed-header {
  position: fixed; top: 0; left: 0; right: 0; z-index: 100;
}

.gradient-section {
  background: linear-gradient(180deg, #1F6CFF 0%, #FFFFFF 100%);
  padding: 0 40rpx 20rpx;
}

.search-bar {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(31, 108, 255, 0.1);
  margin-right: 200rpx;
  height: 100%;
  .search-icon { width: 32rpx; height: 32rpx; margin-right: 20rpx; opacity: 0.4; }
  .search-input { flex: 1; font-size: 28rpx; }
  .ph-color { color: #999; }
}

.white-section {
  background: #FFF; padding-bottom: 0;
}

.horizontal-tabs-wrap {
  display: flex; justify-content: space-between; align-items: center; padding: 20rpx 40rpx;
  .main-tabs {
    display: flex; gap: 40rpx;
    .main-tab {
      font-size: 34rpx; font-weight: bold; color: #888; position: relative; padding-bottom: 10rpx;
      &.active {
        color: #1A1A1A;
        &:after { content: ""; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%); width: 36rpx; height: 6rpx; background: #1F6CFF; border-radius: 3rpx; }
      }
    }
  }
  .record-text { font-size: 28rpx; color: #1F6CFF; }
}

.filter-row {
  display: flex; justify-content: space-between; padding: 20rpx 40rpx 20rpx;
  .filter-item {
    font-size: 28rpx; color: #333; font-weight: 500; display: flex; align-items: center;
    transition: all 0.3s;
    &.active { color: #1F6CFF; }
    .arrow-down { 
      width: 24rpx; height: 24rpx; margin-left: 8rpx; opacity: 0.3; 
      transition: transform 0.3s;
      &.rotate { transform: rotate(180deg); opacity: 0.8; }
    }
  }
}

.dropdown-wrapper {
  position: absolute; top: 100%; left: 0; right: 0; height: calc(100vh - 100%); z-index: 99;
  .mask {
    position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.4);
    animation: fadeIn 0.3s ease-out;
  }
  .dropdown-content {
    background: #FFF; position: relative; z-index: 1; border-top: 1rpx solid #F0F0F0;
    border-radius: 0 0 32rpx 32rpx; padding: 10rpx 0;
    max-height: 60vh; overflow-y: auto;
    animation: slideDown 0.3s ease-out;
    .option-item {
      display: flex; justify-content: space-between; align-items: center; 
      padding: 30rpx 40rpx; font-size: 28rpx; color: #333;
      &:active { background: #F8F9FB; }
      &.selected { color: #1F6CFF; font-weight: bold; }
      .check-icon { width: 32rpx; height: 32rpx; }
    }
  }
}

@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideDown { from { transform: translateY(-20%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

.scroll-body {
  position: fixed; left: 0; right: 0; bottom: 0; background-color: #F8F9FB;
}

.assessment-list {
  padding: 30rpx 40rpx; display: flex; flex-direction: column; gap: 30rpx;
}

.training-list {
  padding: 30rpx 40rpx; display: flex; flex-direction: column; gap: 30rpx;
}

.training-card {
  background: #FFF; border-radius: 32rpx; padding: 32rpx;
  box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.03);
  .t-title { font-size: 32rpx; font-weight: bold; color: #1A1A1A; line-height: 1.4; display: block; margin-bottom: 20rpx; }
  .tag-row {
    display: flex; gap: 10rpx; margin: 12rpx 0;
    .tag-badge { 
      font-size: 20rpx; color: #999; background: #F5F7FA; padding: 6rpx 14rpx; border-radius: 6rpx; 
      &.type-tag { color: #1F6CFF; background: rgba(31, 108, 255, 0.08); }
      &.category-tag { color: #FF9500; background: rgba(255, 149, 0, 0.08); }
    }
  }
  .info-list {
    margin-top: 24rpx; display: flex; flex-direction: column; gap: 16rpx;
    .info-item {
      display: flex; align-items: center;
      .i-icon { width: 28rpx; height: 28rpx; margin-right: 16rpx; opacity: 0.5; }
      .i-text { font-size: 26rpx; color: #666; }
      .ending-tag { font-size: 22rpx; color: #FF4D4F; margin-left: 20rpx; }
    }
  }
}

.video-card {
  background: #FFF; border-radius: 32rpx; overflow: hidden;
  box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.03);
  .video-cover-wrap {
    width: 100%; height: 380rpx; position: relative;
    .v-cover { width: 100%; height: 100%; }
    .play-overlay {
      position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
      .play-icon { width: 100rpx; height: 100rpx; opacity: 0.9; }
    }
    .v-bottom-info {
        position: absolute; left: 0; right: 0; bottom: 0; height: 80rpx;
        background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.5) 100%);
        padding: 0 24rpx; display: flex; justify-content: space-between; align-items: center;
        color: #FFF; font-size: 24rpx;
        .m-icon { width: 24rpx; height: 24rpx; margin-right: 8rpx; }
        .play-mini-icon {
          width: 0; height: 0; 
          border-left: 12rpx solid #FFF; border-top: 8rpx solid transparent; border-bottom: 8rpx solid transparent;
          margin-right: 10rpx;
        }
        .v-info-left, .v-info-right { display: flex; align-items: center; }
    }
    .live-status {
        position: absolute; right: 24rpx; top: 24rpx; border-radius: 8rpx; padding: 4rpx 12rpx; font-size: 22rpx; color: #FFF;
        &.streaming { background: #FF4D4F; }
        &.upcoming { background: #1F6CFF; }
        &.not-started { background: #999; }
        &.finished { background: #666; }
    }
  }
  .v-content {
      padding: 24rpx;
      .v-title { font-size: 32rpx; font-weight: bold; color: #1A1A1A; }
      .v-title-row { display: flex; justify-content: space-between; align-items: center; }
      .spectators {
          display: flex; align-items: center; color: #999; font-size: 24rpx;
          .s-icon { width: 24rpx; height: 24rpx; margin-right: 8rpx; }
      }
  }
}

.job-card {
  background: #FFF; border-radius: 32rpx; padding: 24rpx; display: flex;
  box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.03);
  position: relative;
  .card-left {
    width: 220rpx; height: 220rpx; flex-shrink: 0; margin-right: 24rpx;
    .cover-img { width: 100%; height: 100%; border-radius: 16rpx; }
  }
  .card-right {
    flex: 1; display: flex; flex-direction: column; justify-content: space-between;
    .top-line {
      display: flex; justify-content: space-between; align-items: center;
      .job-title { font-size: 34rpx; font-weight: bold; color: #1A1A1A; }
      .job-level-tag { font-size: 22rpx; color: #1F6CFF; background: rgba(31, 108, 255, 0.1); padding: 4rpx 12rpx; border-radius: 8rpx; }
    }
    .tag-row {
      display: flex; gap: 10rpx; margin: 12rpx 0;
      .tag-badge { 
        font-size: 20rpx; color: #999; background: #F5F7FA; padding: 6rpx 14rpx; border-radius: 6rpx; 
        &.type-tag { color: #1F6CFF; background: rgba(31, 108, 255, 0.08); }
        &.category-tag { color: #FF9500; background: rgba(255, 149, 0, 0.08); }
      }
    }
    .desc-text { font-size: 24rpx; color: #888; line-height: 1.4; margin-bottom: 16rpx; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; }
    .btn-wrap {
      display: flex; justify-content: flex-end; gap: 10rpx;
      .consult-btn {
        margin: 0; background: #FFB700; color: #FFF; border-radius: 30rpx; height: 56rpx; line-height: 56rpx; padding: 0 36rpx; font-size: 26rpx; font-weight: bold;
        &::after { border:none; }
      }
      .start-btn {
        margin: 0; background: linear-gradient(135deg, #1F6CFF 0%, #0056FF 100%); color: #FFF; border-radius: 30rpx; height: 56rpx; line-height: 56rpx; padding: 0 36rpx; font-size: 26rpx; font-weight: bold;
        &::after { border:none; }
      }
      .apply-btn {
        margin: 0; background: #1F6CFF; color: #FFF; border-radius: 30rpx; height: 56rpx; line-height: 56rpx; padding: 0 36rpx; font-size: 26rpx; font-weight: bold;
        &::after { border:none; }
      }
      .applied-btn {
        margin: 0; background: #E0E0E0; color: #999; border-radius: 30rpx; height: 56rpx; line-height: 56rpx; padding: 0 36rpx; font-size: 26rpx; font-weight: bold;
        &::after { border:none; }
      }
      .retry-btn {
        margin: 0; background: #E8F0FF; color: #2B5CFF; border-radius: 30rpx; height: 56rpx; line-height: 56rpx; padding: 0 36rpx; font-size: 26rpx; font-weight: bold;
        &::after { border:none; }
      }
      .report-btn {
        margin: 0; background: #E8F0FF; color: #2B5CFF; border-radius: 30rpx; height: 56rpx; line-height: 56rpx; padding: 0 36rpx; font-size: 26rpx; font-weight: bold;
        &::after { border:none; }
        &.disabled {
          background: #F0F2F5; color: #C0C4CC; pointer-events: none;
        }
      }
    }
  }
}

.text-ellipsis-2 {
  display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
}

.no-data {
  display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 100rpx 0;
  .empty-icon { width: 200rpx; height: 200rpx; margin-bottom: 20rpx; opacity: 0.5; }
  text { font-size: 28rpx; color: #999; }
}

.no-more {
  text-align: center; font-size: 26rpx; color: #BBB; padding: 40rpx 0;
}

.tabbar-placeholder { height: 180rpx; }

.card-anim {
  animation: fadeUp 0.6s ease-out backwards;
  @for $i from 1 through 5 { &:nth-child(#{$i}) { animation-delay: #{$i * 0.1s}; } }
}
@keyframes fadeUp {
  from { opacity: 0; transform: translateY(30rpx); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
