<template>
  <div 
    v-if="visible" 
    class="plot-popup-container" 
    :style="{ left: position.x + 'px', top: position.y + 'px' }"
  >
    <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">小班号：{{ data.plotData?.nyxbh || '无编号' }}</span>
            <el-tag size="small" :type="data.plotData?.status === '1' ? 'success' : 'info'">
              {{ data.plotData?.status === '1' ? '已采集' : '未完成' }}
            </el-tag>
          </div>
        </div>

        <div class="scroll-content">
          <div class="content-padding">
            
            <div class="info-grid">
              <div class="info-item" v-for="(label, key) in plotMap" :key="key">
                <span class="label">{{ label }}：</span>
                <span class="value">{{ getPlotDisplay(key) }}</span>
              </div>
            </div>

            <div class="media-container" v-if="mediaItems.length > 0">
              <el-carousel height="180px" indicator-position="none" :interval="5000" 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="divider" v-if="data.sampleData"></div>

            <div class="stats-group" v-if="data.sampleData">
              <div class="stats-title">小班下样地统计</div>
              <div class="stats-grid">
                <div class="stat-box" v-for="(val, key) in data.sampleData" :key="key">
                  <span class="stat-name">{{ getStatLabel(key) }}</span>
                  <span class="stat-num">{{ val }}</span>
                </div>
              </div>
            </div>

            <div class="popup-actions">
              <el-button 
                type="primary" 
                size="small" 
                plain 
                @click="handleViewSample"
                :disabled="!data.sampleData" 
                :loading="loadingSample"
              >
                查看样地详情
              </el-button>
            </div>

          </div>
        </div>
      </el-card>

      <div v-if="sampleVisible" class="sample-wrapper">
        <SamplePopup 
          :visible="true" 
          :data="sampleData" 
          @close="sampleVisible = false"
        />
      </div>

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

<script setup>
import { computed, ref } from "vue";
import { ElCard, ElButton, ElCarousel, ElCarouselItem, ElTag, ElImage } from "element-plus";
// ✅ 引入样地组件
import SamplePopup from "./SamplePopup.vue";


const props = defineProps({
  visible: Boolean,
  data: { type: Object, default: () => ({ plotData: {}, sampleData: {} }) },
  position: { type: Object, default: () => ({ x: 0, y: 0 }) },
});

// 因为逻辑内聚了，这里不需要 emit view-sample 了
const emit = defineEmits(['enter-sample', 'enter-side', 'close']);

const MEDIA_BASE_URL = '/photos'; // 媒体路径前缀

// --- 样地弹窗相关状态 ---
const sampleVisible = ref(false);
const sampleData = ref({});
const loadingSample = ref(false);

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  return dateStr.split(' ')[0];
};

// 媒体数据处理
const mediaItems = computed(() => {
  const pd = props.data.plotData || {};
  const imgs = Array.isArray(pd.images) ? pd.images : [];
  const vids = Array.isArray(pd.videos) ? pd.videos : [];
  let imgCounter = 0;
  return [
    ...imgs.map((src) => ({ type: "image", src, imgIndex: imgCounter++ })),
    ...vids.map((src) => ({ type: "video", src })),
  ];
});

const allImages = computed(() => {
  const pd = props.data.plotData || {};
  return Array.isArray(pd.images) ? pd.images : [];
});

// 字段映射表
const plotMap = {
  xian: "县名",
  xiang: "乡名",
  cun: "村名",
  nyxbh: "小班号",
  zlwz: "造林位置",
  xbmj: "小班面积",
  lmsyqs: "林木所有权",
  lmqs: "林木权属",
  tdsyq: "土地所有权",
  diLei: "地类",
  linZhong: "林种",
  sllb: "森林类别",
  szzc: "树种组成",
  yssz: "优势树种",
  qiYuan: "起源",
  yuBiDu: "郁闭度",
  pjSg: "平均树高",
  pjXj: "平均胸径",
  pjnl: "平均年龄",
  xbzs: "小班株数",
  meiGqXj: "每公顷蓄积",
  huoLmXj: "活立木蓄积",
  diMao: "地貌",
  poDu: "坡度",
  poXiang: "坡向",
  poWei: "坡位",
  tchd: "土层厚度",
  gclx: "工程类型",
  bcl: "保存率",
  bhdj: "公益林保护等级",
  bhlydj: "保护利用等级",
  sljkdj: "森林健康等级",
  slzhdj: "森林灾害等级",
  collectorName: "采集人员",
  updateTime: "更新时间"
};

function getPlotDisplay(key) {
  const pd = props.data.plotData || {};
  const root = props.data || {}; 
  let val = pd[key];

  if (key === 'zlwz') val = val || root.cun;
  if (key === 'xbmj') return val ? Number(val).toFixed(2) + ' 亩' : '-';
  if (key === 'linZhong') val = val || pd.diLei;
  if (key === 'collectorName') val = val || root.collector;
  if (key === 'updateTime') return formatDate(val || pd.createTime);

  return (val !== null && val !== undefined && val !== '') ? val : '-';
}

const sampleMap = {
  yds: "样地总数",
  ysyfs: "幼树样方数",
  xmyfs: "下木样方数",
  wclyfs: "未成林样方数",
  jjlyfs: "经济林样方数",
  gmyfs: "灌木样方数",
  tbyfs: "藤本样方数",
  cbyfs: "草本样方数",
  dbyfs: "地被样方数",
  mcxms: "目测项目数",
  ssms: "散生单木数",
  spss: "四旁树单木数"
};

function getStatLabel(key) {
  return sampleMap[key] || key;
}

// ✅ 核心逻辑：直接在这里请求样地数据
async function handleViewSample() {
  const pd = props.data.plotData || {};
  const id = pd.id || pd.ID;
  const database = pd.databaseName || pd.database_n || pd.DATABASE_N;

  if (!id || !database) {
    alert("缺少 ID 或 databaseName，无法查询样地");
    return;
  }

  loadingSample.value = true;

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

    if (json.code === 0 && json.data) {
      
      // ✅ 兼容处理：无论后端返回单个对象还是数组，都转成数组
      let rawList = [];
      if (Array.isArray(json.data)) {
        rawList = json.data;
      } else {
        rawList = [json.data];
      }

      // 遍历处理每一个样地的媒体路径
      const processedList = rawList.map(item => processSampleData(item));
      
      sampleData.value = processedList;
      sampleVisible.value = true;
    } else {
      alert("未查询到样地详情数据");
    }
  } catch (error) {
    console.error("样地请求失败", error);
    alert("网络请求失败");
  } finally {
    loadingSample.value = false;
  }
}

// 辅助函数：处理样地媒体路径
function processSampleData(data) {
  const images = [];
  const videos = [];
  
  if (data.mediaPathList && Array.isArray(data.mediaPathList)) {
    data.mediaPathList.forEach(path => {
      const fullUrl = `${MEDIA_BASE_URL}${path}`; 
      const lower = path.toLowerCase();
      if (lower.endsWith('.mp4') || lower.endsWith('.avi')) {
        videos.push(fullUrl);
      } else {
        images.push(fullUrl);
      }
    });
  }
  return { ...data, images, videos };
}
</script>

<style scoped>
/* 1. Main Container: Positioned absolutely on the map */
.plot-popup-container {
  position: absolute;
  z-index: 2000;
  /* Adjust anchor to be above the click point */
  transform: translate(-50%, -100%);
  margin-top: -15px;
  pointer-events: auto;
  /* Allow flex contents to overflow this container if needed */
  width: auto;
}

/* 2. Flex Wrapper: Holds Plot Card (left) and Sample Popup (right) */
.popup-wrapper {
  display: flex;
  align-items: flex-start; /* Align tops */
  gap: 10px; /* Space between the two popups */
}

/* 3. The Plot Card itself */
.popup-card {
  width: 320px;
  border-radius: 8px;
  overflow: visible;
  flex-shrink: 0; /* Prevent shrinking */
}

/* 4. Sample Popup Wrapper */
.sample-wrapper {
  /* No absolute positioning needed here, flex handles it */
  z-index: 2001;
}

/* Arrow indicator for the main popup */
.plot-popup-container::after {
  content: '';
  position: absolute;
  /* Position relative to the main container */
  bottom: -6px;
  left: 160px; /* Center of the first card (320px / 2) */
  transform: translateX(-50%);
  border-width: 6px 6px 0;
  border-style: solid;
  border-color: #fff transparent transparent transparent;
  filter: drop-shadow(0 2px 2px rgba(0,0,0,0.1));
}

/* ... (Keep all your existing inner styles for close-btn, header, media, etc.) ... */
.close-btn {
  position: absolute; top: 8px; right: 12px; font-size: 24px; font-weight: 300; color: #909399; cursor: pointer; z-index: 100; line-height: 1; transition: color 0.2s; user-select: none;
}
.close-btn:hover { color: #f56c6c; }

.popup-header-wrapper { padding: 12px 12px 0 12px; background-color: #fff; border-top-left-radius: 8px; border-top-right-radius: 8px; }
.popup-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 8px; border-bottom: 1px solid #eee; padding-right: 25px; }
.title { font-weight: bold; font-size: 16px; color: #333; }
.scroll-content { max-height: 400px; overflow-y: auto; overflow-x: hidden; }
.content-padding { padding: 10px 12px 12px 12px; }
.scroll-content::-webkit-scrollbar { width: 6px; }
.scroll-content::-webkit-scrollbar-thumb { background: #dcdfe6; border-radius: 3px; }
.scroll-content::-webkit-scrollbar-track { background: #f5f7fa; }
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 10px; font-size: 12px; margin-bottom: 12px; }
.info-item { display: flex; overflow: hidden; white-space: nowrap; }
.info-item .label { color: #909399; flex-shrink: 0; }
.info-item .value { color: #303133; font-weight: 500; overflow: hidden; text-overflow: ellipsis; }
.media-container { position: relative; background: #000; border-radius: 4px; overflow: hidden; margin-bottom: 10px; }
.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: 60px; background: #f5f7fa; color: #c0c4cc; display: flex; align-items: center; justify-content: center; font-size: 12px; border-radius: 4px; margin-bottom: 10px; }
.divider { height: 1px; background-color: #ebeef5; margin: 15px 0; width: 100%; }
.stats-title { font-size: 13px; font-weight: bold; color: #333; margin-bottom: 10px; padding-left: 6px; border-left: 3px solid #409eff; }
.stats-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; }
.stat-box { background-color: #f9f9f9; border: 1px solid #eee; border-radius: 4px; padding: 8px 4px; display: flex; flex-direction: column; align-items: center; justify-content: center; transition: all 0.2s; }
.stat-box:hover { background-color: #ecf5ff; }
.stat-name { font-size: 12px; color: #909399; margin-bottom: 4px; transform: scale(0.9); }
.stat-num { font-size: 14px; font-weight: bold; color: #409eff; }
.popup-actions { margin-top: 15px; text-align: right; border-top: 1px dashed #eee; padding-top: 10px; }
</style>