<template>
  <view class="result-container" v-if="!loading">
    <!-- 自定义导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <image src="/static/icons/arrow_left.svg" class="nav-back-icon" mode="aspectFit"></image>
      </view>
      <text class="nav-title">测评结果</text>
      <view class="nav-placeholder"></view>
    </view>

    <!-- 1. 结果状态区 -->
    <view class="status-card">
      <view class="result-icon-wrap" :class="resultData.finalResult === '1' ? 'pass' : 'fail'">
        <view v-if="resultData.finalResult === '1'" class="css-check"></view>
        <view v-else class="css-cross"></view>
      </view>
      <text class="status-title">{{ resultData.finalResult === '1' ? '恭喜你！达到投递标准' : '很遗憾！未达到投递标准' }}</text>
      
      <view class="action-btns">
        <button v-if="resultData.finalResult === '2'" class="btn-retry" @click="goToAssessment">去练习</button>
        <button class="btn-report" @click="viewReport">查看报告</button>
      </view>
    </view>

    <!-- 2. 能力分布 -->
    <view class="chart-card">
      <view class="card-title">测评情况</view>
      <view class="ability-list">
        <view v-for="(item, index) in resultData.abilityResults" :key="index" class="ability-item">
          <text class="name">{{ item.name }}</text>
          <view class="score-wrap">
            <text class="score" :class="item.isPass ? 'pass' : 'fail'">{{ item.score }}分</text>
            <text class="status-symbol" :class="item.isPass ? 'pass' : 'fail'">{{ item.isPass ? '√' : '×' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 3. 培训推荐 (仅在未通过时显示) -->
    <view v-if="resultData.finalResult === '2'" class="training-recommend">
      <view class="section-title">培训推荐</view>
      <view class="training-list">
        <view 
          v-for="(item, index) in trainingList" 
          :key="index" 
          class="training-card offline" 
          @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>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getEvaluationResult, getTrainingList } from '../../api/assessment.js'

const loading = ref(true)
const resultData = ref({})
const trainingList = ref([])
const assessmentId = ref('')

onLoad(async (options) => {
  // 兼容不同的参数名
  assessmentId.value = options.id || options.assessmentId || ''
  if (!assessmentId.value || assessmentId.value === 'undefined') {
    uni.showToast({ title: '测评ID缺失', icon: 'none' })
    return
  }
  await loadData()
})

const loadData = async () => {
  if (!assessmentId.value || assessmentId.value === 'undefined') return
  try {
    const userInfo = uni.getStorageSync('userInfo') || {}
    const studentId = userInfo.studentId || userInfo.id
    if (!studentId) {
      uni.showToast({ title: '登录信息失效', icon: 'none' })
      return
    }
    const res = await getEvaluationResult(assessmentId.value, studentId)
    if (res.code === 200) {
      resultData.value = res.data
      // 无论通过与否，都加载培训推荐作为兜底
      loadTrainings()
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const resolveDescription = (item, fallback = '') => {
  return item.remark || item.description || item.desc || fallback;
};

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 loadTrainings = async () => {
  try {
    const res = await getTrainingList({ pageNum: 1, pageSize: 5, status: 1 })
    if (res.code === 200 && res.rows) {
      trainingList.value = res.rows.map(item => {
        let title = item.name || item.trainingName || item.title;
        if (!title || title.trim() === '' || title.startsWith('test_')) {
          const job = item.job || item.position || '专业技能';
          title = `${job}培训课程`;
        }
        
        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] : '') : 
          '';
        
        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,
          mainImage: item.thumbnailUrl || '/static/images/training_default.svg',
        };
      });
    }
  } catch (e) {
    console.error('加载培训列表失败:', e)
  }
}

const goToAssessment = () => {
  if (!assessmentId.value || assessmentId.value === 'undefined') {
    uni.navigateBack()
    return
  }
  uni.redirectTo({
    url: `/pages/common/webview?mode=kaoshixing&assessmentId=${encodeURIComponent(assessmentId.value)}`
  })
}

const viewReport = () => {
  if (!assessmentId.value || assessmentId.value === 'undefined') {
    uni.showToast({ title: '参数错误', icon: 'none' })
    return
  }
  // 直接跳转到本地原生的图形化报告页 report.vue
  uni.navigateTo({
    url: `/pages/assessment/report?id=${assessmentId.value}`
  })
}

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

const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.result-container { padding: 0 30rpx 30rpx; background-color: #f8f9fb; min-height: 100vh; }

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 10rpx;
  margin-bottom: 16rpx;
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #f8f9fb;
}
.nav-back {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.nav-back-icon {
  width: 40rpx;
  height: 40rpx;
}
.nav-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #1A1A1A;
}
.nav-placeholder {
  width: 64rpx;
}
.status-card { background: #fff; border-radius: 20rpx; padding: 60rpx 40rpx; display: flex; flex-direction: column; align-items: center; margin-bottom: 30rpx; }

/* 结果图标样式 */
.result-icon-wrap {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
  &.pass { background-color: #52c41a; }
  &.fail { background-color: #ff4d4f; }
}
.css-check {
  width: 50rpx;
  height: 25rpx;
  border-left: 6rpx solid #fff;
  border-bottom: 6rpx solid #fff;
  transform: rotate(-45deg);
  margin-top: -10rpx;
}
.css-cross {
  position: relative;
  width: 50rpx;
  height: 50rpx;
  &::before, &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 6rpx;
    background-color: #fff;
    border-radius: 3rpx;
  }
  &::before { transform: rotate(45deg); }
  &::after { transform: rotate(-45deg); }
}

.status-title { font-size: 34rpx; font-weight: bold; margin-bottom: 50rpx; }
.action-btns { display: flex; width: 100%; gap: 20rpx; }
.btn-retry { flex: 1; background: #e8f0ff; color: #2b5cff; border-radius: 40rpx; font-size: 28rpx; height: 80rpx; line-height: 80rpx; }
.btn-report { flex: 1; background: #2b5cff; color: #fff; border-radius: 40rpx; font-size: 28rpx; height: 80rpx; line-height: 80rpx; }

.chart-card { background: #fff; border-radius: 20rpx; padding: 30rpx; margin-bottom: 30rpx; }
.card-title { font-size: 30rpx; font-weight: bold; margin-bottom: 30rpx; }
.ability-list { display: grid; grid-template-columns: 1fr 1fr; gap: 20rpx; }
.ability-item { padding: 20rpx; background: #f8f9fb; border-radius: 12rpx; display: flex; flex-direction: column; gap: 10rpx; }
.ability-item .name { font-size: 26rpx; color: #666; }
.score-wrap { display: flex; align-items: center; justify-content: space-between; }
.score { font-size: 32rpx; font-weight: bold; }
.score.pass { color: #52c41a; }
.score.fail { color: #ff4d4f; }
.status-symbol { font-size: 28rpx; font-weight: bold; }
.status-symbol.pass { color: #52c41a; }
.status-symbol.fail { color: #ff4d4f; }

.training-recommend { margin-top: 40rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 20rpx; }

/* 培训卡片样式 - 同首页 */
.training-card {
  background: #FFF; border-radius: 32rpx; padding: 32rpx; margin-bottom: 20rpx;
  box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.03);
}
.training-card .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; 
}
.tag-badge.type-tag { color: #1F6CFF; background: rgba(31, 108, 255, 0.08); }
.tag-badge.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; }
</style>