<template>
  <div class="container">
    <div class="left" v-show="isShow">
      <img class="fold" v-show="isShow" src="@/assets/icons/折叠.png" @click="handleFold">
      <div class="search">
        <p class="rule-text">编号规则:数据类型_航次_4位编号</p>
        <div class="input-bar">
          <el-input
              v-model="dataCode"
              style="width: 120px"
              size="large"
              placeholder="数据编号"
          />
          <el-select
              v-model="dataType"
              placeholder="数据类型"
              size="large"
              style="width: 140px"
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="item in dataTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
              v-model="dataStatus"
              placeholder="入库状态"
              size="large"
              style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="已入库" value="已入库" />
            <el-option label="处理中" value="处理中" />
            <el-option label="待审核" value="待审核" />
          </el-select>
        </div>
      </div>
      <div class="btn-bar">
        <el-button :icon="RefreshRight" @click="onReset">重置</el-button>
        <el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
      </div>
      <div class="line" />
      <div class="list">
        <div class="item" v-for="item in dataList" :key="item.id">
          <div class="name">{{ item.data_code }}</div>
          <div class="time">{{ item.fill_time }}</div>
          <div class="row">
            <div class="col">航次：<span>{{ item.voyage_name }}</span></div>
            <div class="col">入库状态：<span>{{ item.data_status }}</span></div>
          </div>
          <div class="row">
            <div class="col">数据类型：<span>{{ getDataTypeLabel(item.data_type) }}</span></div>
            <div class="col">数据名称：<span>{{ item.data_name }}</span></div>
          </div>
          <div class="row">
            <div class="col">数据量：<span>{{ item.file_size }}</span></div>
          </div>
        </div>
      </div>
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <div class="map">
      <div id="cesiumContainer" style="width: 100%; height: 100%;"></div>
      <img class="unfold" v-show="!isShow" src="@/assets/icons/展开.png" alt="" @click="handleUnfold">
    </div>

    <el-dialog
        v-model="dialogVisible"
        title="数据详情"
        width="500"
    >
      <div class="item" v-if="currentMarker">
        <div class="name">{{ currentMarker.data_code }}</div>
        <div class="time">{{ currentMarker.fill_time }}</div>
        <div class="row">
          <div class="col">航次：<span>{{ currentMarker.voyage_name }}</span></div>
          <div class="col">入库状态：<span>{{ currentMarker.data_status }}</span></div>
        </div>
        <div class="row">
          <div class="col">数据类型：<span>{{ getDataTypeLabel(currentMarker.data_type) }}</span></div>
          <div class="col">数据名称：<span>{{ currentMarker.data_name }}</span></div>
        </div>
        <div class="row">
          <div class="col">位置：<span>{{ currentMarker.data_lon }}，{{ currentMarker.data_lat }}</span></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import * as Cesium from 'cesium'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { dataPage } from '@/api/data.js'
import { getParam } from '@/api/task.js'
import { modifyCesiumMouseWheel } from '@/utils/common'
import { getFlatDataTypeOptions, getDataTypeLabel } from '@/constants/dataTypes.js'

import markerIcon1 from '@/assets/icons/标注点1.png'
import markerIcon2 from '@/assets/icons/标注点2.png'
import markerIcon3 from '@/assets/icons/标注点3.png'

const route = useRoute()
const isShow = ref(true)
const dataCode = ref('')
const dataType = ref('')
const dataStatus = ref('')
const searchQuery = ref('')
const searchCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const start = ref(0)
const total = ref(0)
const dataList = ref([])
const dialogVisible = ref(false)
const currentMarker = ref(null)
const dataTypeOptions = getFlatDataTypeOptions()

const handleFold = () => {
  isShow.value = false
}

const handleUnfold = () => {
  isShow.value = true
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  start.value = pageSize.value * (val - 1)
  getDataList()
}

const getDataList = () => {
  dataPage({
    start: start.value,
    limit: 10,
    data_type: dataType.value,
    data_status: dataStatus.value,
    data_code: dataCode.value,
    query: searchQuery.value,
    category: searchCategory.value
  }).then(res => {
    dataList.value = res.page.records
    total.value = res.page.total
    updateMapMarkers()
  })
}

const updateMapMarkers = () => {
  if (!viewer) return
  viewer.entities.removeAll()
  dataList.value.forEach(item => {
    let icon = markerIcon1
    if (item.data_status === '处理中') icon = markerIcon2
    if (item.data_status === '已入库') icon = markerIcon3

    viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(item.data_lon, item.data_lat),
      billboard: {
        image: icon,
        width: 32,
        height: 32
      },
      properties: item
    })
  })
}

const onReset = () => {
  dataType.value = ''
  dataStatus.value = ''
  dataCode.value = ''
  start.value = 0
  getDataList()
}

const onSearch = () => {
  start.value = 0
  getDataList()
}

const CesiumHostAddr = ref('')

const getParamsList = () => {
  if (import.meta.env.VITE_APP_ENV === 'development') {
    CesiumHostAddr.value = import.meta.env.VITE_APP_DS_API
    initMap()
  } else {
    getParam().then(res => {
      const data = res.array.find(item => item.param_name === 'CesiumHostAddr')
      if (data?.param_value) {
        CesiumHostAddr.value = data.param_value
      } else {
        CesiumHostAddr.value = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/tiles/`
      }
      initMap()
    })
  }
}

let viewer

Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkY2Y5NWY2Ni1mODQ1LTQ3YTUtYjc4Zi1jYzhjMGI2YzcxMWYiLCJpZCI6MTI5ODMwLCJpYXQiOjE2Nzk0Njk5NTd9.DTH54ioOH-HLqeNIetBe9hFyrPOX2Vp1AQmZzw8TIZ4'

const cesiumConfig = {
  sceneMode: Cesium.SceneMode.SCENE2D,
  homeButton: false,
  sceneModePicker: false,
  fullscreenButton: false,
  infoBox: false,
  selectionIndicator: false,
  baseLayerPicker: false,
  shadows: true,
  shouldAnimate: true,
  animation: false,
  timeline: false,
  geocoder: false,
  navigationHelpButton: false,
  contextOptions: {
    contextType: 2
  },
  creditContainer: document.createElement('div')
}

const initMap = () => {
  viewer = new Cesium.Viewer('cesiumContainer', cesiumConfig)
  viewer._cesiumWidget._creditContainer.style.display = 'none'
  viewer.scene.sun.show = false
  viewer.scene.moon.show = false
  viewer.scene.fog.enabled = false
  viewer.scene.skyAtmosphere.show = false
  viewer.scene.skyBox.show = false
  viewer.scene.globe.enableLighting = false
  viewer.shadowMap.darkness = 0.8
  viewer.scene._sunBloom = false
  viewer.scene.globe.showGroundAtmosphere = false
  viewer.scene.postProcessStages.fxaa.enabled = true
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(112, 18, 4000000)
  })
  modifyCesiumMouseWheel(viewer)

  if (CesiumHostAddr.value) {
    const shipline = new Cesium.WebMapTileServiceImageryProvider({
      url: CesiumHostAddr.value + 'geoserver/gwc/service/wmts/rest/ougp:正射影像图_GM输出_20240516/{TileMatrixSet}/{TileMatrixSet}:{TileMatrix}/{TileRow}/{TileCol}?format=image/png',
      layer: 'ougp:正射影像图_GM输出_20240516',
      style: 'default',
      format: 'image/png',
      tileMatrixSetID: 'EPSG:4326',
      tilingScheme: new Cesium.GeographicTilingScheme()
    })
    viewer.imageryLayers.addImageryProvider(shipline)

    const contour6000 = new Cesium.WebMapTileServiceImageryProvider({
      url: CesiumHostAddr.value + 'geoserver/gwc/service/wmts/rest/ougp:contour6000/{TileMatrixSet}/{TileMatrixSet}:{TileMatrix}/{TileRow}/{TileCol}?format=image/png',
      layer: 'ougp:contour6000',
      style: 'default',
      format: 'image/png',
      tileMatrixSetID: 'EPSG:4326',
      tilingScheme: new Cesium.GeographicTilingScheme()
    })
    viewer.imageryLayers.addImageryProvider(contour6000)
  }

  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  handler.setInputAction((click) => {
    const picked = viewer.scene.pick(click.position)
    if (Cesium.defined(picked) && picked.id?.properties) {
      currentMarker.value = picked.id.properties.getValue()
      dialogVisible.value = true
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

  updateMapMarkers()
}

onMounted(() => {
  if (route.query.query) {
    searchQuery.value = String(route.query.query)
  }
  if (route.query.category) {
    searchCategory.value = String(route.query.category)
  }
  getParamsList()
  getDataList()
})
</script>

<style lang="scss" scoped>
.container {
  height: 820px;
  display: flex;

  .left {
    width: 450px;
    position: relative;
    padding: 0 30px 30px;
    box-sizing: border-box;

    .fold {
      position: absolute;
      top: 350px;
      right: 0;
    }

    .rule-text {
      color: #000;
    }

    .search {
      .input-bar {
        display: flex;
        justify-content: space-between;
        gap: 8px;
        flex-wrap: wrap;
      }
    }

    .btn-bar {
      margin-top: 10px;
      display: flex;
      justify-content: center;
    }

    .line {
      margin-top: 10px;
      width: 100%;
      height: 1px;
      background-color: #ddd;
    }

    .list {
      color: #333;
      height: 620px;
      overflow-y: scroll;
      scrollbar-width: none;
      -ms-overflow-style: none;

      .item {
        padding: 30px 0;
        border-bottom: 1px solid #dddddd;

        &:hover .name {
          color: #409eff;
        }

        .name {
          padding-bottom: 5px;
          color: #000;
          font-weight: bold;
        }

        .row {
          padding: 5px 0;
          display: flex;
          gap: 20px;

          .col {
            flex: 1;
            color: #999;

            span {
              color: #333;
            }
          }
        }
      }
    }
  }

  .map {
    flex: 1;
    width: 100%;
    height: 100%;
    position: relative;

    .unfold {
      position: absolute;
      top: 350px;
      left: 0;
    }
  }
}

.pagination {
  margin: 10px 0 20px;
  display: flex;
  justify-content: center;
}
</style>
