<template>
  <ModalDialog :visible="visible" :title="institution?.name || ''" @close="handleClose">
    <div class="institution-detail" ref="detailContainer">
      <!-- 基本信息和摄像头区域 -->
      <div class="detail-section detail-section-first" style="height: 936px">
        <!-- 基本信息 -->
        <div class="basic-info">
          <div class="section-title"><span class="title-dot"></span>基本信息</div>
          <table class="info-table">
            <tbody>
              <tr>
                <td colspan="3" class="info-td info-td-header">
                  <div class="header-content">
                    <div class="avatar">
                      <i class="iconfont icon-yanglaoyuan"></i>
                    </div>
                    <div>
                      <div class="header-name">张爱国 (院长)</div>
                      <div class="header-phone">联系电话: 132438245837</div>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="info-td info-td-data">
                  <NumberAnimation
                    :value="120"
                    :unit="'个'"
                    :style="{ fontSize: '48px', color: '#00FFE6', justifyContent: 'center' }"
                  />
                  <div class="data-label">床位数量</div>
                </td>
                <td class="info-td info-td-data">
                  <NumberAnimation
                    :value="98"
                    :unit="'人'"
                    :style="{ fontSize: '48px', color: '#00FFE6', justifyContent: 'center' }"
                  />
                  <div class="data-label">在住老人</div>
                </td>
                <td class="info-td info-td-data">
                  <NumberAnimation
                    :value="17"
                    :unit="'人'"
                    :style="{ fontSize: '48px', color: '#00FFE6', justifyContent: 'center' }"
                  />
                  <div class="data-label">护工人数</div>
                </td>
              </tr>
              <tr>
                <td class="info-td info-td-data">
                  <NumberAnimation
                    :value="81.7"
                    :decimals="1"
                    :unit="'%'"
                    :style="{ fontSize: '48px', color: '#00FFE6', justifyContent: 'center' }"
                  />
                  <div class="data-label">入住率</div>
                </td>
                <td class="info-td info-td-data">
                  <NumberAnimation
                    :value="98.3"
                    :decimals="1"
                    :unit="'%'"
                    :style="{ fontSize: '48px', color: '#00ff4e', justifyContent: 'center' }"
                  />
                  <div class="data-label">服务满意度</div>
                </td>
                <td class="info-td info-td-data">
                  <NumberAnimation
                    :value="15"
                    :unit="'处'"
                    :style="{ fontSize: '48px', color: '#ff1607', justifyContent: 'center' }"
                  />
                  <div class="data-label">机构安全隐患</div>
                </td>
              </tr>
              <tr>
                <td colspan="3" class="info-td info-td-footer">
                  <div class="footer-content">
                    <div class="footer-row">
                      <span>成立时间: 2015年3月</span>
                      <span>建筑面积: 2400平方米</span>
                    </div>
                    <div class="footer-row">
                      <span>机构性质: 公办</span>
                      <span>服务等级: 四星</span>
                    </div>
                    <div class="footer-address">
                      所在地址: 河南省周口市淮阳区淮都大道与陈州路交叉口向东
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 摄像头 -->
        <div class="camera-section">
          <div class="section-title"><span class="title-dot"></span>摄像头</div>
          <table class="camera-table">
            <tbody>
              <tr>
                <td class="camera-td camera-td-label">
                  <div class="camera-label">消防安全摄像头</div>
                </td>
                <td class="camera-td camera-td-count">
                  <div class="camera-count">5个</div>
                </td>
                <td class="camera-td camera-td-videos">
                  <div class="camera-videos">
                    <div v-for="i in 3" :key="'cam1-' + i" class="camera-item">
                      <video class="camera-video" autoplay muted></video>
                    </div>
                    <div
                      v-for="i in 2"
                      :key="'cam1-offline-' + i"
                      class="camera-item camera-item-offline"
                    >
                      <span class="offline-text">摄像头不在线</span>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="camera-td camera-td-label">
                  <div class="camera-label">明厨亮灶摄像头</div>
                </td>
                <td class="camera-td camera-td-count">
                  <div class="camera-count">4个</div>
                </td>
                <td class="camera-td camera-td-videos">
                  <div class="camera-videos">
                    <div v-for="i in 4" :key="'cam2-' + i" class="camera-item">
                      <video class="camera-video" autoplay muted></video>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="camera-td camera-td-label">
                  <div class="camera-label">活动场所摄像头</div>
                </td>
                <td class="camera-td camera-td-count">
                  <div class="camera-count">2个</div>
                </td>
                <td class="camera-td camera-td-videos">
                  <div class="camera-videos">
                    <div v-for="i in 2" :key="'cam3-' + i" class="camera-item">
                      <video class="camera-video" autoplay muted></video>
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 五维整治标准 -->
      <div class="detail-section detail-section-last">
        <div class="section-title"><span class="title-dot"></span>五维整治标准</div>

        <div class="five-dimensions">
          <!-- 钱花得明白 -->
          <div :ref="(el) => setDimensionRef(el as HTMLElement, 0)" class="dimension-wrapper">
            <FinanceDimension v-if="loadedDimensions[0]" :visible="visible" />
            <div v-else class="dimension-placeholder">
              <div class="loading-spinner"></div>
              <div class="loading-text">加载中...</div>
            </div>
          </div>
          <!-- 饭吃得满意 -->
          <div
            :ref="(el) => setDimensionRef(el as HTMLElement, 1)"
            class="dimension-wrapper"
            style="margin-top: 60px"
          >
            <FoodSatisfactionDimension v-if="loadedDimensions[1]" :visible="visible" />
            <div v-else class="dimension-placeholder">
              <div class="loading-spinner"></div>
              <div class="loading-text">加载中...</div>
            </div>
          </div>
          <!-- 衣穿得舒适 -->
          <div
            :ref="(el) => setDimensionRef(el as HTMLElement, 2)"
            class="dimension-wrapper"
            style="margin-top: 60px"
          >
            <ClothingSatisfactionDimension v-if="loadedDimensions[2]" :visible="visible" />
            <div v-else class="dimension-placeholder">
              <div class="loading-spinner"></div>
              <div class="loading-text">加载中...</div>
            </div>
          </div>
          <!-- 房住得安全 -->
          <div
            :ref="(el) => setDimensionRef(el as HTMLElement, 3)"
            class="dimension-wrapper"
            style="margin-top: 60px"
          >
            <HouseSafetyDimension v-if="loadedDimensions[3]" :visible="visible" />
            <div v-else class="dimension-placeholder">
              <div class="loading-spinner"></div>
              <div class="loading-text">加载中...</div>
            </div>
          </div>
          <!-- 人活得体面 -->
          <div
            :ref="(el) => setDimensionRef(el as HTMLElement, 4)"
            class="dimension-wrapper"
            style="margin-top: 60px"
          >
            <DignityDimension v-if="loadedDimensions[4]" :visible="visible" />
            <div v-else class="dimension-placeholder">
              <div class="loading-spinner"></div>
              <div class="loading-text">加载中...</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </ModalDialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import ModalDialog from './ModalDialog.vue'
import NumberAnimation from './NumberAnimation.vue'
import FinanceDimension from './FinanceDimension.vue'
import FoodSatisfactionDimension from './FoodSatisfactionDimension.vue'
import ClothingSatisfactionDimension from './ClothingSatisfactionDimension.vue'
import HouseSafetyDimension from './HouseSafetyDimension.vue'
import DignityDimension from './DignityDimension.vue'

interface Props {
  visible: boolean
  institution?: any
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
}>()

// 五维组件的引用 - 使用 Map 存储，key 为索引
const dimensionRefs = ref<Map<number, HTMLElement>>(new Map())
// 记录哪些维度已经加载
const loadedDimensions = ref<boolean[]>(new Array(5).fill(false))
// IntersectionObserver 实例
let observer: IntersectionObserver | null = null

// 设置 ref 的函数
const setDimensionRef = (el: HTMLElement | null, index: number) => {
  if (el) {
    dimensionRefs.value.set(index, el)
  }
}

// 创建 IntersectionObserver
const createObserver = () => {
  if (observer) {
    observer.disconnect()
  }

  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          // 通过遍历 Map 找到对应的索引
          let foundIndex = -1
          dimensionRefs.value.forEach((el, idx) => {
            if (el === entry.target) {
              foundIndex = idx
            }
          })

          if (foundIndex !== -1 && !loadedDimensions.value[foundIndex]) {
            // 使用 requestAnimationFrame 确保在下一帧渲染，避免阻塞
            requestAnimationFrame(() => {
              loadedDimensions.value[foundIndex] = true
            })
            // 加载后取消观察
            observer?.unobserve(entry.target)
          }
        }
      })
    },
    {
      rootMargin: '500px', // 在元素进入视口前500px开始加载
      threshold: 0.1,
    }
  )

  // 观察所有维度组件容器
  dimensionRefs.value.forEach((el) => {
    if (el) {
      observer?.observe(el)
    }
  })
}

// 重置加载状态
const resetLoadedDimensions = () => {
  loadedDimensions.value = new Array(5).fill(false)
}

// 监听弹窗可见性变化
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      // 弹窗打开时重置状态
      resetLoadedDimensions()
      // 等待DOM更新后创建观察者
      requestAnimationFrame(() => {
        createObserver()
      })
    } else {
      // 弹窗关闭时清理观察者
      if (observer) {
        observer.disconnect()
        observer = null
      }
    }
  }
)

const handleClose = () => {
  emit('close')
}

onUnmounted(() => {
  if (observer) {
    observer.disconnect()
    observer = null
  }
})
</script>

<style lang="scss" scoped>
$neon-cyan: #00ffe6;

:deep(.modal-body) {
  padding-right: 0 !important;
}

// 弹窗内容样式
.institution-detail {
  width: 100%;
  height: 100%;
  padding-right: 40px;
  overflow-y: auto;
  color: $neon-cyan;

  // 自定义滚动条
  &::-webkit-scrollbar {
    width: 12px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(0, 255, 230, 0.1);
    border-radius: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 255, 230, 0.5);
    border-radius: 6px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: rgba(0, 255, 230, 0.8);
  }

  .detail-section {
    margin-bottom: 60px;

    &.detail-section-first {
      display: flex;
      gap: 20px;
      justify-content: space-between;
    }

    &.detail-section-last {
      margin-bottom: 0;
    }

    .basic-info {
      width: 958px;
      height: 100%;

      .info-table {
        width: 100%;
        height: calc(100% - 92px);
        border-collapse: collapse;

        .info-td {
          border: 1px solid #07615e;

          &.info-td-header {
            vertical-align: middle;
            padding: 0 30px;

            .header-content {
              display: flex;
              align-items: center;
              gap: 20px;

              .avatar {
                width: 160px;
                height: 160px;
                background: rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;

                .iconfont {
                  font-size: 100px;
                  color: $neon-cyan;
                }
              }

              .header-name {
                font-size: 32px;
                font-weight: 400;
                color: #00d6c0;
              }

              .header-phone {
                font-size: 32px;
                color: $neon-cyan;
                margin-top: 10px;
              }
            }
          }

          &.info-td-data {
            text-align: center;
            padding: 0 20px;
            width: 33.333%;

            .data-label {
              font-size: 30px;
              color: $neon-cyan;
              margin-top: 10px;
            }
          }

          &.info-td-footer {
            padding: 0 30px;

            .footer-content {
              font-size: 30px;
              color: rgba(0, 255, 230, 0.7);
              line-height: 2;

              .footer-row {
                display: flex;

                span {
                  flex: 1;
                }
              }

              .footer-address {
                color: rgba(0, 255, 230, 0.7);
              }
            }
          }
        }
      }
    }

    .camera-section {
      width: 2196px;
      height: 100%;

      .camera-table {
        width: 100%;
        max-width: 100%;
        height: calc(100% - 92px);
        border-collapse: collapse;
        table-layout: fixed;

        .camera-td {
          border: 1px solid #07615e;

          &.camera-td-label {
            width: 80px;
            vertical-align: middle;
            padding: 20px;
            text-align: center;

            .camera-label {
              font-size: 28px;
              letter-spacing: 4px;
              color: #00d6c0;
              font-weight: 400;
              writing-mode: vertical-rl;
              text-orientation: mixed;
            }
          }

          &.camera-td-count {
            width: 100px;
            vertical-align: middle;
            padding: 20px;
            text-align: center;

            .camera-count {
              font-size: 32px;
              color: $neon-cyan;
              font-weight: 400;
            }
          }

          &.camera-td-videos {
            width: 2016px;
            padding: 0 30px;
            overflow-x: auto;

            .camera-videos {
              display: flex;
              gap: 16px;
              height: 240px;
              min-width: 0;

              .camera-item {
                flex-shrink: 0;
                width: 360px;
                background: rgba(255, 255, 255, 0.2);
                display: flex;
                align-items: center;
                justify-content: center;

                .camera-video {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }
              }

              .camera-item-offline {
                flex-shrink: 0;
                width: 360px;
                background: rgba(255, 71, 87, 0.1);
                border: 1px solid #ff4757;
                display: flex;
                align-items: center;
                justify-content: center;

                .offline-text {
                  color: #ff4757;
                  font-size: 16px;
                  font-weight: 600;
                }
              }
            }
          }
        }
      }
    }

    .section-title {
      display: flex;
      align-items: center;
      font-size: 40px;
      color: rgba(0, 255, 230, 0.9);
      line-height: 72px;
      letter-spacing: 2px;
      margin-bottom: 20px;
      font-weight: 500;

      .title-dot {
        display: inline-block;
        width: 18px;
        height: 18px;
        background-color: #0efee6;
        border-radius: 50%;
        margin-right: 12px;
        vertical-align: middle;
      }
    }

    .standards-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 30px;

      .standard-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;

        .standard-label {
          font-size: 18px;
          color: $neon-cyan;
          margin-top: 10px;
        }
      }
    }
  }

  .five-dimensions {
    display: flex;
    flex-direction: column;
    gap: 30px;
  }

  .dimension-wrapper {
    min-height: 800px;
  }

  .dimension-placeholder {
    min-height: 800px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed rgba(0, 255, 230, 0.3);
    background: rgba(0, 255, 230, 0.02);

    .loading-spinner {
      width: 60px;
      height: 60px;
      border: 4px solid rgba(0, 255, 230, 0.1);
      border-top-color: #00ffe6;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .loading-text {
      margin-top: 20px;
      font-size: 28px;
      color: rgba(0, 255, 230, 0.6);
    }
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
}
</style>
