<template>
  <div class="page-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline data-id="search-form">
        <el-form-item>
          <el-input
            v-model.trim="searchForm.keyword"
            placeholder="LSS ID / 名称"
            clearable
            data-id="search-keyword"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="状态" clearable data-id="search-status">
            <el-option label="全部" value="" />
            <el-option label="在线" value="ONLINE" />
            <el-option label="离线" value="OFFLINE" />
            <el-option label="繁忙" value="BUSY" />
            <el-option label="维护" value="MAINTENANCE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.enabled" placeholder="启用状态" clearable data-id="search-enabled">
            <el-option label="全部" :value="null" />
            <el-option label="已启用" :value="true" />
            <el-option label="已禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" data-id="btn-search" @click="handleSearch">
            {{ t('查询') }}
          </el-button>
          <el-button :icon="RefreshRight" data-id="btn-reset" @click="handleReset">{{ t('重置') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="lssList"
        stripe
        size="default"
        data-id="lss-table"
        height="100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="lssId" label="LSS ID" min-width="120" sortable="custom" show-overflow-tooltip />
        <el-table-column prop="lssName" :label="t('名称')" min-width="140" sortable="custom" show-overflow-tooltip />
        <el-table-column prop="address" :label="t('地址')" min-width="180" sortable="custom" show-overflow-tooltip />
        <el-table-column prop="status" :label="t('状态')" min-width="100" sortable="custom">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentTasks" :label="t('当前任务')" min-width="100" sortable="custom" align="center">
          <template #default="{ row }">{{ row.currentTasks }} / {{ row.maxTasks }}</template>
        </el-table-column>
        <el-table-column prop="enabled" :label="t('启用')" min-width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.enabled"
              :loading="row._switching"
              @change="(val: boolean) => handleToggleEnabled(row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="ffmpegVersion" label="FFmpeg" show-overflow-tooltip />
        <el-table-column :label="t('摄像头')" min-width="80" align="center">
          <template #default="{ row }">
            <el-button type="primary" link :icon="VideoCamera" @click="handleCameraList(row)" />
          </template>
        </el-table-column>
        <el-table-column label="詳情" align="center">
          <template #default="{ row }">
            <el-button type="primary" link :icon="View" @click="handleViewDetail(row)" />
          </template>
        </el-table-column>
        <el-table-column :label="t('操作')" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)" />
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- LSS 详情抽屉 -->
    <el-drawer v-model="detailDrawerVisible" title="LSS 节点详情" direction="rtl" size="500px" destroy-on-close>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="LSS ID">{{ currentLss?.lssId }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ currentLss?.lssName }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ currentLss?.address }}</el-descriptions-item>
        <el-descriptions-item label="机器 ID">{{ currentLss?.machineId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentLss?.status)" size="small">
            {{ formatStatus(currentLss?.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="任务数">
          {{ currentLss?.currentTasks }} / {{ currentLss?.maxTasks }}
        </el-descriptions-item>
        <el-descriptions-item label="FFmpeg 版本">{{ currentLss?.ffmpegVersion || '-' }}</el-descriptions-item>
        <el-descriptions-item label="系统信息">{{ currentLss?.systemInfo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="启用状态">
          <el-tag :type="currentLss?.enabled ? 'success' : 'info'" size="small">
            {{ currentLss?.enabled ? '已启用' : '已禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(currentLss?.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(currentLss?.updatedAt) }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 摄像头列表抽屉 -->
    <el-drawer
      v-model="cameraDrawerVisible"
      :title="`摄像头列表 - ${currentLss?.lssName || ''}`"
      direction="rtl"
      size="600px"
      destroy-on-close
    >
      <div v-loading="cameraLoading">
        <el-empty v-if="!cameraLoading && cameraList.length === 0" description="暂无关联摄像头" />
        <el-table v-else :data="cameraList" stripe size="small">
          <el-table-column prop="cameraId" label="摄像头 ID" min-width="120" show-overflow-tooltip />
          <el-table-column prop="name" :label="t('名称')" min-width="120" show-overflow-tooltip />
          <el-table-column prop="ip" label="IP" min-width="120" />
          <el-table-column prop="status" :label="t('状态')" min-width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 'ONLINE' ? 'success' : 'danger'" size="small">
                {{ row.status === 'ONLINE' ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="enabled" :label="t('启用')" min-width="70" align="center">
            <template #default="{ row }">
              <el-tag :type="row.enabled ? 'success' : 'info'" size="small">
                {{ row.enabled ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="cameraList.length > 0" class="camera-count">共 {{ cameraList.length }} 个摄像头</div>
      </div>
    </el-drawer>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, RefreshRight, Delete, View, Edit, VideoCamera } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listLssNodes, deleteLssNode, setLssNodeEnabled } from '@/api/lss'
import { adminListCameras } from '@/api/camera'
import type { LssNodeDTO, LssNodeStatus, LssNodeListRequest, CameraInfoDTO } from '@/types'
import dayjs from 'dayjs'
import { useI18n } from 'vue-i18n'

const { t } = useI18n({ useScope: 'global' })

// 格式化状态显示
function formatStatus(status: LssNodeStatus | undefined): string {
  switch (status) {
    case 'ONLINE':
      return '在线'
    case 'OFFLINE':
      return '离线'
    case 'BUSY':
      return '繁忙'
    case 'MAINTENANCE':
      return '维护中'
    default:
      return '-'
  }
}

// 获取状态标签类型
function getStatusTagType(status: LssNodeStatus | undefined): 'success' | 'danger' | 'warning' | 'info' {
  switch (status) {
    case 'ONLINE':
      return 'success'
    case 'OFFLINE':
      return 'danger'
    case 'BUSY':
      return 'warning'
    case 'MAINTENANCE':
      return 'info'
    default:
      return 'info'
  }
}

// 格式化时间
function formatTime(time: string | undefined): string {
  if (!time) return '-'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const loading = ref(false)
const lssList = ref<(LssNodeDTO & { _switching?: boolean })[]>([])
const tableRef = ref()

// 抽屉状态
const detailDrawerVisible = ref(false)
const currentLss = ref<LssNodeDTO | null>(null)

// 摄像头列表抽屉状态
const cameraDrawerVisible = ref(false)
const cameraLoading = ref(false)
const cameraList = ref<CameraInfoDTO[]>([])

// 排序状态
const sortState = reactive<{
  sortBy: string
  sortDir: 'ASC' | 'DESC' | undefined
}>({
  sortBy: '',
  sortDir: undefined
})

// 搜索表单
const searchForm = reactive<{
  keyword: string
  status: LssNodeStatus | ''
  enabled: boolean | null
}>({
  keyword: '',
  status: '',
  enabled: null
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

async function getList() {
  loading.value = true
  try {
    const params: LssNodeListRequest = {
      page: currentPage.value,
      size: pageSize.value
    }
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword
    }
    if (searchForm.status) {
      params.status = searchForm.status
    }
    if (searchForm.enabled !== null) {
      params.enabled = searchForm.enabled
    }
    if (sortState.sortBy) {
      params.sortBy = sortState.sortBy
      params.sortDir = sortState.sortDir
    }

    const res = await listLssNodes(params)
    if (res.success && res.data) {
      lssList.value = res.data.list
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.errMessage || '获取列表失败')
    }
  } catch (error) {
    console.error('获取 LSS 列表失败', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  getList()
}

function handleReset() {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.enabled = null
  currentPage.value = 1
  sortState.sortBy = ''
  sortState.sortDir = undefined
  getList()
}

function handleSortChange({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) {
  sortState.sortBy = prop || ''
  sortState.sortDir = order === 'ascending' ? 'ASC' : order === 'descending' ? 'DESC' : undefined
  getList()
}

function handleSizeChange(val: number) {
  pageSize.value = val
  currentPage.value = 1
  getList()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  getList()
}

function handleViewDetail(row: LssNodeDTO) {
  currentLss.value = row
  detailDrawerVisible.value = true
}

function handleEdit(row: LssNodeDTO) {
  handleCameraList(row)
}

async function handleCameraList(row: LssNodeDTO) {
  currentLss.value = row
  cameraDrawerVisible.value = true
  cameraLoading.value = true
  cameraList.value = []

  try {
    const res = await adminListCameras({ lssId: row.lssId })
    if (res.success && res.data) {
      cameraList.value = res.data.list || []
    } else {
      ElMessage.error(res.errMessage || '获取摄像头列表失败')
    }
  } catch (error) {
    console.error('获取摄像头列表失败', error)
    ElMessage.error('获取摄像头列表失败')
  } finally {
    cameraLoading.value = false
  }
}

async function handleToggleEnabled(row: LssNodeDTO & { _switching?: boolean }, enabled: boolean) {
  row._switching = true
  try {
    const res = await setLssNodeEnabled(row.lssId, enabled)
    if (res.success) {
      ElMessage.success(enabled ? '已启用' : '已禁用')
    } else {
      // 恢复原状态
      row.enabled = !enabled
      ElMessage.error(res.errMessage || '操作失败')
    }
  } catch (error) {
    row.enabled = !enabled
    console.error('切换启用状态失败', error)
    ElMessage.error('操作失败')
  } finally {
    row._switching = false
  }
}

async function handleDelete(row: LssNodeDTO) {
  try {
    await ElMessageBox.confirm(`确定要删除 LSS 节点 "${row.lssName}" 吗？`, '提示', {
      type: 'warning'
    })
    const res = await deleteLssNode(row.lssId)
    if (res.success) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(res.errMessage || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }
}

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

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.search-form {
  flex-shrink: 0;
  margin-bottom: 16px;
  padding: 16px 16px 4px 16px;
  background: #f5f7fa;

  :deep(.el-form-item) {
    margin-bottom: 12px;
    margin-right: 16px;
  }

  :deep(.el-input),
  :deep(.el-select) {
    width: 160px;
  }

  :deep(.el-button--primary) {
    background-color: #4f46e5;
    border-color: #4f46e5;

    &:hover,
    &:focus {
      background-color: #6366f1;
      border-color: #6366f1;
    }
  }
}

.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.pagination-container {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;

  :deep(.el-pagination) {
    .el-pager li.is-active {
      background-color: #4f46e5;
      color: #fff;
    }

    .el-pager li:not(.is-active):hover {
      color: #4f46e5;
    }

    .btn-prev:hover,
    .btn-next:hover {
      color: #4f46e5;
    }
  }
}

.camera-count {
  margin-top: 16px;
  text-align: right;
  color: #666;
  font-size: 14px;
}

// 抽屉样式
:deep(.el-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #e5e7eb;
  }

  .el-drawer__body {
    padding: 16px;
  }

  .el-descriptions {
    .el-descriptions__label {
      width: 100px;
      font-weight: 600;
    }
  }
}

// 表格样式
:deep(.el-table) {
  --el-table-row-hover-bg-color: #f0f0ff;

  .el-table__row--striped td.el-table__cell {
    background-color: #f8f9fc;
  }

  .el-table__header th {
    background-color: #f5f7fa;
    color: #333;
    font-weight: 600;
  }

  .el-button--primary.is-link {
    color: #4f46e5;

    &:hover {
      color: #6366f1;
    }
  }

  .caret-wrapper {
    .sort-caret.ascending {
      border-bottom-color: #4f46e5;
    }

    .sort-caret.descending {
      border-top-color: #4f46e5;
    }
  }
}
</style>
