<template>
  <module-container title="模块三 培训质控分析">
    <div class="module-three-content">
      <div class="chart-card">
        <div class="chart-title">查堵-人员自测漏检次数（总累积）</div>
        <div ref="chart1" class="echarts"></div>
      </div>
      <div class="chart-card">
        <div class="chart-title">查堵培训-人员月考成绩（总累积）</div>
        <div ref="chart2" class="echarts"></div>
      </div>
    </div>
  </module-container>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import ModuleContainer from './ModuleContainer.vue'
import { useEcharts } from '@/hooks/chart.js'
import { monthlyAssessment, selfTestHasMissCheck } from '@/api/blockingData/blockingDataScreen.js'
import { formatDateHy } from '@/utils/index.js'

// 接收筛选参数
const props = defineProps({
  filterParams: {
    type: Object,
    default: () => ({})
  }
})

const chart1 = ref(null)
const chart2 = ref(null)

const { setOption: setOption1 } = useEcharts(chart1)
const { setOption: setOption2 } = useEcharts(chart2)

// 处理filterParams，将dateRange拆分为startTime和endTime
const processFilterParams = (params) => {
  const { dateRange, ...rest } = params
  const processed = { ...rest }

  if (dateRange && Array.isArray(dateRange) && dateRange.length === 2) {
    processed.startDate = formatDateHy(dateRange[0])
    processed.endDate = formatDateHy(dateRange[1])
  }
  if (processed.brigadeId == 'all') {
    delete processed.brigadeId
  }
  if (processed.terminalId == 'all') {
    delete processed.terminalId
  }

  return processed
}

// 数据加载函数
const loadData = async () => {
  try {
    const queryParams = processFilterParams(props.filterParams)

    // 并行请求培训质控数据
    const [selfTestRes, monthlyAssessmentRes] = await Promise.allSettled([
      selfTestHasMissCheck(queryParams),
      monthlyAssessment(queryParams)
    ])

    // 查堵-人员自测漏检次数（总累积）
    const selfTestData = selfTestRes?.value?.data || []

    if (selfTestData.length > 0) {
      setOption1(ringPieOption(
        selfTestData.map(item => ({
          name: item.name || item.level || '未知',
          value: item.total || item.count || 0
        })),
        ['#3b82f6', '#22c55e', '#f97316', '#cbd5e1']
      ))
    }

    // 查堵培训-人员月考成绩（总累积）
    const monthlyAssessmentData = monthlyAssessmentRes?.value?.data || []
    if (monthlyAssessmentData.length > 0) {
      setOption2(ringPieOption(
        monthlyAssessmentData.map(item => ({
          name: item.name || item.grade || '未知',
          value: item.total || item.count || 0
        })),
        ['#64748b', '#ef4444', '#22c55e', '#3b82f6', '#cbd5e1']
      ))
    }

  } catch (error) {
    console.error('加载培训质控数据失败:', error)
  }
}

// 监听筛选参数变化
watch(() => props.filterParams, () => {
  loadData()
}, { deep: true })

const ringPieOption = (data, colors, centerOffset = ['50%', '55%']) => ({
  color: colors,
  legend: {
    data: data.map(item => item.name),
    top: '0%',
    textStyle: { fontSize: 10 }
  },
  series: [{
    type: 'pie',
    radius: ['45%', '70%'],
    center: centerOffset,
    data: data,
    label: {
      show: true,
      formatter: '{b}\n{c} ({d}%)',
      fontSize: 10
    },
    labelLine: {
      show: true,
      length: 15,
      length2: 10
    }
  }]
})

onMounted(() => {
  loadData()
})
</script>

<style lang="less" scoped>
.module-three-content {
  height: 100%;
  display: flex;
  gap: 10px;

}

.chart-card {
  flex: 1;
  background: #fff;
  border-radius: 6px;
  padding: 15px;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  min-height: 400px;  /* 400px */
  height: 100%;
}

.chart-title {
  font-size: 17px;
  color: black;
  margin-bottom: 5px;
  text-align: left;
}

.echarts {
  flex: 1;
  width: 100%;
  min-height: 400px;  /* 400px */
  height: 400px;
}
</style>
