<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年份" prop="year">
        <el-select v-model="queryParams.year" placeholder="请选择年份" clearable style="width: 240px">
          <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="mon">
        <el-select v-model="queryParams.mon" placeholder="请选择月份" clearable style="width: 240px">
          <el-option v-for="month in 12" :key="month" :label="month + '月'" :value="String(month).padStart(2, '0')" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card shadow="hover" @click="handleDrillDown('ybsNum')" style="cursor: pointer;">
          <template #header>
            <span>应辨识总数</span>
          </template>
          <div class="stat-card">
            <div class="stat-value">{{ totalCount.ybsNum || 0 }}</div>
            <div class="stat-label">一般: {{ totalCount.ybYbs || 0 }} | 重大: {{ totalCount.zdYbs || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" @click="handleDrillDown('alrhaz')" style="cursor: pointer;">
          <template #header>
            <span>已辨识总数</span>
          </template>
          <div class="stat-card">
            <div class="stat-value">{{ totalCount.alrhaz || 0 }}</div>
            <div class="stat-label">辨识率: {{ totalCount.hazBsl || 0 }}%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" @click="handleDrillDown('haz')" style="cursor: pointer;">
          <template #header>
            <span>危险源总数</span>
          </template>
          <div class="stat-card">
            <div class="stat-value">{{ (totalCount.ybHaz || 0) + (totalCount.zdHaz || 0) }}</div>
            <div class="stat-label">一般: {{ totalCount.ybHaz || 0 }} | 重大: {{ totalCount.zdHaz || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" @click="handleDrillDown('gkl')" style="cursor: pointer;">
          <template #header>
            <span>总管控率</span>
          </template>
          <div class="stat-card">
            <div class="stat-value">{{ totalCount.totGkl || 0 }}%</div>
            <div class="stat-label">工程数量: {{ totalCount.engNum || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-tabs v-model="statTab">
      <el-tab-pane label="图表概览" name="chart">
        <el-row :gutter="20" class="mb8">
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header><span>月度统计趋势</span></template>
              <div ref="chartRef" style="height: 400px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header><span>管控率统计</span></template>
              <div ref="controlChartRef" style="height: 400px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="GIS地图" name="gis">
        <el-card shadow="hover">
          <div v-loading="mapLoading" ref="mapContainer" style="height: 600px; width: 100%;"></div>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="月度明细" name="table">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>月度统计列表</span>
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hazard:tbusihazcountmon:export']">导出</el-button>
            </div>
          </template>
          <el-table v-loading="loading" :data="countMonList" @row-click="handleRowClick">
            <el-table-column label="年份" align="center" prop="year" />
            <el-table-column label="月份" align="center" prop="mon" />
            <el-table-column label="应辨识总数" align="center" prop="ybsNum" />
            <el-table-column label="已辨识总数" align="center" prop="alrhaz" />
            <el-table-column label="辨识率(%)" align="center" prop="hazBsl" />
            <el-table-column label="一般危险源" align="center" prop="ybHaz" />
            <el-table-column label="重大危险源" align="center" prop="zdHaz" />
            <el-table-column label="一般管控数" align="center" prop="ybGkHaz" />
            <el-table-column label="重大管控数" align="center" prop="zdGkHaz" />
            <el-table-column label="总管控率(%)" align="center" prop="totGkl" />
          </el-table>
          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 统计明细弹窗 -->
    <el-dialog title="统计明细" v-model="detailOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="年份">{{ detailRow.year }}</el-descriptions-item>
        <el-descriptions-item label="月份">{{ detailRow.mon }}月</el-descriptions-item>
        <el-descriptions-item label="应辨识总数">{{ detailRow.ybsNum }}</el-descriptions-item>
        <el-descriptions-item label="已辨识总数">{{ detailRow.alrhaz }}</el-descriptions-item>
        <el-descriptions-item label="辨识率">{{ detailRow.hazBsl }}%</el-descriptions-item>
        <el-descriptions-item label="辨识率系数">{{ detailRow.bslXs }}</el-descriptions-item>
        <el-descriptions-item label="一般危险源">{{ detailRow.ybHaz }}</el-descriptions-item>
        <el-descriptions-item label="重大危险源">{{ detailRow.zdHaz }}</el-descriptions-item>
        <el-descriptions-item label="一般应辨识">{{ detailRow.ybYbs }}</el-descriptions-item>
        <el-descriptions-item label="重大应辨识">{{ detailRow.zdYbs }}</el-descriptions-item>
        <el-descriptions-item label="有效一般危险源">{{ detailRow.yxYbHaz }}</el-descriptions-item>
        <el-descriptions-item label="有效重大危险源">{{ detailRow.yxZdHaz }}</el-descriptions-item>
        <el-descriptions-item label="一般管控数">{{ detailRow.ybGkHaz }}</el-descriptions-item>
        <el-descriptions-item label="重大管控数">{{ detailRow.zdGkHaz }}</el-descriptions-item>
        <el-descriptions-item label="一般管控率">{{ detailRow.hazYbGkl }}%</el-descriptions-item>
        <el-descriptions-item label="重大管控率">{{ detailRow.hazZdGkl }}%</el-descriptions-item>
        <el-descriptions-item label="总管控率">{{ detailRow.totGkl }}%</el-descriptions-item>
        <el-descriptions-item label="工程数量">{{ detailRow.engNum }}</el-descriptions-item>
        <el-descriptions-item label="已辨识工程">{{ detailRow.alrEngNum }}</el-descriptions-item>
        <el-descriptions-item label="生成时间" :span="2">{{ detailRow.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HazardStat">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { listTBusiHazCount, listTBusiHazCountMon } from "@/api/slaj/hazard"
import { listObjHaz } from "@/api/slaj/hazard"
import * as echarts from "echarts"

const { proxy } = getCurrentInstance()
const { haz_grad, haz_stat, risk_grad } = proxy.useDict("haz_grad", "haz_stat", "risk_grad")

const loading = ref(true)
const showSearch = ref(true)
const countMonList = ref([])
const totalCount = ref({})
const total = ref(0)
const chartRef = ref(null)
const controlChartRef = ref(null)
const statTab = ref("chart")
const mapContainer = ref(null)
const mapLoading = ref(false)
const detailOpen = ref(false)
const detailRow = ref({})

let map = null

const yearOptions = ref([])
const currentYear = new Date().getFullYear()
for (let i = currentYear; i >= currentYear - 5; i--) {
  yearOptions.value.push(String(i))
}

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    year: String(currentYear),
    mon: undefined
  }
})

const { queryParams } = toRefs(data)

function getList() {
  loading.value = true
  listTBusiHazCountMon(queryParams.value).then(res => {
    loading.value = false
    countMonList.value = res.rows
    total.value = res.total
    initChart()
  })
}

function getTotalCount() {
  listTBusiHazCount({ pageNum: 1, pageSize: 1 }).then(res => {
    if (res.rows && res.rows.length > 0) {
      totalCount.value = res.rows[0]
    }
  })
}

function initChart() {
  if (chartRef.value) {
    const chart = echarts.init(chartRef.value)
    const months = countMonList.value.map(item => item.mon + '月')
    const ybHazData = countMonList.value.map(item => item.ybHaz || 0)
    const zdHazData = countMonList.value.map(item => item.zdHaz || 0)
    chart.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['一般危险源', '重大危险源'] },
      xAxis: { type: 'category', data: months },
      yAxis: { type: 'value' },
      series: [
        { name: '一般危险源', type: 'bar', data: ybHazData },
        { name: '重大危险源', type: 'bar', data: zdHazData }
      ]
    })
  }

  if (controlChartRef.value) {
    const chart = echarts.init(controlChartRef.value)
    const months = countMonList.value.map(item => item.mon + '月')
    const bslData = countMonList.value.map(item => item.hazBsl || 0)
    const gklData = countMonList.value.map(item => item.totGkl || 0)
    chart.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['辨识率', '管控率'] },
      xAxis: { type: 'category', data: months },
      yAxis: { type: 'value', axisLabel: { formatter: '{value}%' } },
      series: [
        { name: '辨识率', type: 'line', data: bslData },
        { name: '管控率', type: 'line', data: gklData }
      ]
    })
  }
}

/** 加载GIS地图 */
function initMap() {
  if (!mapContainer.value) return
  mapLoading.value = true

  fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
    .then(res => res.json())
    .then(chinaJson => {
      echarts.registerMap('china', chinaJson)
      mapLoading.value = false
      renderMap()
    })
    .catch(() => {
      mapLoading.value = false
      renderMap()
    })
}

function renderMap() {
  if (!mapContainer.value) return
  map = echarts.init(mapContainer.value)
  map.setOption({
    tooltip: { trigger: 'item', formatter: (p) => p.data.name + '<br/>等级: ' + p.data.grad },
    geo: { map: 'china', roam: true, label: { show: true, fontSize: 10 }, itemStyle: { areaColor: '#eee', borderColor: '#333' } },
    series: [{ name: '危险源', type: 'scatter', coordinateSystem: 'geo', data: [], symbolSize: (v) => Math.max(6, v[2] / 10) }]
  })
  loadMapData()
}

function loadMapData() {
  listObjHaz({ pageNum: 1, pageSize: 1000 }).then(res => {
    const list = res.rows || []
    const mapData = list
      .filter(item => item.partLong && item.partLat)
      .map(item => ({
        name: item.hazName,
        value: [parseFloat(item.partLong), parseFloat(item.partLat), 100],
        grad: item.hiddGrad === '2' ? '重大' : '一般'
      }))
    if (map) {
      map.setOption({ series: [{ data: mapData }] })
    }
  })
}

/** 点击统计卡片钻取 */
function handleDrillDown(type) {
  statTab.value = "table"
}

/** 点击行查看明细 */
function handleRowClick(row) {
  detailRow.value = row
  detailOpen.value = true
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.year = String(currentYear)
  queryParams.value.mon = undefined
  handleQuery()
}

function handleExport() {
  proxy.download("hazard/tbusihazcountmon/export", {
    ...queryParams.value
  }, `hazardCountMon_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList()
  getTotalCount()
})

onUnmounted(() => {
  map?.dispose()
})
</script>

<style scoped>
.stat-card {
  text-align: center;
  padding: 20px 0;
}
.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}
.stat-label {
  font-size: 14px;
  color: #909399;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
