<template>
  <div class="content">
    <div class="grid-container">
      <!-- 左边区域 -->
      <div class="left-section">
        <!-- 上层：预警提示和系统状态左右布局 -->
        <div class="top-section">
          <HomePageWarning />
          <HomePageSystemStatus @time-range-change="handleTimeRangeChange" @date-change="handleDateChange" />
        </div>

        <!-- <div class="bottom-section"> -->
          <!-- 下层：统计卡片 -->
          <HomePageStats :type-detail-data="typeDetailData" @sort-change="handleSortChange" />
        <!-- </div> -->
      </div>

      <!-- 右边区域 -->
      <div class="right-section">
        <HomePageOverview :time-range="selectedTimeRange" :start-date="startDate" :end-date="endDate"
          :selected-role="selectedRole" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import HomePageWarning from '../pageItems/HomePageWarning.vue'
import HomePageSystemStatus from '../pageItems/HomePageSystemStatus.vue'
import HomePageStats from '../pageItems/HomePageStats.vue'
import HomePageOverview from '../pageItems/HomePageOverview.vue'
import useUserStore from '@/store/modules/user'
import oneIcon from '@/assets/icons/one.png'
import twoIcon from '@/assets/icons/two.png'
import threeIcon from '@/assets/icons/three.png'
import {
  getHomePage,
  getSeizureReport,
  getAttendanceStats,
  getAccuracyStatistics,
  getSeizureRanking,
  getCheckRanking
} from '@/api/largeScreen/largeScreen'

const userStore = useUserStore()
const userRole = userStore.roles
const currentUser = userStore.userInfo

// 角色选择相关（移植自home-new页面）
const selectedRole = ref('individual')

// 时间选择相关数据
const selectedTimeRange = ref('year')
const startDate = ref('')
const endDate = ref('')

// 数据存储
const inspectionData = ref({})
const seizeData = ref({})
const attendanceStats = ref({})
const accuracyStatistics = ref({})
const rankData = ref({
  seizeRank: 0,
  seizeModalType: 0,
  answerRank: 0,
  answerModalType: 0,
  checkRank: 0,
  checkModalType: 0
})

// 排序状态管理
const sortStates = ref({
  '查获上报': { teamSortType: 'asc', deptSortType: 'asc' },
  '抽问抽答': { teamSortType: 'asc', deptSortType: 'asc' },
  '巡检': { teamSortType: 'asc', deptSortType: 'asc' }
})

// 角色判断逻辑（移植自home-new页面）
const isTeamView = computed(() => {
  return userRole.includes('banzuzhang')
})

const isIndividualView = computed(() => {
  return userRole.includes('SecurityCheck')
})

// 判断是否为科长角色
const isKezhang = computed(() => {
  return userRole.includes('kezhang')
})

// 判断是否为测试角色
const isTestRole = computed(() => {

  return userRole.includes('test') || userRole.includes('zhijianke') || userRole.includes('kezhang') || userRole.includes('admin')
})

// TypeDetail组件数据（移植自home-new页面）
const typeDetailData = computed(() => {
  return [
    {
      title: '查获上报',
      linkText: isTestRole.value ? "" : seizePendingCount.value ? `${seizePendingCount.value}条数据待处理` : '',
      // link: isTeamView.value || isKezhang.value ? '/pages/myToDoList/index' : '/pages/voiceSubmissionDraft/index',
      statTitle: '查获数量',
      dividerIndex: 0,
      dataItems: getSeizeDataItems(),
      // rankList: getSeizeRankList(),
      departmentRank: seizeData.value.stationMasterData && seizeData.value.stationMasterData.brigadeRankings?.map(item => ({ ...item,passRate: item.seizureCount?.toFixed(2), name: item.brigadeName })) || [],
      teamRank: seizeData.value.stationMasterData && seizeData.value.stationMasterData.topThreeTeamRankings?.map(item => ({ ...item, passRate: item.seizureCount?.toFixed(2), name: item.teamName })) || [],
      bottomTeamRank: [{ passRate: 0, name: '无' }],
      teamSortType: sortStates.value['查获上报'].teamSortType,
      deptSortType: sortStates.value['查获上报'].deptSortType,
      bottomTeamRank: seizeData.value.stationMasterData && seizeData.value.stationMasterData.botomThreeTeamRankings.map(item => ({ ...item, passRate: item.seizureCount.toFixed(2), name: item.teamName })),
    },
    {
      title: '抽问抽答',
      linkText: isIndividualView.value ? accuracyStatistics.value.hasPendingTask ? '待答题' : '' : '',
      // link: '/pages/daily-exam/task-list/index',
      statTitle: '正确率',
      dividerIndex: 0,
      dataItems: getQuestionDataItems(),
      // rankList: getQuestionRankList(),
      departmentRank: accuracyStatistics.value.topDepts && accuracyStatistics.value.topDepts?.map(item => ({ ...item, passRate: item.accuracy?.toFixed(2) })) || [],
      teamRank: accuracyStatistics.value.topTeamsInSite && accuracyStatistics.value.topTeamsInSite?.map(item => ({ ...item, passRate: item.accuracy?.toFixed(2) })) || [],
      bottomTeamRank: accuracyStatistics.value.bottomTeamsInSite && accuracyStatistics.value.bottomTeamsInSite?.map(item => ({ ...item, passRate: item.accuracy?.toFixed(2)})) || [],
      teamSortType: sortStates.value['抽问抽答'].teamSortType,
      deptSortType: sortStates.value['抽问抽答'].deptSortType
    },
    {
      title: '巡检',
      linkText: isTestRole.value ? "" : inspectionData.value.toDoNumber ? `${inspectionData.value.toDoNumber}条待处理任务` : "",
      // link: '/pages/myToDoList/index',
      statTitle: '合格率',
      dividerIndex: 0,
      dataItems: getInspectionDataItems(),
      completed: inspectionData.value.doneNumber,
      pending: inspectionData.value.doingNumber,
      // rankList: getRankList(),
      departmentRank: inspectionData.value.brigadeRankingList && inspectionData.value.brigadeRankingList?.map(item => ({ ...item, passRate: (item.passRate * 100)?.toFixed(2) })) || [],
      teamRank: inspectionData.value.teamRankingList && inspectionData.value.teamRankingList?.map(item => ({ ...item, passRate: (item.passRate * 100)?.toFixed(2) })) || [],
      bottomTeamRank: [{ passRate: 0, name: '无' }],
      teamSortType: sortStates.value['巡检'].teamSortType,
      deptSortType: sortStates.value['巡检'].deptSortType,
      bottomTeamRank: inspectionData.value.reverseTeamRankingList && inspectionData.value.reverseTeamRankingList.map(item => ({ ...item, passRate: (item.passRate * 100).toFixed(2) })),
    }
  ]
})

// 待处理数量计算
const seizePendingCount = computed(() => {
  if (isIndividualView.value) {
    const { securityCheckerData } = seizeData.value;
    const { pendingCount } = securityCheckerData || {};
    return pendingCount;
  } else if (userRole.includes('kezhang')) {
    const { sectionMasterData } = seizeData.value;
    const { pendingCount } = sectionMasterData || {};
    return pendingCount;
  } else if (isTeamView.value) {
    const { teamLeaderData } = seizeData.value;
    const { pendingCount } = teamLeaderData || {}
    return pendingCount;
  }
  return 0
})



// 时间范围变化处理
const handleTimeRangeChange = (range) => {
  selectedTimeRange.value = range
  if (range !== 'custom') {

    const { startDate: newStartDate, endDate: newEndDate } = calculateDateRange(range)
    startDate.value = newStartDate
    endDate.value = newEndDate
  }
  refreshData()
}

// 日期变化处理
const handleDateChange = (dates) => {
  startDate.value = dates.startDate
  endDate.value = dates.endDate
  selectedTimeRange.value = 'custom'
  refreshData()
}

// 计算日期范围（移植自home-new页面）
const calculateDateRange = (timeRange) => {

  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);

  let originStartDate = new Date(yesterday);
  let originEndDate = new Date(yesterday);

  switch (timeRange) {
    case 'week':
      // 近一周：从7天前到昨天
      originStartDate.setDate(yesterday.getDate() - 6);
      break;
    case 'month':
      // 近一月：从30天前到昨天
      originStartDate.setDate(yesterday.getDate() - 29);
      break;
    case 'quarter':
      // 近三月：从90天前到昨天
      originStartDate.setDate(yesterday.getDate() - 89);
      break;
    case 'halfYear':
      // 近半年：从180天前到昨天
      originStartDate.setDate(yesterday.getDate() - 179);
      break;
    case 'year':
      // 近一年：从365天前到昨天
      originStartDate.setDate(yesterday.getDate() - 364);
      break;
    case 'custom':
      // 自定义时间：使用用户选择的日期
      if (startDate.value && endDate.value) {
        originStartDate = new Date(startDate.value);
        originEndDate = new Date(endDate.value);
      }
      break;
    default:
      // 默认近一周
      originStartDate.setDate(yesterday.getDate() - 364);
  }

  return {
    startDate: formatDateForInput(originStartDate),
    endDate: formatDateForInput(originEndDate)
  };
}
// 格式化日期为输入框格式
const formatDateForInput = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
// 数据获取方法（移植自home-new页面）
const getInspectionData = async () => {
  try {
    let params = {}

    if (isIndividualView.value) {
      params = { userId: currentUser.userId }
    } else {
      params = { deptId: currentUser.deptId }
    }

    const { startDate: calcStartDate, endDate: calcEndDate } = calculateDateRange(selectedTimeRange.value)

    params.startDate = calcStartDate
    params.endDate = calcEndDate

    const res = await getHomePage(params)

    inspectionData.value = res.data || {}
  } catch (error) {
    console.error("获取巡检数据失败:", error)
  }
}

const getSeizeData = async () => {
  try {
    let params = {}
    const { startDate: calcStartDate, endDate: calcEndDate } = calculateDateRange(selectedTimeRange.value)
    params.startDate = calcStartDate
    params.endDate = calcEndDate

    if (!isTestRole.value) {
      params.dataSource = selectedRole.value
    }

    const res = await getSeizureReport(params)
    seizeData.value = res.data || {}
  } catch (error) {
    console.error("获取查获数据失败:", error)
  }
}

const fetchAttendanceStats = async () => {
  try {
    let params = {}
    const { startDate: calcStartDate, endDate: calcEndDate } = calculateDateRange(selectedTimeRange.value)
    params.startDate = calcStartDate
    params.endDate = calcEndDate

    const res = await getAttendanceStats(params)
    attendanceStats.value = res.data || {}
  } catch (error) {
    console.error("获取考勤统计数据失败:", error)
  }
}

const fetchAccuracyStatistics = async () => {
  try {
    let params = {}
    const { startDate: calcStartDate, endDate: calcEndDate } = calculateDateRange(selectedTimeRange.value)
    params.startDate = calcStartDate
    params.endDate = calcEndDate
    params.dataSource = selectedRole.value
    const res = await getAccuracyStatistics(params)
    accuracyStatistics.value = res.data || {}
  } catch (error) {
    console.error("获取抽问抽答数据失败:", error)
  }
}

const getRank = async () => {
  try {
    let params = {}
    const { startDate: calcStartDate, endDate: calcEndDate } = calculateDateRange(selectedTimeRange.value)
    params.startDate = calcStartDate
    params.endDate = calcEndDate
    params.dataSource = selectedRole.value

    let idObj = {}
    if (isIndividualView.value) {
      idObj = { userId: currentUser.userId }
    } else {
      idObj = { deptId: currentUser.deptId }
    }

    const apiRequests = [getSeizureRanking(params)]

    if (!isTestRole.value) {
      apiRequests.push(getCheckRanking({ ...params, ...idObj }))
    }

    const results = await Promise.allSettled(apiRequests)
    const [seizureRes] = results

    // 处理第一个promise的结果（查获排名）
    const seizureData = seizureRes?.status === 'fulfilled' ? seizureRes.value?.data : null
    rankData.value.seizeRank = seizureData && seizureData[0]?.rank || 0
    rankData.value.seizeModalType = seizureData && seizureData[0]?.medalType || 0

    if (results.length > 1) {
      // 处理第二个promise的结果（检查排名）
      const checkResult = results[1];

      const checkData = checkResult?.status === 'fulfilled' ? checkResult.value?.data : {}
      const { checkLargeScreenHomePageRankingDto = {}, dailyTaskAccuracyRankingDto = {} } = checkData
      rankData.value.checkRank = checkLargeScreenHomePageRankingDto?.rank || 0
      rankData.value.checkModalType = checkLargeScreenHomePageRankingDto?.medalType || 0
      rankData.value.answerRank = dailyTaskAccuracyRankingDto?.rank || 0
      rankData.value.answerModalType = dailyTaskAccuracyRankingDto?.medalType || 0
    }
  } catch (error) {
    console.error("获取排名数据失败:", error)
  }
}



// 数据项获取方法（完整版，移植自home-new页面）
const getInspectionDataItems = () => {
  const { personalPassRate, teamPassRate, departmentPassRate, stationPassRate, teamRankingList, departmentRankingList } = inspectionData.value;
  if (isIndividualView.value) {
    // SecurityCheck角色：本人、班组平均数、本科平均数、本站平均数
    return [
      { label: '本人', value: ((personalPassRate || 0) * 100).toFixed(2) + '%', isImage: false },
      { label: '班组平均数', value: ((teamPassRate || 0) * 100).toFixed(2) + '%', isImage: false, color: teamPassRate < personalPassRate ? '#00AE41' : '#F96060' },
      { label: '本科平均数', value: ((departmentPassRate || 0) * 100).toFixed(2) + '%', isImage: false, color: departmentPassRate < personalPassRate ? '#00AE41' : '#F96060' },
      { label: '本站平均数', value: ((stationPassRate || 0) * 100).toFixed(2) + '%', isImage: false, color: stationPassRate < personalPassRate ? '#00AE41' : '#F96060' }
    ];
  } else if (isTeamView.value) {
    // banzuzhang角色：班组、本科平均数、本站平均数
    return [
      { label: '班组', value: ((teamPassRate || 0) * 100).toFixed(2) + '%', isImage: false },
      { label: '本科平均数', value: ((departmentPassRate || 0) * 100).toFixed(2) + '%', isImage: false, color: departmentPassRate < teamPassRate ? '#00AE41' : '#F96060' },
      { label: '本站平均数', value: ((stationPassRate || 0) * 100).toFixed(2) + '%', isImage: false, color: stationPassRate < teamPassRate ? '#00AE41' : '#F96060' }
    ];
  } else
    // if (isKezhang.value) {
    //   // kezhang角色：全科、本站平均数、前三名班组(isImage: true)
    //   return [
    //     { label: '全科', value: ((departmentPassRate || 0) * 100).toFixed(2) + '%', isImage: false },
    //     { label: '本站平均数', value: ((stationPassRate || 0) * 100).toFixed(2) + '%', isImage: false, color: stationPassRate < departmentPassRate ? '#00AE41' : '#F96060' },
    //     { label: getObjByRank(teamRankingList, 1).name, value: oneIcon, isImage: true },
    //     { label: getObjByRank(teamRankingList, 2).name, value: twoIcon, isImage: true },
    //     { label: getObjByRank(teamRankingList, 3).name, value: threeIcon, isImage: true }
    //   ];
    // } else
    if (isTestRole.value) {
      // test/zhijianke角色：全站、前三名的大队(isImage: true)
      return [
        { label: '全站', value: ((stationPassRate || 0) * 100).toFixed(2) + '%', isImage: false },
        { label: getObjByRank(departmentRankingList, 1).name, value: oneIcon, isImage: true },
        { label: getObjByRank(departmentRankingList, 2).name, value: twoIcon, isImage: true },
        { label: getObjByRank(departmentRankingList, 3).name, value: threeIcon, isImage: true }
      ];
    } else {
      // 默认角色：检查项、完成率
      return [
        { label: '检查项', value: '12', isImage: false },
        { label: '完成率', value: '92%', isImage: false }
      ];
    }
}

//获取抽问抽答
const getQuestionDataItems = () => {
  const { personalAccuracy, teamAvgAccuracy, deptAvgAccuracy, siteAvgAccuracy, topDepts, topTeamsInDept } = accuracyStatistics.value;
  if (isIndividualView.value) {
    // SecurityCheck角色：本人、班组平均数、本科平均数、本站平均数
    return [
      { label: '本人', value: (personalAccuracy || 0) + '%', isImage: false },
      { label: '班组平均数', value: (teamAvgAccuracy || 0) + '%', isImage: false, color: teamAvgAccuracy < personalAccuracy ? '#00AE41' : '#F96060' },
      { label: '本科平均数', value: (deptAvgAccuracy || 0) + '%', isImage: false, color: deptAvgAccuracy < personalAccuracy ? '#00AE41' : '#F96060' },
      { label: '本站平均数', value: (siteAvgAccuracy || 0) + '%', isImage: false, color: siteAvgAccuracy < personalAccuracy ? '#00AE41' : '#F96060' }
    ];
  } else if (isTeamView.value) {
    // banzuzhang角色：班组、本科平均数、本站平均数
    return [
      { label: '班组', value: (teamAvgAccuracy || 0) + '%', isImage: false },
      { label: '本科平均数', value: (deptAvgAccuracy || 0) + '%', isImage: false, color: deptAvgAccuracy < teamAvgAccuracy ? '#00AE41' : '#F96060' },
      { label: '本站平均数', value: (siteAvgAccuracy || 0) + '%', isImage: false, color: siteAvgAccuracy < teamAvgAccuracy ? '#00AE41' : '#F96060' }
    ];
  } else
    // if (isKezhang.value) {
    //   // kezhang角色：全科、本站平均数、前三名班组(isImage: true)
    //   return [
    //     { label: '全科', value: (deptAvgAccuracy || 0) + '%', isImage: false, },
    //     { label: '本站平均数', value: (siteAvgAccuracy || 0) + '%', isImage: false, color: siteAvgAccuracy < deptAvgAccuracy ? '#00AE41' : '#F96060' },
    //     { label: getObjByRank(topTeamsInDept, 1).teamName, value: oneIcon, isImage: true },
    //     { label: getObjByRank(topTeamsInDept, 2).teamName, value: twoIcon, isImage: true },
    //     { label: getObjByRank(topTeamsInDept, 3).teamName, value: threeIcon, isImage: true }
    //   ];
    // } else 
    if (isTestRole.value) {
      // test/zhijianke角色：全站、前三名的大队(isImage: true)
      return [
        { label: '全站', value: (siteAvgAccuracy || 0) + '%', isImage: false },
        { label: getObjByRank(topDepts, 1).name, value: oneIcon, isImage: true },
        { label: getObjByRank(topDepts, 2).name, value: twoIcon, isImage: true },
        { label: getObjByRank(topDepts, 3).name, value: threeIcon, isImage: true }
      ];
    } else {
      // 默认角色：检查项、完成率
      return [

      ];
    }
}

//根据角色获取查获数据项目组
const getSeizeDataItems = () => {
  
  if (isIndividualView.value) {
    // SecurityCheck角色：从securityCheckerData解构
    const { securityCheckerData } = seizeData.value;
    const { selfSeizureCount, teamAverage, departmentAverage, stationAverage } = securityCheckerData || {}

    // SecurityCheck角色：本人、班组平均数、本科平均数、本站平均数
    return [
      { label: '本人', value: selfSeizureCount || 0, isImage: false },
      { label: '班组平均数', value: teamAverage || 0, isImage: false, color: teamAverage < selfSeizureCount ? '#00AE41' : '#F96060' },
      { label: '本科平均数', value: departmentAverage || 0, isImage: false, color: departmentAverage < selfSeizureCount ? '#00AE41' : '#F96060' },
      { label: '本站平均数', value: (stationAverage && stationAverage.toFixed(2)) || 0, isImage: false, color: stationAverage < selfSeizureCount ? '#00AE41' : '#F96060' }
    ];
  } else if (isTeamView.value) {
    // banzuzhang角色：从teamLeaderData解构
    const { teamLeaderData } = seizeData.value;
    const { departmentAverage, stationAverage, teamAverage } = teamLeaderData || {};
    // banzuzhang角色：班组、本科平均数、本站平均数
    return [
      { label: '班组', value: teamAverage || 0, isImage: false },
      { label: '本科平均数', value: departmentAverage || 0, isImage: false, color: departmentAverage < teamAverage ? '#00AE41' : '#F96060' },
      { label: '本站平均数', value: (stationAverage && stationAverage.toFixed(2)) || 0, isImage: false, color: stationAverage < teamAverage ? '#00AE41' : '#F96060' }
    ];
  } else
    // if (isKezhang.value) {
    //   // kezhang角色：从securityCheckerData解构
    //   const { sectionMasterData } = seizeData.value;
    //   const { stationAverage, topThreeTeams, departmentAverage } = sectionMasterData || {}

    //   // kezhang角色：全科、本站平均数、前三名班组(isImage: true)
    //   return [
    //     { label: '全科', value: departmentAverage || 0, isImage: false },
    //     { label: '本站平均数', value: stationAverage?.toFixed(2) || 0, isImage: false, color: stationAverage?.toFixed(2) < departmentAverage ? '#00AE41' : '#F96060' },
    //     { label: getObjByRank(topThreeTeams, 1).teamName, value: oneIcon, isImage: true },
    //     { label: getObjByRank(topThreeTeams, 2).teamName, value: twoIcon, isImage: true },
    //     { label: getObjByRank(topThreeTeams, 3).teamName, value: threeIcon, isImage: true }
    //   ];
    // } else
    if (isTestRole.value) {
      // test/zhijianke角色：从securityCheckerData解构
      const { stationMasterData } = seizeData.value;
      const { totalStationSeizure, brigadeRankings } = stationMasterData || {}

      // 对departmentRankings数组按照seizureCount由大到小排序
      const sortedDepartmentRankings = Array.isArray(brigadeRankings)
        ? [...brigadeRankings].sort((a, b) => (b.seizureCount || 0) - (a.seizureCount || 0))
        : [];

      if (sortedDepartmentRankings.length == 0) {
        return []
      }
      // test/zhijianke角色：全站、前三名的大队(isImage: true)
      return [
        { label: '全站', value: totalStationSeizure || 0, isImage: false },
        { label: sortedDepartmentRankings[0].brigadeName, value: oneIcon, isImage: true },
        { label: sortedDepartmentRankings[1].brigadeName, value: twoIcon, isImage: true },
        { label: sortedDepartmentRankings[2].brigadeName, value: threeIcon, isImage: true }
      ];
    } else {
      // 默认角色：检查项、完成率
      return [
        { label: '检查项', value: '12', isImage: false },
        { label: '完成率', value: '92%', isImage: false }
      ];
    }
}

// 根据角色获取巡检排名列表
const getRankList = () => {
  const { teamRanking, teamTotal, departmentRanking, departmentTotal, stationRanking, stationTotal } = inspectionData.value;
  // 根据角色返回不同的排名数据
  if (isIndividualView.value) {
    // 科长、SecurityCheck角色：显示班组、科级和站级排名
    return [
      { label: '班组排名', current: teamRanking || 0, total: teamTotal || 0, percentage: teamTotal ? ((teamRanking || 0) / teamTotal) * 100 : 0 },
      { label: '科级排名', current: departmentRanking || 0, total: departmentTotal || 0, percentage: departmentTotal ? ((departmentRanking || 0) / departmentTotal) * 100 : 0 },
      { label: '站级排名', current: stationRanking || 0, total: stationTotal || 0, percentage: stationTotal ? ((stationRanking || 0) / stationTotal) * 100 : 0, type: 'station' }
    ];
  } else if (isKezhang.value) {
    return [
      { label: '站级排名', current: stationRanking || 0, total: stationTotal || 0, percentage: stationTotal ? ((stationRanking || 0) / stationTotal) * 100 : 0, type: 'station' }
    ];
  } else if (isTeamView.value) {
    // 班组长角色：显示科级和站级排名
    return [
      { label: '科级排名', current: departmentRanking || 0, total: departmentTotal || 0, percentage: departmentTotal ? ((departmentRanking || 0) / departmentTotal) * 100 : 0 },
      { label: '站级排名', current: stationRanking || 0, total: stationTotal || 0, percentage: stationTotal ? ((stationRanking || 0) / stationTotal) * 100 : 0, type: 'station' }
    ];
  } else {
    // 默认角色：显示个人排名
    return [];
  }
}

//获取抽问抽答排名
const getQuestionRankList = () => {
  // 根据角色返回不同的排名数据
  if (isIndividualView.value) {
    const { teamRanking, deptRanking, siteRanking } = accuracyStatistics.value;
    // 科长、SecurityCheck角色：显示班组、科级和站级排名
    return [
      { label: '班组排名', current: teamRanking?.rank || 0, total: teamRanking?.total || 0, percentage: teamRanking?.total ? ((teamRanking.rank || 0) / teamRanking.total) * 100 : 0 },
      { label: '科级排名', current: deptRanking?.rank || 0, total: deptRanking?.total || 0, percentage: deptRanking?.total ? ((deptRanking.rank || 0) / deptRanking.total) * 100 : 0 },
      { label: '站级排名', current: siteRanking?.rank || 0, total: siteRanking?.total || 0, percentage: siteRanking?.total ? ((siteRanking.rank || 0) / siteRanking.total) * 100 : 0, type: 'station' }
    ];
  } else if (isKezhang.value) {
    const { deptInSiteRanking } = accuracyStatistics.value;
    return [
      { label: '站级排名', current: deptInSiteRanking?.rank || 0, total: deptInSiteRanking?.total || 0, percentage: deptInSiteRanking?.total ? ((deptInSiteRanking?.rank || 0) / deptInSiteRanking?.total) * 100 : 0, type: 'station' }
    ];
  } else if (isTeamView.value) {
    const { teamInDeptRanking, teamInSiteRanking } = accuracyStatistics.value;
    // 班组长角色：显示科级和站级排名
    return [
      { label: '科级排名', current: teamInDeptRanking?.rank || 0, total: teamInDeptRanking?.total || 0, percentage: teamInDeptRanking?.total ? ((teamInDeptRanking.rank || 0) / teamInDeptRanking.total) * 100 : 0 },
      { label: '站级排名', current: teamInSiteRanking?.rank || 0, total: teamInSiteRanking?.total || 0, percentage: teamInSiteRanking?.total ? ((teamInSiteRanking.rank || 0) / teamInSiteRanking.total) * 100 : 0, type: 'station' }
    ];
  } else {
    // 默认角色：显示个人排名
    return [];
  }
}

// 根据角色获取巡检排名列表
const getSeizeRankList = () => {
  // 根据角色返回不同的排名数据
  if (isIndividualView.value) {
    const { securityCheckerData } = seizeData.value;
    const { teamRanking, departmentRanking, stationRanking } = securityCheckerData || {}
    // 科长、SecurityCheck角色：显示班组、科级和站级排名
    return [
      { label: '班组排名', current: teamRanking?.currentRank || 0, total: teamRanking?.totalItems || 0, percentage: teamRanking?.totalItems ? ((teamRanking.currentRank || 0) / teamRanking.totalItems) * 100 : 0 },
      { label: '科级排名', current: departmentRanking?.currentRank || 0, total: departmentRanking?.totalItems || 0, percentage: departmentRanking?.totalItems ? ((departmentRanking.currentRank || 0) / departmentRanking.totalItems) * 100 : 0 },
      { label: '站级排名', current: stationRanking?.currentRank || 0, total: stationRanking?.totalItems || 0, percentage: stationRanking?.totalItems ? ((stationRanking.currentRank || 0) / stationRanking.totalItems) * 100 : 0, type: 'station' }
    ];
  } else if (isKezhang.value) {
    const { sectionMasterData } = seizeData.value;
    const { stationRanking } = sectionMasterData || {};
    // 科长、SecurityCheck角色：显示班组、科级和站级排名
    return [
      { label: '站级排名', current: stationRanking?.currentRank || 0, total: stationRanking?.totalItems || 0, percentage: stationRanking?.totalItems ? ((stationRanking.currentRank || 0) / stationRanking.totalItems) * 100 : 0, type: 'station' }
    ];
  } else if (isTeamView.value) {
    const { teamLeaderData } = seizeData.value;
    const { departmentRanking, stationRanking } = teamLeaderData || {}
    // 班组长角色：显示科级和站级排名
    return [
      { label: '科级排名', current: departmentRanking?.currentRank || 0, total: departmentRanking?.totalItems || 0, percentage: departmentRanking?.totalItems ? ((departmentRanking.currentRank || 0) / departmentRanking.totalItems) * 100 : 0 },
      { label: '站级排名', current: stationRanking?.currentRank || 0, total: stationRanking?.totalItems || 0, percentage: stationRanking?.totalItems ? ((stationRanking.currentRank || 0) / stationRanking.totalItems) * 100 : 0, type: 'station' }
    ];
  } else {
    // 默认角色：显示个人排名
    return [];
  }
}

// 辅助方法：根据排名获取对象
const getObjByRank = (arr, rank) => {
  if (!Array.isArray(arr)) return {}
  let res = arr.find(item => item.rank == rank)
  return res || {}
}

// 处理排序变化
const handleSortChange = (title, type, sortType) => {
  if (sortStates.value[title]) {
    if (type === 'team') {
      sortStates.value[title].teamSortType = sortType
    } else if (type === 'dept') {
      sortStates.value[title].deptSortType = sortType
    }
  }
}

// 刷新数据
const refreshData = async () => {
  await Promise.allSettled([
    getInspectionData(),
    getSeizeData(),
    fetchAttendanceStats(),
    fetchAccuracyStatistics(),
    getRank()
  ])
}

onMounted(async () => {
  // 初始化时间范围
  const { startDate: initStartDate, endDate: initEndDate } = calculateDateRange(selectedTimeRange.value)
  startDate.value = initStartDate
  endDate.value = initEndDate

  // 获取初始数据
  await refreshData()


})
</script>

<style lang="scss" scoped>
.content {
  height: 100%;
  // background: linear-gradient(135deg, #0E4B71 0%, #037599 100%);
  color: #fff;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;

  .grid-container {
    height: 100%;
    display: flex;
    gap: 20px;

    .left-section {
      flex: 2;
      display: flex;
      flex-direction: column;
      gap: 15px;
      overflow: hidden; /* 添加溢出控制 */

      .top-section {
        flex: 0.33; /* 降低上层区域高度比例 */
        display: flex;
        gap: 15px;
        min-height: 150px; /* 设置最小高度 */

        &>* {
          flex: 1;
        }
      }

      /* 为HomePageStats组件设置明确的高度比例 */
      & > :last-child {
        flex: 0.67; /* 增加下层区域高度比例 */
        height: 100%;
        overflow: hidden; /* 防止内容溢出 */
      }
    }

    .right-section {
      flex: 0.7;
      height: 100%;
    }
  }
}
</style>
