<template>
  <HomeContainer>
    <!-- 时间范围显示 -->
    <!-- <view v-if="startDate && endDate" class="time-range-display">
      <text class="time-range-text">时间范围：{{ startDate }} 至 {{ endDate }}</text>
    </view> -->

    <!-- 统计表格区域 -->
    <view class="statistic-tables-section">
      <!-- 查获数量统计表格 -->
      <StatisticTable title="查获数量" :columns="seizureColumns" :data="seizureTableData" :blankData="'0'"
        class="statistic-table" />

      <!-- 在岗时长统计表格 -->
      <StatisticTable title="在岗时长" :columns="workingColumns" :data="workingTableData" :blankData="'0'"
        class="statistic-table" />

      <!-- 巡检合格率统计表格 -->
      <StatisticTable title="巡检合格率" :columns="inspectionColumns" :data="inspectionTableData" :blankData="'0'"
        class="statistic-table" />

      <!-- 抽问抽答正确率统计表格 -->
      <StatisticTable title="抽问抽答正确率" :columns="questionColumns" :data="questionTableData" :blankData="'0'"
        class="statistic-table" />

      <!-- 培训答题分数统计表格 -->
      <StatisticTable title="培训答题分数" :columns="learningColumns" :data="learningTableData" :blankData="'0'"
        class="statistic-table" />
    </view>
  </HomeContainer>
</template>

<script>
import HomeContainer from '@/components/HomeContainer.vue'
import HeadTitle from '@/components/HeadTitle.vue'
import StatisticTable from '@/components/statistic-table/statistic-table.vue'
import { getHomeReportWhole } from '@/api/home-new/home-new.js'
export default {
  name: 'StatisticalReport',
  components: {
    HomeContainer,
    HeadTitle,
    StatisticTable
  },
  data() {
    return {
      // 时间参数
      startDate: '',
      endDate: '',
      // 表格列配置
      seizureColumns: [
        { props: 'name', title: '查获数量' },
        { props: 'totalNumber', title: '总数' },
        { props: 'averageNumber', title: '平均数' },
        { props: 'medianNumber', title: '中位数' },
        { props: 'maxNumber', title: '最大值' },
        { props: 'minNumber', title: '最小值' }
      ],
      workingColumns: [
        { props: 'name', title: '在岗时长' },
        { props: 'totalNumber', title: '总数' },
        { props: 'averageNumber', title: '平均数' },
        { props: 'medianNumber', title: '中位数' },
        { props: 'maxNumber', title: '最大值' },
        { props: 'minNumber', title: '最小值' }
      ],
      inspectionColumns: [
        { props: 'name', title: '巡检合格率(%)' },
        // { props: 'totalNumber', title: '总数' },
        { props: 'averageNumber', title: '平均数' },
        { props: 'medianNumber', title: '中位数' },
        { props: 'maxNumber', title: '最大值' },
        { props: 'minNumber', title: '最小值' }
      ],
      questionColumns: [
        { props: 'name', title: '抽问抽答正确率(%)' },
        // { props: 'totalNumber', title: '总数' },
        { props: 'averageNumber', title: '平均数' },
        { props: 'medianNumber', title: '中位数' },
        { props: 'maxNumber', title: '最大值' },
        { props: 'minNumber', title: '最小值' }
      ],
      learningColumns: [
        { props: 'name', title: '培训答题分数' },
        // { props: 'totalNumber', title: '总数' },
        { props: 'averageNumber', title: '平均数' },
        { props: 'medianNumber', title: '中位数' },
        { props: 'maxNumber', title: '最大值' },
        { props: 'minNumber', title: '最小值' }
      ],
      // 统计表格数据
      seizureTableData: [],      // 查获数量 - seizureList
      workingTableData: [],      // 在岗时长 - workingList
      inspectionTableData: [],   // 巡检合格率 - checkList
      questionTableData: [],     // 抽问抽答正确率 - answerList
      learningTableData: []      // 培训答题分数 - learningList
    }
  },

  async onLoad(options) {
    // 接收页面参数
    this.startDate = options.startDate || ''
    this.endDate = options.endDate || ''

    console.log('接收到的时间参数:', {
      startDate: this.startDate,
      endDate: this.endDate
    })

    // 页面加载时获取数据
    await this.loadData()
  },

  methods: {
    // 加载数据方法
    async loadData() {
      try {
        // 根据时间参数构建查询条件
        const queryParams = {}
        if (this.startDate && this.endDate) {
          queryParams.startDate = this.startDate
          queryParams.endDate = this.endDate
        }

        console.log('加载数据的查询参数:', queryParams)

        // 调用getHomeReportWhole接口获取真实数据
        const response = await getHomeReportWhole(queryParams)

        if (response.code === 200 && response.data) {
          // 处理接口返回的真实数据
          const { checkList, learningList, seizureList, workingList, answerList } = response.data;

          // 分配数据到对应的表格
          this.seizureTableData = seizureList || this.generateMockDepartmentData('查获数量')
          this.workingTableData = workingList || this.generateMockDepartmentData('在岗时长')
          this.inspectionTableData = checkList.map((item) => {
            return {
              ...item,
              medianNumber: `${(item.medianNumber * 100).toFixed(2)}`,
              maxNumber: `${(item.maxNumber * 100).toFixed(2)}`,
              minNumber: `${(item.minNumber * 100).toFixed(2)}`,
              averageNumber: `${(item.averageNumber * 100).toFixed(2)}`
            }
          }) || this.generateMockDepartmentData('巡检合格率')
          this.questionTableData = answerList.map((item) => {
            return {
              ...item,
              medianNumber: `${(item.medianNumber).toFixed(2)}`,
              maxNumber: `${(item.maxNumber).toFixed(2)}`,
              minNumber: `${(item.minNumber).toFixed(2)}`,
              averageNumber: `${(item.averageNumber).toFixed(2)}`
            }
          }) || this.generateMockDepartmentData('抽问抽答正确率')
          this.learningTableData = learningList || this.generateMockDepartmentData('培训答题分数')

          // 如果有时间参数，显示时间范围提示
          // if (this.startDate && this.endDate) {
          //   uni.showToast({
          //     title: `已加载 ${this.startDate} 至 ${this.endDate} 的数据`,
          //     icon: 'none',
          //     duration: 2000
          //   })
          // }
        } else {
          // 如果接口返回失败，使用模拟数据
          console.warn('接口返回数据异常，使用模拟数据')
          this.seizureTableData = this.generateMockDepartmentData('查获数量')
          this.workingTableData = this.generateMockDepartmentData('在岗时长')
          this.inspectionTableData = this.generateMockDepartmentData('巡检合格率')
          this.questionTableData = this.generateMockDepartmentData('抽问抽答正确率')
          this.learningTableData = this.generateMockDepartmentData('培训答题分数')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        // 如果接口调用失败，使用模拟数据
        this.seizureTableData = this.generateMockDepartmentData('查获数量')
        this.workingTableData = this.generateMockDepartmentData('在岗时长')
        this.inspectionTableData = this.generateMockDepartmentData('巡检合格率')
        this.questionTableData = this.generateMockDepartmentData('抽问抽答正确率')
        this.learningTableData = this.generateMockDepartmentData('培训答题分数')

        uni.showToast({
          title: '数据加载失败，使用模拟数据',
          icon: 'none'
        })
      }
    },





    // 生成模拟科室数据（根据类型生成不同科室的统计数据）
    generateMockDepartmentData(type) {
      // 模拟科室列表
      const departments = ['安检一科', '安检二科', '安检三科', '安检四科', '安检五科']

      // 根据类型设置基础数值范围
      const baseConfig = {
        '查获数量': { baseTotal: 800, baseAvg: 20, baseMedian: 18, baseMax: 40, baseMin: 5 },
        '在岗时长': { baseTotal: 1200, baseAvg: 30, baseMedian: 28, baseMax: 60, baseMin: 15 },
        '巡检合格率': { baseTotal: 1000, baseAvg: 25, baseMedian: 23, baseMax: 50, baseMin: 10 },
        '抽问抽答正确率': { baseTotal: 600, baseAvg: 15, baseMedian: 14, baseMax: 30, baseMin: 3 },
        '培训答题分数': { baseTotal: 900, baseAvg: 22, baseMedian: 21, baseMax: 45, baseMin: 8 }
      }

      const config = baseConfig[type] || baseConfig['查获数量']

      return departments.map((dept, index) => {
        // 为每个科室生成略有差异的数据
        const variation = (index + 1) * 0.1 // 每个科室数据略有不同

        return {
          name: dept,
          totalNumber: Math.round(config.baseTotal * (1 + variation * 0.2)),
          averageNumber: (config.baseAvg * (1 + variation * 0.1)).toFixed(1),
          medianNumber: (config.baseMedian * (1 + variation * 0.1)).toFixed(1),
          maxNumber: Math.round(config.baseMax * (1 + variation * 0.3)),
          minNumber: Math.round(config.baseMin * (1 + variation * 0.1))
        }
      })
    },

    // 生成模拟表格数据（根据时间参数调整数据）
    generateMockTableData(type, queryParams = {}) {
      // 根据时间范围调整数据值
      let baseValue = 1000
      let completionRate = 98.5
      let passRate = 96.2
      let avgTime = 15

      // 如果有时间参数，根据时间范围调整数据
      if (queryParams.startDate && queryParams.endDate) {
        // 计算时间跨度（天数）
        const start = new Date(queryParams.startDate)
        const end = new Date(queryParams.endDate)
        const diffTime = Math.abs(end - start)
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

        // 根据时间跨度调整数据
        baseValue = Math.round(1000 * (diffDays / 30)) // 假设30天为基准
        completionRate = 98.5 - (30 - Math.min(diffDays, 30)) * 0.1
        passRate = 96.2 - (30 - Math.min(diffDays, 30)) * 0.05
        avgTime = 15 + (30 - Math.min(diffDays, 30)) * 0.2
      }

      return [
        { label: `${type}总数`, value: baseValue.toLocaleString() },
        { label: `${type}完成率`, value: `${completionRate.toFixed(1)}%` },
        { label: `${type}合格率`, value: `${passRate.toFixed(1)}%` },
        { label: `${type}平均用时`, value: `${avgTime.toFixed(0)}分钟` }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
.statistical-report {
  min-height: 100vh;
  background-color: #f5f7fa;
}

// 时间范围显示样式
.time-range-display {
  background-color: #ffffff;
  padding: 24rpx 32rpx;
  margin-bottom: 24rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .time-range-text {
    font-size: 28rpx;
    color: #666;
    font-weight: 500;
  }
}

.page-header {
  margin-bottom: 32rpx;
}

.statistic-tables-section {
  .statistic-table {
    margin-bottom: 32rpx;
  }
}

// 响应式适配
@media (max-width: 750px) {
  .time-range-display {
    padding: 20rpx 24rpx;
    margin-bottom: 20rpx;

    .time-range-text {
      font-size: 26rpx;
    }
  }

  .statistic-tables-section {
    .statistic-table {
      margin-bottom: 24rpx;
    }
  }
}
</style>