<template>
  <BasicLayout>
    <view class="container">
      <uni-card :is-shadow="false" is-full>
        <view class="header">
          <text class="score">我的得分: {{ totalScore }}</text>
          <view class="status">
            <text>我的状态: </text>
            <view class="status-indicator"></view>
            <view class="review-count" v-if="reviewingCountComputed > 0">
              {{ reviewingCountComputed }}项在审核
            </view>
          </view>
        </view>
      </uni-card>

      <uni-card :is-shadow="false" is-full margin="10px 0 0 0">
        <view class="list-header">
          <text class="category-header">分类</text>
          <text class="value-header">分值</text>
        </view>
        <view v-if="loading" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>
        <view
          v-else
          class="list-item"
          v-for="(item, index) in evaluationItems"
          :key="index"
        >
          <view
            class="flex-row items-center justify-between w-full"
            @click="handleItemClick(item)"
          >
            <view class="category-name">{{ item.category }}</view>
            <view class="flex-row items-center">
              <text class="value">{{ item.value }}</text>
              <view class="review-badge" v-if="item.isUnderReview">审</view>
              <u-icon name="arrow-right" size="16" color="#999"></u-icon
            ></view>
          </view>
        </view>
      </uni-card>
    </view>
    <template #bottom>
      <view class="white-bg-color py-5">
        <view class="flex-row items-center pb-10 pt-5">
          <u-button
            text="个人荣誉申请"
            class="ml-15 mr-7"
            type="primary"
            @click="scgrry"
          />
          <u-button
            text="公开课获奖申请"
            class="mr-15 mr-7"
            type="primary"
            @click="scgkkhj"
          />
        </view>
      </view>
    </template>
  </BasicLayout>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { jsFindPageJfApi, inspectItemFindAllApi } from "@/api/base/server";

// 响应式数据
const evaluationItems = ref([]);
const totalScore = ref(0);
const loading = ref(false);

// 计算正在审核的项目数量
const reviewingCountComputed = computed(() => {
  return evaluationItems.value.filter(item => item.isUnderReview).length;
});

// 获取检查项数据
const loadInspectItems = async () => {
  try {
    const res = await inspectItemFindAllApi({ type: 2 });
    if (res && res.resultCode === 1 && res.result) {
      return res.result;
    }
    return [];
  } catch (error) {
    console.error('获取检查项失败:', error);
    return [];
  }
};

// 获取教师积分数据
const loadTeacherScore = async () => {
  loading.value = true;
  try {
    // 从本地缓存获取当前教师ID
    const userDataStr = uni.getStorageSync('app-user');
    let teacherId = '';
    let userData = null;
    
    if (userDataStr) {
      try {
        userData = typeof userDataStr === 'string' ? JSON.parse(userDataStr) : userDataStr;
        if (userData && userData.jsData && userData.jsData.id) {
          teacherId = userData.jsData.id;
          console.log('当前教师ID:', teacherId);
          console.log('教师信息:', userData.jsData);
        } else {
          console.error('未找到教师ID信息');
          uni.showToast({
            title: '未找到教师信息',
            icon: 'none'
          });
          return;
        }
      } catch (error) {
        console.error('解析用户数据失败:', error);
        uni.showToast({
          title: '用户数据解析失败',
          icon: 'none'
        });
        return;
      }
    } else {
      console.error('未找到用户数据');
      uni.showToast({
        title: '未找到用户数据',
        icon: 'none'
      });
      return;
    }
    
    // 设置查询参数，获取当前教师的积分数据
    const params = {
      startTime: new Date().getFullYear() + '-01-01', // 当年开始时间
      endTime: new Date().getFullYear() + '-12-31',   // 当年结束时间
      pageSize: 100, // 增大页面大小，确保能获取到当前教师数据
      pageNum: 1,
      id: teacherId // 使用教师ID过滤
    };
    
    const res = await jsFindPageJfApi(params);
    console.log('查询参数:', params);
    console.log('当前教师ID:', teacherId);
    console.log('API返回结果:', res);
    
    if (res && res.rows && res.rows.length > 0) {
      // 查找当前教师的数据
      const teacherData = res.rows.find(row => row.id === teacherId);
      
      if (!teacherData) {
        console.warn('未找到当前教师的积分数据');
        uni.showToast({
          title: '未找到积分数据',
          icon: 'none'
        });
        return;
      }
      
      console.log('找到的教师积分数据:', teacherData);
      console.log('教师姓名:', teacherData.jsxm);
      console.log('总分:', teacherData.totalScore);
      console.log('积分汇总数据:', teacherData.summaries);
      
      // 获取检查项数据
      const inspectItems = await loadInspectItems();
      
      if (inspectItems.length === 0) {
        console.warn('未获取到检查项数据');
        return;
      }
      
      console.log('检查项数据:', inspectItems);
      
      // 构建评价项目数据，参考后端界面的getScore方法
      const items = [];
      let total = 0;
      
      console.log('检查项数据:', inspectItems);
      console.log('教师积分汇总:', teacherData.summaries);
      
      inspectItems.forEach((item, index) => {
        // 参考后端界面的getScore方法逻辑
        let score = 0;
        let num = 0;
        
        if (teacherData.summaries && teacherData.summaries.length > 0) {
          for (let i = 0; i < teacherData.summaries.length; i++) {
            const summaryId = teacherData.summaries[i].inspectItemId;
            const itemId = item.id;
            
            // 使用宽松比较，并考虑大小写
            if (summaryId == itemId || summaryId?.toUpperCase() == itemId?.toUpperCase()) {
              score = parseFloat(teacherData.summaries[i].score) || 0;
              num = parseInt(teacherData.summaries[i].num) || 0;
              console.log(`✅ 匹配成功: ${item.name}, score=${score}, num=${num}`);
              break;
            }
          }
        }
        
        items.push({
          id: item.id,
          category: item.name,
          value: score,
          isUnderReview: num > 0, // 如果有记录数，说明在审核中
          num: num
        });
        
        total += score;
      });
      
      evaluationItems.value = items;
      totalScore.value = total;
      
      console.log('处理后的积分数据:', {
        items: items,
        totalScore: total,
        reviewingCount: reviewingCountComputed.value
      });
    } else {
      console.warn('查询结果为空或格式不正确');
      uni.showToast({
        title: '未获取到积分数据',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取教师积分失败:', error);
    uni.showToast({
      title: '获取积分数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

function handleItemClick(item: any) {
  // 检查该项积分是否为0
  if (!item.value || item.value === 0 || item.value === '0' || item.value === 0.0 || item.value === null || item.value === undefined) {
    uni.showToast({
      title: '积分为0',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
  const url = `/pages/view/routine/JiFenPingJia/detail?inspectItemId=${item.id}`;
  uni.navigateTo({
    url: url,
  });
}

function scgrry() {
  uni.navigateTo({
    url: `/pages/view/routine/JiFenPingJia/PersonalHonor`,
  });
}

function scgkkhj() {
  uni.navigateTo({
    url: `/pages/view/routine/JiFenPingJia/PublicClassAwards`,
  });
}

// 页面加载时获取数据
onMounted(() => {
  loadTeacherScore();
});
</script>

<style scoped lang="scss">
.container {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding: 15px;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0; // Adjusted padding
  font-size: 16px;
}

.score {
  color: #333;
  font-weight: bold;
}

.status {
  display: flex;
  align-items: center;
  color: #666;
}

.status-indicator {
  width: 12px;
  height: 12px;
  background-color: #4caf50; // Green color from the image
  margin-left: 8px;
  border-radius: 2px; // Slightly rounded corners
}

.review-count {
  background-color: #fff2e8;
  color: #ff6b35;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 12px;
  border: 1px solid #ff6b35;
  font-weight: bold;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text {
  color: #999;
  font-size: 28rpx;
}

// Remove default card padding if needed
::v-deep .uni-card .uni-card__content {
  padding: 10px 15px !important; // Overwrite default padding
}

.list-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 0; // Adjust padding as needed
  border-bottom: 1px solid #eee;
  color: #666;
  font-size: 14px;
}

.category-header {
  flex: 3; // Give more space to category
}

.value-header {
  flex: 1;
  text-align: right;
}

.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0; // Vertical padding for spacing
  border-bottom: 1px solid #eee;
  font-size: 14px;

  &:last-child {
    border-bottom: none; // Remove border for the last item
  }
}

.category-name {
  flex: 3; // Corresponds to header
  color: #333;
}

.value {
  flex: 1; // Corresponds to header
  text-align: right;
  color: #333;
  font-weight: 500;
}

.review-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  background-color: #ff6b35;
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
  border-radius: 50%;
  margin-left: 8px;
  margin-right: 8px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 107, 53, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(255, 107, 53, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 107, 53, 0);
  }
}
</style>
