<template>
  <ContentWrap>
   
    <div  class="container">
      <el-button-group>
    <el-button @click="updateLayout(1)" :class="{ active: layoutMode === 1 }">
          <Icon :size="16" icon="fa-solid:expand" />
        </el-button>
    <el-button @click="updateLayout(4)" :class="{ active: layoutMode === 4 }">
          <Icon :size="16" icon="ep:menu" />
        </el-button>
    <el-button @click="updateLayout(9)" :class="{ active: layoutMode === 9 }">
          <Icon :size="16" icon="ep:grid" />
        </el-button>
    <el-button type="success" @click="toggleCameraFullScreen">
          <Icon :size="16" icon="ep:monitor" /> 全屏
    </el-button>
  </el-button-group>
    </div>

    <!-- 相机数量大于选择的布局数量时，使用 tabs 分页显示 -->
    <el-tabs v-if="list.length > layoutMode" tab-position="left" style="height: 72vh" class="demo-tabs">
      <el-tab-pane v-for="tabIndex in tabCount" :key="tabIndex" :label="`视频墙 ${tabIndex}`">
        <div class="video-grid">
          <el-row v-for="rowIndex in rows" :key="rowIndex" class="grid-row">
            <el-col v-for="colIndex in cols" :key="colIndex" :span="24 / cols" :style="{ height: videoHeight }" class="grid-col">
              <Camera 
                v-if="getCameraId(tabIndex, rowIndex, colIndex)"
                :cameraId="getCameraId(tabIndex, rowIndex, colIndex)" 
                :ptzShow="false" 
              />
              <div v-else class="placeholder">
                <Icon icon="ep:video-camera-filled" :size="40" />
              </div>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 相机数量小于等于选择的布局数量时，直接显示 -->
    <div v-else class="video-grid" style="height: 72vh">
      <el-row v-for="rowIndex in rows" :key="rowIndex" class="grid-row">
        <el-col v-for="colIndex in cols" :key="colIndex" :span="24 / cols" :style="{ height: videoHeight }" class="grid-col">
          <Camera 
            v-if="getSingleCameraId(rowIndex, colIndex)"
            :cameraId="getSingleCameraId(rowIndex, colIndex)" 
            :ptzShow="false" 
          />
          <div v-else class="placeholder">
            <Icon icon="ep:video-camera-filled" :size="40" />
          </div>
        </el-col>
      </el-row>
    </div>
  </ContentWrap>

  <!-- 全屏相机显示 -->
  <div v-if="cameraFullScreenVisible" class="camera-fullscreen">
    <div class="camera-fullscreen-hint">按 ESC 键退出全屏</div>
    <div class="camera-fullscreen-content">
      <div class="video-grid">
        <el-row v-for="rowIndex in rows" :key="rowIndex" class="grid-row">
          <el-col v-for="colIndex in cols" :key="colIndex" :span="24 / cols" :style="{ height: fullscreenVideoHeight }" class="grid-col">
            <Camera 
              v-if="getSingleCameraId(rowIndex, colIndex)"
              :cameraId="getSingleCameraId(rowIndex, colIndex)" 
              :ptzShow="false" 
            />
            <div v-else class="placeholder">
              <Icon icon="ep:video-camera-filled" :size="40" />
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Camera from '@/components/camera/camera.vue'
import { CameraApi, CameraVO } from '@/api/logistics/camera'
/** 相机 列表 */
defineOptions({ name: 'Camera' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const list = ref<CameraVO[]>([]) // 列表的数据
const layoutMode = ref(4) // 默认4个视频布局
const rows = ref(2) // 行数
const cols = ref(2) // 列数
const cameraFullScreenVisible = ref(false) // 全屏相机显示状态

/** 查询列表 */
const getList = async () => {
  try {
    const data = await CameraApi.getCameraList()
    list.value = data
  } finally {

  }
}

// 根据 layoutMode 计算行数和列数
const updateLayout = (mode: number) => {
  layoutMode.value = mode
  if (mode === 1) {
    rows.value = 1
    cols.value = 1
  } else if (mode === 4) {
    rows.value = 2
    cols.value = 2
  } else if (mode === 9) {
    rows.value = 3
    cols.value = 3
  }
}

// 根据 topNum 动态调整 tab 个数
const tabCount = computed(() => {
  return Math.ceil(list.value.length / layoutMode.value);
});

// 根据 tab 索引获取对应的数据项
const getItemsForTab = (tabIndex: number) => {
  const startIndex = (tabIndex - 1) * layoutMode.value;
  const endIndex = startIndex + layoutMode.value;
  return list.value.slice(startIndex, endIndex);
};

const toggleFullScreen = () => {
  const contentWrap = document.querySelector('.content-wrap');
  if (!contentWrap) return;

  if (!document.fullscreenElement) {
    contentWrap.requestFullscreen().catch(err => {
      console.error(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
    });
  } else {
    document.exitFullscreen().catch(err => {
      console.error(`Error attempting to exit full-screen mode: ${err.message} (${err.name})`);
    });
  }
};

// 进入全屏相机模式
const toggleCameraFullScreen = () => {
  cameraFullScreenVisible.value = true;
};

// 退出全屏相机模式
const exitCameraFullScreen = () => {
  cameraFullScreenVisible.value = false;
};

// 处理键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape') {
    exitCameraFullScreen();
  }
};

// 监听键盘事件
watch(() => cameraFullScreenVisible.value, (newVal) => {
  if (newVal) {
    document.addEventListener('keydown', handleKeyDown);
  } else {
    document.removeEventListener('keydown', handleKeyDown);
  }
});

// 计算 videoHeight
const videoHeight = computed(() => {
  const tabHeight = 72 * window.innerHeight / 100;
  const rowHeight = tabHeight / rows.value;
  return `${rowHeight}px`;
});

// 计算全屏模式下的 videoHeight
const fullscreenVideoHeight = computed(() => {
  const fullscreenContentHeight = window.innerHeight;
  const rowHeight = fullscreenContentHeight / rows.value;
  return `${rowHeight}px`;
});

// 获取每个单元格的 cameraId (分页模式)
const getCameraId = (tabIndex: number, rowIndex: number, colIndex: number) => {
  const startIndex = (tabIndex - 1) * layoutMode.value;
  const index = startIndex + (rowIndex - 1) * cols.value + colIndex - 1;
  return list.value[index]?.id || null;
};

// 获取每个单元格的 cameraId (单页模式)
const getSingleCameraId = (rowIndex: number, colIndex: number) => {
  const index = (rowIndex - 1) * cols.value + colIndex - 1;
  return list.value[index]?.id || null;
};

/** 初始化 **/
onMounted(() => {
  getList();
});
</script>

<style scoped>
.container {
  display: flex;
  justify-content: flex-end; /* 将按钮组放到右侧 */
  padding-bottom: 10px; /* 可选，增加间距 */
}

.container .el-button.active {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.video-grid {
  width: 100%;
  height: 100%;
  border: 1px solid #dcdfe6;
}

.video-grid :deep(.el-row) {
  border-bottom: 1px solid #dcdfe6;
  margin: 0 !important;
}

.video-grid :deep(.el-row:last-child) {
  border-bottom: none;
}

.grid-col {
  border: 1px solid #656464;
  padding: 0 !important;
  background-color: #f5f5f5;
}

.grid-col:last-child {
  border-right: 1px solid #656464;
}

.placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e0e0e0;
  color: #999;
}

/* 全屏相机样式 */
.camera-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #f5f5f5;
  z-index: 9999;
  display: flex;
  flex-direction: column;
}

.camera-fullscreen-hint {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 8px 16px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 4px;
  font-size: 13px;
  z-index: 10000;
  pointer-events: none;
  transition: opacity 0.3s;
}

.camera-fullscreen-content {
  flex: 1;
  padding: 0;
  overflow: hidden;
  background-color: #f5f5f5;
}

.camera-fullscreen-content .video-grid {
  height: 100%;
  border: 1px solid #dcdfe6;
}

.camera-fullscreen-content :deep(.el-row) {
  border-bottom: 1px solid #dcdfe6;
  margin: 0 !important;
}

.camera-fullscreen-content :deep(.el-row:last-child) {
  border-bottom: none;
}

.camera-fullscreen-content .grid-col {
  border: 1px solid #656464;
  padding: 0 !important;
  background-color: #f5f5f5;
}

.camera-fullscreen-content .grid-col:last-child {
  border-right: 1px solid #656464;
}

.camera-fullscreen-content .placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e0e0e0;
  color: #999;
}
</style>