<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="never">
          <template #header>
            <span>筛选条件</span>
          </template>
          <el-form :model="queryParams" ref="queryRef" label-width="80px">
            <el-form-item label="事故等级" prop="acciGrad">
              <el-select v-model="queryParams.acciGrad" placeholder="请选择事故等级" clearable style="width: 100%">
                <el-option v-for="dict in acci_grad" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="事故类别" prop="acciCate">
              <el-select v-model="queryParams.acciCate" placeholder="请选择事故类别" clearable style="width: 100%">
                <el-option v-for="dict in acci_cate" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="查询范围" prop="dataFrom">
              <el-select v-model="queryParams.dataFrom" placeholder="查询范围" clearable style="width: 100%">
                <el-option label="直属单位" value="1" />
                <el-option label="下级水行政" value="2" />
                <el-option label="流域机构" value="3" />
              </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-divider content-position="left">统计信息</el-divider>

          <el-descriptions :column="1" border>
            <el-descriptions-item label="事故总数">{{ statData.total }}</el-descriptions-item>
            <el-descriptions-item label="一般事故">{{ statData.general }}</el-descriptions-item>
            <el-descriptions-item label="较大事故">{{ statData.larger }}</el-descriptions-item>
            <el-descriptions-item label="重大事故">{{ statData.major }}</el-descriptions-item>
            <el-descriptions-item label="特别重大事故">{{ statData.special }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>事故分布地图</span>
              <el-button type="primary" plain icon="FullScreen" @click="toggleFullScreen">全屏</el-button>
            </div>
          </template>
          <div v-loading="mapLoading" ref="mapContainer" class="map-container" :class="{ 'full-screen': isFullScreen }"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="事故详情" v-model="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="事故名称" :span="2">{{ detailData.acciName }}</el-descriptions-item>
        <el-descriptions-item label="事故等级">
          <dict-tag :options="acci_grad" :value="detailData.acciGrad" />
        </el-descriptions-item>
        <el-descriptions-item label="事故类别">
          <dict-tag :options="acci_cate" :value="detailData.acciCate" />
        </el-descriptions-item>
        <el-descriptions-item label="报告状态">
          <dict-tag :options="rep_stat" :value="detailData.repStat" />
        </el-descriptions-item>
        <el-descriptions-item label="发生时间">{{ detailData.occuTime }}</el-descriptions-item>
        <el-descriptions-item label="发生地点" :span="2">{{ detailData.occuLoc }}</el-descriptions-item>
        <el-descriptions-item label="死亡/重伤/失踪">
          {{ detailData.casNum || 0 }}/{{ detailData.serInjNum || 0 }}/{{ detailData.missNum || 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="经济损失(万元)">{{ detailData.econLoss }}</el-descriptions-item>
        <el-descriptions-item label="经度">{{ detailData.occuLong }}</el-descriptions-item>
        <el-descriptions-item label="纬度">{{ detailData.occuLat }}</el-descriptions-item>
        <el-descriptions-item label="事故描述" :span="2">{{ detailData.acciDesc || detailData.note }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleViewDetail">查看详情</el-button>
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AcciGIS">
import { getCurrentInstance, onMounted, onUnmounted, nextTick, reactive, ref, toRefs } from 'vue'
import { listObjAcci, getAcciSummary } from "@/api/slaj/acci"
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()
const { acci_grad, acci_cate, rep_stat } = proxy.useDict("acci_grad", "acci_cate", "rep_stat")

const mapContainer = ref(null)
const detailOpen = ref(false)
const detailData = ref({})
const isFullScreen = ref(false)
const mapLoading = ref(false)

let map = null

const statData = ref({
  total: 0, general: 0, larger: 0, major: 0, special: 0
})

const data = reactive({
  queryParams: {
    acciGrad: undefined,
    acciCate: undefined,
    dataFrom: undefined
  }
})

const { queryParams } = toRefs(data)

/** 初始化地图 */
function initMap() {
  if (!mapContainer.value) return
  map = echarts.init(mapContainer.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        return params.data.name + '<br/>等级: ' + params.data.grad + '<br/>类别: ' + params.data.cate
      }
    },
    geo: {
      map: 'china',
      roam: true,
      label: { show: true, fontSize: 10 },
      itemStyle: { areaColor: '#eee', borderColor: '#333' }
    },
    series: [{
      name: '事故分布',
      type: 'scatter',
      coordinateSystem: 'geo',
      data: [],
      symbolSize: (val) => Math.max(6, val[2] / 10),
      label: { show: false },
      emphasis: { label: { show: true } }
    }]
  }
  map.setOption(option)
  map.on('click', (params) => {
    if (params.data && params.data.item) {
      detailData.value = params.data.item
      detailOpen.value = true
    }
  })
}

/** 加载中国地图数据 */
function loadMap() {
  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)
      initMap()
      loadMapData()
      mapLoading.value = false
    })
    .catch(() => {
      mapLoading.value = false
      initMap()
      loadMapData()
    })
}

/** 加载事故数据 */
function loadMapData() {
  listObjAcci(queryParams.value).then(res => {
    const list = res.rows || []

    let total = list.length, general = 0, larger = 0, major = 0, special = 0

    list.forEach(item => {
      if (item.acciGrad === '1') general++
      else if (item.acciGrad === '2') larger++
      else if (item.acciGrad === '3') major++
      else if (item.acciGrad === '4') special++
    })

    statData.value = { total, general, larger, major, special }

    const mapData = list
      .filter(item => item.occuLong && item.occuLat)
      .map(item => ({
        name: item.acciName,
        value: [parseFloat(item.occuLong), parseFloat(item.occuLat), 100],
        grad: item.acciGrad,
        cate: item.acciCate,
        item: item
      }))

    if (map) {
      map.setOption({ series: [{ data: mapData }] })
    }
  })
}

function handleQuery() {
  loadMapData()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  loadMapData()
}

function toggleFullScreen() {
  isFullScreen.value = !isFullScreen.value
  nextTick(() => map?.resize())
}

function handleViewDetail() {
  detailOpen.value = false
  proxy.$router.push({ path: '/slaj/acci/detail', query: { guid: detailData.value.guid } })
}

onMounted(() => {
  loadMap()
  window.addEventListener('resize', () => map?.resize())
})

onUnmounted(() => {
  map?.dispose()
  window.removeEventListener('resize', () => map?.resize())
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.map-container {
  height: 600px;
  width: 100%;
}
.map-container.full-screen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  height: 100vh;
  width: 100vw;
}
</style>
