<template>
  <div class="monitor-page">
    <!-- 顶部工具栏 -->
    <div class="monitor-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="addTab" icon="Plus">
          {{ t('新建标签') }}
        </el-button>
        <el-select v-model="currentGridSize" @change="handleGridSizeChange" style="width: 120px">
          <el-option label="2 x 2" :value="2" />
          <el-option label="3 x 3" :value="3" />
          <el-option label="4 x 4" :value="4" />
        </el-select>
      </div>
      <div class="toolbar-right">
        <el-button @click="saveConfig" icon="FolderChecked">
          {{ t('保存配置') }}
        </el-button>
      </div>
    </div>

    <!-- 标签栏 -->
    <div class="monitor-tabs">
      <el-tabs v-model="activeTabId" type="card" editable @edit="handleTabEdit">
        <el-tab-pane v-for="tab in tabs" :key="tab.id" :label="tab.name" :name="tab.id" :closable="tabs.length > 1" />
      </el-tabs>
    </div>

    <!-- 网格区域 -->
    <div class="monitor-grid-container">
      <VideoGrid
        v-if="currentTab"
        :grid-size="currentTab.gridSize"
        :slots="currentTab.slots"
        @select-camera="handleSelectCamera"
        @update-slot="handleUpdateSlot"
      />
    </div>

    <!-- 摄像头选择器 -->
    <CameraSelector
      v-model:visible="selectorVisible"
      :current-position="selectedPosition"
      @select="handleCameraSelected"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus, FolderChecked } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import VideoGrid from '@/components/monitor/VideoGrid.vue'
import CameraSelector from '@/components/monitor/CameraSelector.vue'
import { useMonitorStore, type GridSlot, type CameraVendor } from '@/composables/useMonitorStore'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const { tabs, activeTabId, currentTab, addTab, removeTab, updateTab, saveToStorage, loadFromStorage } =
  useMonitorStore()

const selectorVisible = ref(false)
const selectedPosition = ref(0)

const currentGridSize = computed({
  get: () => currentTab.value?.gridSize || 2,
  set: (val) => {
    if (currentTab.value) {
      updateTab(currentTab.value.id, { gridSize: val })
    }
  }
})

function handleGridSizeChange(size: number) {
  if (currentTab.value) {
    updateTab(currentTab.value.id, { gridSize: size as 2 | 3 | 4 })
    saveToStorage()
  }
}

function handleTabEdit(targetName: string | number, action: 'add' | 'remove') {
  if (action === 'add') {
    addTab()
  } else if (action === 'remove') {
    removeTab(String(targetName))
  }
}

function handleSelectCamera(position: number) {
  selectedPosition.value = position
  selectorVisible.value = true
}

function handleCameraSelected(camera: {
  id: string
  name: string
  streamType: 'webrtc' | 'cloudflare'
  streamUrl: string
  vendor?: CameraVendor
  ptzHost?: string
  ptzUsername?: string
  ptzPassword?: string
}) {
  if (!currentTab.value) return

  const newSlot: GridSlot = {
    position: selectedPosition.value,
    cameraId: camera.id,
    cameraName: camera.name,
    streamType: camera.streamType,
    streamUrl: camera.streamUrl,
    // PTZ 配置
    vendor: camera.vendor,
    ptzHost: camera.ptzHost,
    ptzUsername: camera.ptzUsername,
    ptzPassword: camera.ptzPassword
  }

  const existingSlots = currentTab.value.slots.filter((s) => s.position !== selectedPosition.value)
  updateTab(currentTab.value.id, {
    slots: [...existingSlots, newSlot]
  })

  selectorVisible.value = false
  saveToStorage()
}

function handleUpdateSlot(position: number, slot: Partial<GridSlot> | null) {
  if (!currentTab.value) return

  if (slot === null) {
    // 移除格子
    const newSlots = currentTab.value.slots.filter((s) => s.position !== position)
    updateTab(currentTab.value.id, { slots: newSlots })
  } else {
    // 更新格子
    const existingSlots = currentTab.value.slots.filter((s) => s.position !== position)
    updateTab(currentTab.value.id, {
      slots: [...existingSlots, { position, ...slot } as GridSlot]
    })
  }
  saveToStorage()
}

function saveConfig() {
  saveToStorage()
  ElMessage.success('配置已保存')
}

onMounted(() => {
  loadFromStorage()
})
</script>

<style lang="scss" scoped>
.monitor-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
  // background-color: var(--bg-container);

  // 全局去除圆角
  :deep(.el-button) {
    border-radius: var(--radius-base);
  }

  :deep(.el-select) {
    .el-input__wrapper {
      border-radius: var(--radius-base);
    }
  }

  :deep(.el-tabs__item) {
    border-radius: 0;
  }

  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
    border-radius: 0;
  }
}

.monitor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--bg-container);
  border-radius: var(--radius-base);
  margin-bottom: var(--spacing-base);

  .toolbar-left {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .toolbar-right {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.monitor-tabs {
  margin-bottom: 0;
  background-color: var(--bg-container);
  padding-top: var(--spacing-base);
  padding-left: var(--spacing-base);
  padding-right: var(--spacing-base);

  :deep(.el-tabs__header) {
    margin: 0;
    border-radius: 0;
  }

  :deep(.el-tabs__item) {
    height: 36px;
    line-height: 36px;
    border-radius: 0;
  }

  :deep(.el-tabs--card > .el-tabs__header) {
    border-radius: 0;
  }

  :deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
    border-radius: 0;
  }
}

.monitor-grid-container {
  flex: 1;
  background-color: var(--bg-container);
  border-radius: var(--radius-base);
  // padding-top: var(--spacing-base);
  padding-left: var(--spacing-base);
  padding-right: var(--spacing-base);
  padding-bottom: var(--spacing-base);
  overflow: auto;
}
</style>
