<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="68px">
            <el-form-item label="危险源等级" prop="hiddGrad">
              <el-select v-model="queryParams.hiddGrad" placeholder="请选择危险源等级" clearable style="width: 100%">
                <el-option v-for="dict in haz_grad" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="危险源状态" prop="hazStat">
              <el-select v-model="queryParams.hazStat" placeholder="请选择危险源状态" clearable style="width: 100%">
                <el-option v-for="dict in haz_stat" :key="dict.value" :label="dict.label" :value="dict.value" />
              </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.major }}</el-descriptions-item>
            <el-descriptions-item label="一般危险源">{{ statData.normal }}</el-descriptions-item>
            <el-descriptions-item label="已备案">{{ statData.registered }}</el-descriptions-item>
            <el-descriptions-item label="已管控">{{ statData.controlled }}</el-descriptions-item>
            <el-descriptions-item label="未管控">{{ statData.uncontrolled }}</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="危险源名称">{{ detailData.hazName }}</el-descriptions-item>
        <el-descriptions-item label="危险源等级">
          <dict-tag :options="haz_grad" :value="detailData.hiddGrad" />
        </el-descriptions-item>
        <el-descriptions-item label="危险源状态">
          <dict-tag :options="haz_stat" :value="detailData.hazStat" />
        </el-descriptions-item>
        <el-descriptions-item label="风险等级">
          <dict-tag :options="risk_grad" :value="detailData.riskGrad" />
        </el-descriptions-item>
        <el-descriptions-item label="涉及部位">{{ detailData.proPart }}</el-descriptions-item>
        <el-descriptions-item label="部位经度">{{ detailData.partLong }}</el-descriptions-item>
        <el-descriptions-item label="部位纬度">{{ detailData.partLat }}</el-descriptions-item>
        <el-descriptions-item label="采集时间" :span="2">{{ detailData.collTime }}</el-descriptions-item>
        <el-descriptions-item label="责任人" :span="2">{{ detailData.supPers }}</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="HazardGIS">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
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 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, major: 0, normal: 0,
  registered: 0, controlled: 0, uncontrolled: 0
})

const data = reactive({
  queryParams: {
    hiddGrad: undefined,
    hazStat: 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.stat
      }
    },
    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() {
  listObjHaz(queryParams.value).then(res => {
    const list = res.rows || []

    let total = list.length, major = 0, normal = 0
    let registered = 0, controlled = 0, uncontrolled = 0

    list.forEach(item => {
      if (item.hiddGrad === '2') major++
      else normal++
      if (item.hazStat === '2') registered++
      if (item.ifControl === 'Y') controlled++
      else uncontrolled++
    })

    statData.value = { total, major, normal, registered, controlled, uncontrolled }

    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' ? '重大' : '一般',
        stat: item.hazStat === '2' ? '已备案' : item.hazStat === '4' ? '已核销' : '未备案',
        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/hazard/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>
