<template>
  <div class="home-container">
    <!-- Hero 区域 -->
    <section class="hero">
      <div class="hero-overlay"></div>
      <div class="hero-content">
        <div class="search-box">
          <div class="search-input-wrap">
            <el-icon class="search-icon"><Search /></el-icon>
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="请输入检索关键词"
              @keyup.enter="handleHeroSearch"
            />
          </div>
          <button class="search-btn" @click="handleHeroSearch">搜索</button>
        </div>
        <p class="hero-desc">
          深海地球物理数据管理可视化平台面向深海调查与科学研究需求，汇聚多波束、地震、重磁、侧扫及海洋环境等多类型地球物理数据，
          提供数据入库、可视化检索与空间分析能力，服务数据贡献者、科研团队和管理机构。
        </p>
        <div class="stat-grid">
          <div class="stat-card" v-for="item in statCards" :key="item.key">
            <div class="stat-icon" :class="`stat-icon--${item.key}`">
              <StatIcon :type="item.key" :size="44" />
            </div>
            <div class="stat-info">
              <div class="stat-label">{{ item.label }}</div>
              <div class="stat-value">
                <span>{{ item.value }}</span>{{ item.unit }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 数据资源 -->
    <section class="section resources-section">
      <div class="section-inner">
        <div class="section-header">
          <span class="section-bar"></span>
          <h2>数据资源</h2>
        </div>
        <div class="resource-grid">
          <div
            class="resource-card"
            v-for="(item, index) in resourceCategories"
            :key="item.id"
            :class="{ active: activeResource === index }"
            @click="handleResourceClick(item, index)"
          >
            <div class="resource-cover" :style="{ backgroundImage: `url(${item.cover})` }">
              <div class="resource-cover-overlay"></div>
              <span class="resource-type-tag">{{ item.desc }}</span>
            </div>
            <div class="resource-footer">
              <div class="resource-name">{{ item.label }}</div>
              <div class="resource-count">{{ item.count }} 个数据集</div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 热门数据 -->
    <section class="section hot-section">
      <div class="section-inner">
        <div class="section-header hot-header">
          <div class="left">
            <span class="section-bar"></span>
            <h2>热门数据</h2>
          </div>
          <div class="hot-tabs">
            <button
              v-for="tab in hotTabs"
              :key="tab.key"
              :class="{ active: hotTab === tab.key }"
              @click="hotTab = tab.key"
            >
              {{ tab.label }}
            </button>
          </div>
        </div>
        <div class="hot-content">
          <div class="hot-featured" v-if="featuredData" @click="goDataDetail(featuredData.id)">
            <span class="hot-badge">HOT</span>
            <div class="featured-cover">
              <img :src="getDataTypeImage(featuredData.data_type)" :alt="featuredData.data_name" />
              <div class="featured-cover-overlay"></div>
              <div class="featured-type">{{ getDataTypeLabel(featuredData.data_type) }}</div>
            </div>
            <div class="featured-body">
              <h3>{{ featuredData.data_name }}</h3>
              <p>{{ featuredData.data_code }} · {{ featuredData.voyage_name }} · {{ featuredData.file_size }}</p>
              <div class="meta-grid">
                <div class="meta-item">
                  <span class="meta-label">数据类型</span>
                  <span class="meta-value">{{ getDataTypeLabel(featuredData.data_type) }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">数据编号</span>
                  <span class="meta-value">{{ featuredData.data_code }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">入库时间</span>
                  <span class="meta-value">{{ featuredData.fill_time }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="hot-list">
            <div
              class="hot-item"
              v-for="item in hotListData"
              :key="item.id"
              @click="goDataDetail(item.id)"
            >
              <span class="hot-badge small">HOT</span>
              <div class="hot-thumb">
                <img :src="getDataTypeImage(item.data_type)" :alt="item.data_name" />
              </div>
              <div class="hot-item-body">
                <h4>{{ item.data_name }}</h4>
                <p>{{ item.data_code }} · {{ item.voyage_name }}</p>
                <div class="meta-grid compact">
                  <div class="meta-item">
                    <span class="meta-label">数据类型</span>
                    <span class="meta-value">{{ getDataTypeLabel(item.data_type) }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">数据编号</span>
                    <span class="meta-value">{{ item.data_code }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">入库时间</span>
                    <span class="meta-value">{{ item.fill_time }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 空间分布地图 -->
    <section class="section map-section">
      <div class="section-inner">
        <div class="section-header center">
          <span class="section-bar"></span>
          <h2>地球物理数据空间分布</h2>
        </div>
        <div class="map" id="cesiumContainer"></div>
      </div>
    </section>
  </div>
</template>

<script setup>
import * as Cesium from 'cesium'
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { getParam } from '@/api/task.js'
import { dataPage } from '@/api/data.js'
import { modifyCesiumMouseWheel } from '@/utils/common'
import { getDataTypeLabel } from '@/constants/dataTypes.js'
import { getDataTypeImage } from '@/constants/homeImages.js'
import {
  HOME_RESOURCE_CATEGORIES,
  HOME_STAT_CARDS,
  HOT_DATA_TABS,
  enrichHotDataMetrics
} from '@/mock/homeData.js'
import StatIcon from '@/components/home/StatIcon.vue'

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

const router = useRouter()
const searchKeyword = ref('')
const statCards = HOME_STAT_CARDS
const resourceCategories = HOME_RESOURCE_CATEGORIES
const hotTabs = HOT_DATA_TABS
const hotTab = ref('views')
const activeResource = ref(1)
const hotDataList = ref([])

/**
 * 按当前 Tab 排序后的热门数据
 */
const sortedHotData = computed(() => {
  const list = [...hotDataList.value]
  const field = hotTab.value
  return list.sort((a, b) => (b[field] || 0) - (a[field] || 0))
})

const featuredData = computed(() => sortedHotData.value[0] || null)
const hotListData = computed(() => sortedHotData.value.slice(1, 4))

const handleHeroSearch = () => {
  router.push({
    path: '/demand',
    query: searchKeyword.value ? { query: searchKeyword.value } : {}
  })
}

const handleResourceClick = (item, index) => {
  activeResource.value = index
  router.push({ path: item.route, query: item.query })
}

const goDataDetail = (id) => {
  router.push(`/input/${id}`)
}

const getDataList = () => {
  dataPage({ start: 0, limit: 13 }).then(res => {
    hotDataList.value = enrichHotDataMetrics(res.page.records)
    updateMapMarkers()
  })
}

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')
      CesiumHostAddr.value = data?.param_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) {
    viewer.imageryLayers.addImageryProvider(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(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()
    }))
  }

  updateMapMarkers()
}

const updateMapMarkers = () => {
  if (!viewer) return
  viewer.entities.removeAll()
  hotDataList.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: 28, height: 28 }
    })
  })
}

onMounted(() => {
  getDataList()
  getParamsList()
})
</script>

<style lang="scss" scoped>
.home-container {
  background: #f5f7fa;
}

.hero {
  position: relative;
  margin-top: -100px;
  padding: 224px 8% 60px;
  min-height: 520px;
  background: url(@/assets/loginBg.jpg) center / cover no-repeat;

  .hero-overlay {
    position: absolute;
    inset: 0;
    background: linear-gradient(180deg, rgba(0, 40, 90, 0.55) 0%, rgba(0, 60, 120, 0.75) 100%);
  }

  .hero-content {
    position: relative;
    z-index: 1;
    max-width: 1200px;
    margin: 0 auto;
  }

  .search-box {
    display: flex;
    max-width: 720px;
    margin: 8px auto 24px;
    background: #fff;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);

    .search-input-wrap {
      flex: 1;
      display: flex;
      align-items: center;
      padding: 0 16px;

      .search-icon {
        font-size: 20px;
        color: #999;
        margin-right: 10px;
      }

      input {
        flex: 1;
        border: none;
        outline: none;
        height: 52px;
        font-size: 16px;
        color: #333;
        background: transparent;

        &::placeholder {
          color: #bbb;
        }
      }
    }

    .search-btn {
      width: 100px;
      border: none;
      background: #0056a4;
      color: #fff;
      font-size: 16px;
      cursor: pointer;
      transition: background 0.2s;

      &:hover {
        background: #004080;
      }
    }
  }

  .hero-desc {
    max-width: 900px;
    margin: 0 auto 36px;
    text-align: center;
    font-size: 14px;
    line-height: 1.8;
    color: rgba(255, 255, 255, 0.92);
  }

  .stat-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;

    .stat-card {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 20px 22px;
      border-radius: 10px;
      background: rgba(255, 255, 255, 0.78);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.55);
      box-shadow: 0 4px 20px rgba(0, 40, 90, 0.12);
      transition: transform 0.2s ease, box-shadow 0.2s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 28px rgba(0, 40, 90, 0.16);
      }

      .stat-icon {
        flex-shrink: 0;
        width: 64px;
        height: 64px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 14px;

        &--multibeam {
          background: linear-gradient(145deg, #eef6fc 0%, #d6ebf9 100%);
        }

        &--seismic {
          background: linear-gradient(145deg, #fef6ec 0%, #fde8cf 100%);
        }

        &--magnetic {
          background: linear-gradient(145deg, #edf9f1 0%, #d4f0de 100%);
        }

        &--sidescan {
          background: linear-gradient(145deg, #f4eefb 0%, #e8dcf5 100%);
        }

        &--dataset {
          background: linear-gradient(145deg, #eef4fc 0%, #d8e6f7 100%);
        }

        &--gravity {
          background: linear-gradient(145deg, #ecf9f5 0%, #d0f0e6 100%);
        }

        &--ocean {
          background: linear-gradient(145deg, #eef9fd 0%, #d4eef9 100%);
        }

        &--records {
          background: linear-gradient(145deg, #f0f2fc 0%, #dde3f7 100%);
        }
      }

      .stat-info {
        min-width: 0;

        .stat-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 6px;
        }

        .stat-value {
          font-size: 14px;
          color: #888;

          span {
            font-size: 28px;
            font-weight: bold;
            color: #0056a4;
            margin-right: 3px;
            line-height: 1;
          }
        }
      }
    }
  }
}

.section {
  padding: 50px 0;

  .section-inner {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 8%;
  }

  .section-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;

    &.center {
      justify-content: center;
    }

    &.hot-header {
      justify-content: space-between;
    }

    .left {
      display: flex;
      align-items: center;
    }

    .section-bar {
      display: inline-block;
      width: 4px;
      height: 22px;
      background: #0056a4;
      border-radius: 2px;
      margin-right: 12px;
    }

    h2 {
      margin: 0;
      font-size: 22px;
      font-weight: bold;
      color: #242424;
    }
  }
}

.resources-section {
  background: #f5f7fa url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23d0d8e0' fill-opacity='0.3'%3E%3Ccircle cx='1' cy='1' r='1'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");

  .resource-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
  }

  .resource-card {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.25s ease;

    &:hover,
    &.active {
      border-color: #0056a4;
      box-shadow: 0 6px 20px rgba(0, 86, 164, 0.18);
      transform: translateY(-2px);
    }

    .resource-cover {
      position: relative;
      height: 160px;
      display: flex;
      align-items: flex-end;
      padding: 16px;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;

      .resource-cover-overlay {
        position: absolute;
        inset: 0;
        background: linear-gradient(180deg, rgba(0, 20, 50, 0.15) 0%, rgba(0, 30, 70, 0.55) 100%);
      }

      .resource-type-tag {
        position: relative;
        z-index: 1;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.85);
        background: rgba(0, 0, 0, 0.2);
        padding: 4px 10px;
        border-radius: 4px;
      }
    }

    .resource-footer {
      padding: 16px 18px;

      .resource-name {
        font-size: 16px;
        font-weight: bold;
        color: #242424;
        margin-bottom: 6px;
      }

      .resource-count {
        font-size: 13px;
        color: #888;
      }
    }
  }
}

.hot-section {
  background: #fff;

  .hot-tabs {
    display: flex;
    gap: 8px;

    button {
      padding: 6px 18px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background: #fff;
      color: #666;
      font-size: 13px;
      cursor: pointer;
      transition: all 0.2s;

      &.active {
        background: #0056a4;
        border-color: #0056a4;
        color: #fff;
      }

      &:hover:not(.active) {
        border-color: #0056a4;
        color: #0056a4;
      }
    }
  }

  .hot-content {
    display: grid;
    grid-template-columns: 1fr 1.2fr;
    gap: 24px;
  }

  .hot-badge {
    position: absolute;
    top: 12px;
    left: 12px;
    z-index: 2;
    background: #f5a623;
    color: #fff;
    font-size: 11px;
    font-weight: bold;
    padding: 2px 8px;
    border-radius: 3px;

    &.small {
      top: 8px;
      left: 8px;
      font-size: 10px;
      padding: 1px 6px;
    }
  }

  .hot-featured {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    cursor: pointer;
    transition: box-shadow 0.25s;

    &:hover {
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
    }

    .featured-cover {
      position: relative;
      height: 200px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
      }

      .featured-cover-overlay {
        position: absolute;
        inset: 0;
        background: linear-gradient(180deg, rgba(0, 30, 70, 0.1) 0%, rgba(0, 30, 70, 0.55) 100%);
      }

      .featured-type {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 1;
        font-size: 18px;
        font-weight: bold;
        color: rgba(255, 255, 255, 0.95);
        text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
        padding: 6px 14px;
        border-radius: 4px;
        background: rgba(0, 50, 100, 0.45);
        backdrop-filter: blur(2px);
      }
    }

    .featured-body {
      padding: 20px;

      h3 {
        margin: 0 0 8px;
        font-size: 16px;
        color: #0056a4;
        line-height: 1.5;
      }

      p {
        margin: 0 0 16px;
        font-size: 13px;
        color: #888;
      }
    }
  }

  .hot-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .hot-item {
    position: relative;
    display: flex;
    gap: 16px;
    padding: 16px;
    background: #fafbfc;
    border-radius: 8px;
    border: 1px solid #eee;
    cursor: pointer;
    transition: all 0.25s;

    &:hover {
      border-color: #0056a4;
      box-shadow: 0 4px 12px rgba(0, 86, 164, 0.1);
    }

    .hot-thumb {
      flex-shrink: 0;
      width: 120px;
      height: 90px;
      border-radius: 6px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
      }
    }

    .hot-item-body {
      flex: 1;
      min-width: 0;

      h4 {
        margin: 0 0 6px;
        font-size: 14px;
        color: #0056a4;
        line-height: 1.4;
      }

      p {
        margin: 0 0 10px;
        font-size: 12px;
        color: #999;
      }
    }
  }

  .meta-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;

    &.compact {
      gap: 4px;
    }

    .meta-item {
      .meta-label {
        display: block;
        font-size: 11px;
        color: #bbb;
        margin-bottom: 2px;
      }

      .meta-value {
        display: block;
        font-size: 12px;
        color: #444;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

.map-section {
  background: #f5f7fa;
  padding-bottom: 60px;

  .map {
    width: 100%;
    height: 600px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  }
}

@media (max-width: 1200px) {
  .hero .stat-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .resources-section .resource-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .hot-section .hot-content {
    grid-template-columns: 1fr;
  }
}
</style>
