<template>
  <div v-if="visible" class="sample-popup-container">
    
    <div class="popup-wrapper">

      <el-card shadow="always" class="popup-card" :body-style="{ padding: '0', position: 'relative' }">
        <span class="close-btn" @click="$emit('close')">×</span>

        <div class="popup-header-wrapper">
          <div class="popup-header">
            <span class="title">样地详情</span>
            <div class="pagination" v-if="total > 1">
              <el-button size="small" circle :disabled="currentIndex === 0" @click="prevSample" class="nav-btn">&lt;</el-button>
              <span class="page-info">{{ currentIndex + 1 }} / {{ total }}</span>
              <el-button size="small" circle :disabled="currentIndex === total - 1" @click="nextSample" class="nav-btn">&gt;</el-button>
            </div>
            <el-tag v-else size="small" type="warning">样地</el-tag>
          </div>
        </div>

        <div class="scroll-content">
          <div class="content-padding">
            <div class="sub-header">ID: {{ currentData.id || '-' }}</div>

            <div class="info-grid">
              <div class="info-item" v-for="(label, key) in fieldMap" :key="key">
                <span class="label">{{ label }}：</span>
                <span class="value">{{ getDisplayValue(key) }}</span>
              </div>
            </div>

            <div class="media-container" v-if="mediaItems.length > 0">
              <el-carousel :key="currentIndex" height="160px" indicator-position="none" :interval="4000" arrow="hover">
                <el-carousel-item v-for="(item, index) in mediaItems" :key="index">
                  <template v-if="item.type === 'image'">
                    <el-image :src="item.src" class="media-content" fit="cover" :preview-src-list="allImages" :initial-index="item.imgIndex" preview-teleported @click.stop />
                  </template>
                  <template v-else-if="item.type === 'video'">
                    <video controls class="media-content"><source :src="item.src" type="video/mp4" /></video>
                  </template>
                </el-carousel-item>
              </el-carousel>
              <div class="media-count">{{ mediaItems.length }} 个附件</div>
            </div>
            <div v-else class="no-media">暂无样地影像</div>

            <div class="popup-actions">
              <el-button type="success" size="small" plain @click="handleViewTree" :loading="loadingTree">
                查看样木信息
              </el-button>
            </div>
          </div>
        </div>
      </el-card>

      <div v-if="treeVisible" class="tree-wrapper">
        <TreePopup 
          :visible="true" 
          :data="treeData" 
          @close="treeVisible = false"
        />
      </div>

    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import { ElCard, ElCarousel, ElCarouselItem, ElTag, ElImage, ElButton } from "element-plus";
import TreePopup from "./TreePopup.vue";

const props = defineProps({
  visible: Boolean,
  data: { type: [Array, Object], default: () => [] },
  // position 不需要了，因为完全由 CSS 布局控制
});

defineEmits(['close']);

// 样地相关逻辑 (保持不变)
const currentIndex = ref(0);
watch(() => props.visible, (val) => { if (val) currentIndex.value = 0; });

const dataList = computed(() => {
  if (Array.isArray(props.data)) return props.data;
  if (props.data && Object.keys(props.data).length > 0) return [props.data];
  return [];
});
const total = computed(() => dataList.value.length);
const currentData = computed(() => dataList.value[currentIndex.value] || {});
const prevSample = () => { if (currentIndex.value > 0) currentIndex.value--; };
const nextSample = () => { if (currentIndex.value < total.value - 1) currentIndex.value++; };

const fieldMap = { parentId: "所属小班ID", databaseName: "数据库名", pjXj: "平均胸径(cm)", zs: "株数", ydzxj: "样地总蓄积", angle: "角度", area: "面积", length: "长度", width: "宽度", version: "版本号", bz: "备注" };
function getDisplayValue(key) {
  const val = currentData.value[key];
  if (val === null || val === undefined || val === '') return '-';
  if (key === 'pjXj' || key === 'ydzxj') return Number(val).toFixed(2);
  return val;
}
const mediaItems = computed(() => {
  const cur = currentData.value;
  const imgs = Array.isArray(cur.images) ? cur.images : [];
  const vids = Array.isArray(cur.videos) ? cur.videos : [];
  let imgCounter = 0;
  return [...imgs.map((src) => ({ type: "image", src, imgIndex: imgCounter++ })), ...vids.map((src) => ({ type: "video", src }))];
});
const allImages = computed(() => { const cur = currentData.value; return Array.isArray(cur.images) ? cur.images : []; });

// --- 样木相关逻辑 ---
const treeVisible = ref(false);
const treeData = ref([]);
const loadingTree = ref(false);

async function handleViewTree() {
  const cur = currentData.value;
  const id = cur.id;
  const database = cur.databaseName;

  if (!id || !database) {
    alert("缺少样地ID或数据库名");
    return;
  }

  loadingTree.value = true;
  try {
    const url = `/api/stats/t1sub2?database=${encodeURIComponent(database)}&id=${id}`;
    const res = await fetch(url);
    const json = await res.json();

    if (json.code === 0 && json.data) {
      // 兼容单条/多条
      if (Array.isArray(json.data)) {
        treeData.value = json.data;
      } else {
        treeData.value = [json.data];
      }
      treeVisible.value = true;
    } else {
      alert("未查询到样木数据");
    }
  } catch (error) {
    console.error("样木查询失败", error);
    alert("请求失败");
  } finally {
    loadingTree.value = false;
  }
}
</script>

<style scoped>
/* 1. 外层容器：相对定位 (相对于父组件 PlotPopup 的 flex item) */
.sample-popup {
  position: relative;
  z-index: 2001;
  width: 280px;
}

/* 箭头 (指向左边的小班弹窗) */
.sample-popup::after {
  content: '';
  position: absolute;
  bottom: 20px; 
  left: -6px; /* 指向左侧 */
  border-width: 6px 6px 6px 0; /* 向右的三角形 */
  border-style: solid;
  border-color: transparent #fff transparent transparent;
  filter: drop-shadow(-2px 0 2px rgba(0,0,0,0.1));
}

/* 2. Flex 布局：让样地卡片和样木弹窗并排 */
.popup-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 10px; /* 间距 */
}

/* 3. 样地卡片样式 */
.popup-card {
  width: 280px;
  border-radius: 8px;
  overflow: visible;
  border: 1px solid #dcdfe6;
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  flex-shrink: 0; /* 防止被挤压 */
}

/* 4. 样木弹窗包装器 */
.tree-wrapper {
  z-index: 2002;
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  top: 8px;
  right: 8px; /* 稍微靠右一点 */
  font-size: 24px;
  font-weight: 300;
  color: #fff;
  cursor: pointer;
  z-index: 100; /* 确保在最上层 */
  line-height: 1;
}
.close-btn:hover { color: #ffe6e6; }

.popup-header-wrapper {
  background-color: #5db862; /* 绿色主题 */
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  /* ✅ 关键修复：右侧预留空间，防止被关闭按钮遮挡 */
  padding-right: 35px;
  color: white;
  height: 32px;
}

.title { font-weight: bold; font-size: 14px; white-space: nowrap; }

/* 翻页器样式 */
.pagination {
  display: flex; align-items: center; gap: 4px;
}
.page-info { font-size: 12px; font-weight: bold; white-space: nowrap; }
.nav-btn {
  width: 18px; height: 18px; min-height: 18px; font-size: 12px; padding: 0;
  background: rgba(255,255,255,0.2); border: none; color: white;
}
.nav-btn:hover:not(:disabled) { background: rgba(255,255,255,0.4); }
.nav-btn:disabled { opacity: 0.5; cursor: not-allowed; }

.scroll-content {
  max-height: 350px; overflow-y: auto; overflow-x: hidden;
  background: #fff; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px;
}
.content-padding { padding: 12px; }

.sub-header { font-size: 12px; color: #909399; margin-bottom: 8px; border-bottom: 1px solid #eee; padding-bottom: 4px; }

.info-grid { display: flex; flex-direction: column; gap: 8px; margin-bottom: 12px; }
.info-item { display: flex; justify-content: space-between; border-bottom: 1px dashed #eee; padding-bottom: 4px; font-size: 12px; }
.info-item .label { color: #909399; flex-shrink: 0; }
.info-item .value { color: #303133; font-weight: bold; word-break: break-all; text-align: right; }

.media-container { position: relative; background: #000; border-radius: 4px; overflow: hidden; }
.media-content { width: 100%; height: 100%; object-fit: contain; background-color: #000; display: block; }
.media-count { position: absolute; bottom: 5px; right: 5px; background: rgba(0,0,0,0.6); color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 10px; }
.no-media { height: 50px; background: #f5f7fa; color: #c0c4cc; display: flex; align-items: center; justify-content: center; font-size: 12px; border-radius: 4px; }

.popup-actions { margin-top: 15px; text-align: right; border-top: 1px dashed #eee; padding-top: 10px; }

/* 滚动条 */
.scroll-content::-webkit-scrollbar { width: 6px; }
.scroll-content::-webkit-scrollbar-thumb { background: #dcdfe6; border-radius: 3px; }
.scroll-content::-webkit-scrollbar-track { background: #f5f7fa; }
</style>