<template>
  <div class="big-screen-wrap">
    <div class="header">
      <div class="filters">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        <el-button type="primary" @click="reloadAll">查询</el-button>
      </div>
      <div class="cards">
        <div class="card">
          <div class="label">总巡检次数</div>
          <div class="value">{{ total }}</div>
        </div>
        <div class="card">
          <div class="label">期间巡检次数</div>
          <div class="value">{{ monthTotal }}</div>
        </div>
        <div class="card">
          <div class="label">覆盖率</div>
          <div class="value">{{ (coverage.coverageRate * 100).toFixed(1) }}% ({{ coverage.inspectedCount }}/{{ coverage.totalCount }})</div>
        </div>
      </div>
    </div>

    <div class="charts-row">
      <div class="chart" ref="barDom"></div>
      <div class="chart" ref="pieInspectorDom"></div>
      <div class="chart" ref="pieTypeDom"></div>
    </div>

    <div class="charts-row">
      <div class="chart wide" ref="lineDom"></div>
      <div class="chart" ref="barTypeDom"></div>
      <div class="chart" ref="pieStatusDom"></div>
    </div>

    <div class="table-wrap">
      <el-card>
        <template #header>
          <span>未巡检点位清单</span>
        </template>
        <el-table :data="uninspected" height="300">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="inspectionPoint" label="巡检点" />
          <el-table-column prop="inspectionPointType" label="类型" width="120" />
          <el-table-column prop="inspectionStatus" label="状态" width="120" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ColumnList, RoundList, listTotal, listmonthTotal, trendDaily, typeProportion, coverage as fetchCoverage, uninspectedPoints, pointTypeCounts, statusDistribution } from '@/api/inspection/report.js'

const dateRange = ref([])

// numbers
const total = ref(0)
const monthTotal = ref(0)
const coverageData = ref({ inspectedCount: 0, totalCount: 0, coverageRate: 0 })

// tables
const uninspected = ref([])

// chart doms
const barDom = ref(null)
const pieInspectorDom = ref(null)
const pieTypeDom = ref(null)
const lineDom = ref(null)
const barTypeDom = ref(null)
const pieStatusDom = ref(null)

let barChart, pieInspectorChart, pieTypeChart, lineChart, barTypeChart, pieStatusChart

const buildParams = () => {
  const params = {}
  if (dateRange.value && dateRange.value.length === 2) {
    params.startTime = dateRange.value[0]
    params.endTime = dateRange.value[1]
  }
  return params
}

const reloadAll = async () => {
  const params = buildParams()
  // totals
  const [totalRes, monthRes, covRes] = await Promise.all([
    listTotal(params),
    listmonthTotal(params),
    fetchCoverage(params)
  ])
  total.value = (totalRes?.data?.data) ?? (totalRes?.data) ?? 0
  monthTotal.value = (monthRes?.data?.data) ?? (monthRes?.data) ?? 0
  const cov = (covRes?.data?.data) ?? covRes?.data ?? {}
  coverageData.value = cov

  // charts
  const [barRes, pieInspectorRes, pieTypeRes, lineRes, barTypeRes, pieStatusRes] = await Promise.all([
    ColumnList(params),
    RoundList(params),
    typeProportion(params),
    trendDaily(params),
    pointTypeCounts(params),
    statusDistribution()
  ])

  // bar (地点巡检次数)
  const barData = (barRes?.data?.data) ?? barRes?.data ?? {}
  const barOption = {
    title: { text: '地点巡检次数' },
    tooltip: {},
    xAxis: { type: 'category', data: barData.xAxis || [] },
    yAxis: { type: 'value' },
    series: [{ type: 'bar', data: barData.seriesData || [] }]
  }
  barChart && barChart.setOption(barOption)

  // pie inspectors
  const pieInspectorData = (pieInspectorRes?.data?.data) ?? pieInspectorRes?.data ?? {}
  const pieInspectorOption = {
    title: { text: '巡检人分布' },
    tooltip: { trigger: 'item' },
    series: [{ type: 'pie', radius: ['40%', '70%'], data: pieInspectorData.seriesData || [] }]
  }
  pieInspectorChart && pieInspectorChart.setOption(pieInspectorOption)

  // pie types
  const pieTypeData = (pieTypeRes?.data?.data) ?? pieTypeRes?.data ?? {}
  const pieTypeOption = {
    title: { text: '巡检类型占比' },
    tooltip: { trigger: 'item' },
    series: [{ type: 'pie', radius: ['40%', '70%'], data: pieTypeData.seriesData || [] }]
  }
  pieTypeChart && pieTypeChart.setOption(pieTypeOption)

  // line daily trend
  const lineData = (lineRes?.data?.data) ?? lineRes?.data ?? {}
  const lineOption = {
    title: { text: '按日巡检趋势' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: lineData.xAxis || [] },
    yAxis: { type: 'value' },
    series: [{ type: 'line', smooth: true, data: lineData.seriesData || [] }]
  }
  lineChart && lineChart.setOption(lineOption)

  // bar type counts
  const barTypeData = (barTypeRes?.data?.data) ?? barTypeRes?.data ?? {}
  const barTypeOption = {
    title: { text: '类型已巡检点数量' },
    tooltip: {},
    xAxis: { type: 'category', data: barTypeData.xAxis || [] },
    yAxis: { type: 'value' },
    series: [{ type: 'bar', data: barTypeData.seriesData || [] }]
  }
  barTypeChart && barTypeChart.setOption(barTypeOption)

  // pie status distribution
  const pieStatusData = (pieStatusRes?.data?.data) ?? pieStatusRes?.data ?? {}
  const pieStatusOption = {
    title: { text: '点位状态分布' },
    tooltip: { trigger: 'item' },
    series: [{ type: 'pie', radius: ['40%', '70%'], data: pieStatusData.seriesData || [] }]
  }
  pieStatusChart && pieStatusChart.setOption(pieStatusOption)

  // table
  const uninspectedRes = await uninspectedPoints(params)
  uninspected.value = uninspectedRes?.data?.rows ?? uninspectedRes?.data ?? []
}

onMounted(async () => {
  await nextTick()
  barChart = echarts.init(barDom.value)
  pieInspectorChart = echarts.init(pieInspectorDom.value)
  pieTypeChart = echarts.init(pieTypeDom.value)
  lineChart = echarts.init(lineDom.value)
  barTypeChart = echarts.init(barTypeDom.value)
  pieStatusChart = echarts.init(pieStatusDom.value)
  reloadAll()
})

onUnmounted(() => {
  ;[barChart, pieInspectorChart, pieTypeChart, lineChart, barTypeChart, pieStatusChart].forEach(c => {
    if (c && c.dispose) c.dispose()
  })
})

// 暴露覆盖率方便模板取值
const coverage = {
  get inspectedCount() { return coverageData.value.inspectedCount || 0 },
  get totalCount() { return coverageData.value.totalCount || 0 },
  get coverageRate() { return coverageData.value.coverageRate || 0 }
}
</script>

<style scoped>
.big-screen-wrap { padding: 16px; }
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
.filters { display: flex; gap: 8px; align-items: center; }
.cards { display: flex; gap: 12px; }
.card { background: #fff; border-radius: 8px; padding: 12px 16px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); min-width: 220px; }
.card .label { font-size: 14px; color: #666; }
.card .value { font-size: 20px; font-weight: 600; margin-top: 4px; }
.charts-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 12px; }
.chart { height: 320px; background: #fff; border-radius: 8px; }
.chart.wide { grid-column: span 2; }
.table-wrap { margin-top: 12px; }
</style>