<template>
  <div class="page-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="queryParams" inline>
        <el-form-item label="机器">
          <el-select
            v-model="queryParams.machineId"
            placeholder="请选择机器"
            style="width: 120px"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="machine in machineList"
              :key="machine.machineId"
              :label="machine.name"
              :value="machine.machineId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择"
            style="width: 120px"
            clearable
            @change="handleQuery"
          >
            <el-option label="在线" value="ONLINE" />
            <el-option label="离线" value="OFFLINE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="table-actions">
      <el-button type="primary" :icon="Plus" @click="handleAdd">新增摄像头</el-button>
      <el-button plain :icon="Refresh" @click="getList">刷新列表</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="filteredList" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="cameraId" label="摄像头ID" min-width="120" show-overflow-tooltip />
      <el-table-column prop="name" label="名称" min-width="120" show-overflow-tooltip />
      <el-table-column prop="ip" label="IP地址" min-width="130" show-overflow-tooltip />
      <el-table-column prop="port" label="端口" width="80" align="center" />
      <el-table-column prop="brand" label="品牌" min-width="100" show-overflow-tooltip />
      <el-table-column prop="machineName" label="所属机器" min-width="100" show-overflow-tooltip />
      <el-table-column prop="capability" label="能力" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.capability === 'ptz_enabled' ? 'success' : 'info'">
            {{ row.capability === 'ptz_enabled' ? 'PTZ' : '仅切换' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 'ONLINE' ? 'success' : 'danger'">
            {{ row.status === 'ONLINE' ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="enabled" label="启用" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.enabled ? 'success' : 'info'">
            {{ row.enabled ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link :icon="View" @click="handleChannel(row)">通道</el-button>
          <el-button type="success" link :icon="Connection" @click="handleCheck(row)">检测</el-button>
          <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="650px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="摄像头ID" prop="cameraId">
          <el-input v-model="form.cameraId" placeholder="请输入摄像头ID" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ip">
              <el-input v-model="form.ip" placeholder="请输入IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <el-input-number v-model="form.port" :min="1" :max="65535" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-select v-model="form.brand" placeholder="请选择">
                <el-option label="海康威视" value="hikvision" />
                <el-option label="大华" value="dahua" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="能力" prop="capability">
              <el-select v-model="form.capability" placeholder="请选择">
                <el-option label="仅切换" value="switch_only" />
                <el-option label="支持PTZ" value="ptz_enabled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="所属机器" prop="machineId">
          <el-select v-model="form.machineId" placeholder="请选择机器" clearable>
            <el-option
              v-for="machine in machineList"
              :key="machine.machineId"
              :label="machine.name"
              :value="machine.machineId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isEdit" label="启用状态">
          <el-switch v-model="form.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 通道弹窗 -->
    <el-dialog v-model="channelDialogVisible" title="通道列表" width="700px" destroy-on-close>
      <el-table :data="currentChannels" border>
        <el-table-column prop="channelId" label="通道ID" min-width="100" />
        <el-table-column prop="name" label="名称" min-width="100" />
        <el-table-column prop="rtspUrl" label="RTSP地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="defaultView" label="默认视角" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.defaultView ? 'success' : 'info'">
              {{ row.defaultView ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'ONLINE' ? 'success' : 'danger'">
              {{ row.status === 'ONLINE' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, View, Edit, Delete, Connection } from '@element-plus/icons-vue'
import { adminListCameras, adminAddCamera, adminUpdateCamera, adminDeleteCamera, adminCheckCamera } from '@/api/camera'
import { listAllMachines } from '@/api/machine'
import type { CameraInfoDTO, ChannelInfoDTO, CameraAddRequest, CameraUpdateRequest, MachineDTO } from '@/types'

const loading = ref(false)
const submitLoading = ref(false)
const cameraList = ref<CameraInfoDTO[]>([])
const machineList = ref<MachineDTO[]>([])
const dialogVisible = ref(false)
const channelDialogVisible = ref(false)
const currentChannels = ref<ChannelInfoDTO[]>([])
const formRef = ref<FormInstance>()

const queryParams = reactive({
  machineId: '',
  status: '' as '' | 'ONLINE' | 'OFFLINE'
})

const form = reactive<{
  id?: number
  cameraId: string
  name: string
  ip: string
  port: number
  username: string
  password: string
  brand: string
  capability: 'switch_only' | 'ptz_enabled'
  machineId: string
  enabled: boolean
}>({
  cameraId: '',
  name: '',
  ip: '',
  port: 80,
  username: 'admin',
  password: '',
  brand: 'hikvision',
  capability: 'switch_only',
  machineId: '',
  enabled: true
})

const isEdit = computed(() => !!form.id)
const dialogTitle = computed(() => (isEdit.value ? '编辑摄像头' : '新增摄像头'))

const filteredList = computed(() => {
  let list = cameraList.value
  if (queryParams.status) {
    list = list.filter((item) => item.status === queryParams.status)
  }
  return list
})

const rules: FormRules = {
  cameraId: [{ required: true, message: '请输入摄像头ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    {
      pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
      message: '请输入正确的IP地址',
      trigger: 'blur'
    }
  ]
}

async function getMachines() {
  try {
    const res = await listAllMachines()
    if (res.success) {
      machineList.value = res.data
    }
  } catch (error) {
    console.error('获取机器列表失败', error)
  }
}

async function getList() {
  loading.value = true
  try {
    const params = {
      machineId: queryParams.machineId || undefined,
      status: queryParams.status || undefined
    }
    const res = await adminListCameras(params)
    if (res.success) {
      cameraList.value = res.data.list
    }
  } finally {
    loading.value = false
  }
}

function handleQuery() {
  getList()
}

function resetQuery() {
  queryParams.machineId = ''
  queryParams.status = ''
  getList()
}

function handleAdd() {
  Object.assign(form, {
    id: undefined,
    cameraId: '',
    name: '',
    ip: '',
    port: 80,
    username: 'admin',
    password: '',
    brand: 'hikvision',
    capability: 'switch_only',
    machineId: '',
    enabled: true
  })
  dialogVisible.value = true
}

function handleEdit(row: CameraInfoDTO) {
  Object.assign(form, {
    id: row.id,
    cameraId: row.cameraId,
    name: row.name,
    ip: row.ip,
    port: row.port,
    username: row.username,
    password: '',
    brand: row.brand,
    capability: row.capability,
    machineId: row.machineId || '',
    enabled: row.enabled
  })
  dialogVisible.value = true
}

function handleChannel(row: CameraInfoDTO) {
  currentChannels.value = row.channels || []
  channelDialogVisible.value = true
}

async function handleCheck(row: CameraInfoDTO) {
  try {
    const res = await adminCheckCamera(row.id)
    if (res.success) {
      if (res.data) {
        ElMessage.success('摄像头连接正常')
      } else {
        ElMessage.warning('摄像头连接失败')
      }
    }
  } catch (error) {
    console.error('检测失败', error)
  }
}

async function handleDelete(row: CameraInfoDTO) {
  try {
    await ElMessageBox.confirm(`确定要删除摄像头 "${row.name}" 吗？`, '提示', {
      type: 'warning'
    })
    const res = await adminDeleteCamera(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      getList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error)
    }
  }
}

async function handleSubmit() {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          const updateData: CameraUpdateRequest = {
            id: form.id!,
            name: form.name,
            ip: form.ip,
            port: form.port,
            username: form.username,
            password: form.password || undefined,
            brand: form.brand,
            capability: form.capability,
            machineId: form.machineId || undefined,
            enabled: form.enabled
          }
          const res = await adminUpdateCamera(updateData)
          if (res.success) {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            getList()
          }
        } else {
          const addData: CameraAddRequest = {
            cameraId: form.cameraId,
            name: form.name,
            ip: form.ip,
            port: form.port,
            username: form.username,
            password: form.password || undefined,
            brand: form.brand,
            capability: form.capability,
            machineId: form.machineId || undefined
          }
          const res = await adminAddCamera(addData)
          if (res.success) {
            ElMessage.success('新增成功')
            dialogVisible.value = false
            getList()
          }
        }
      } finally {
        submitLoading.value = false
      }
    }
  })
}

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

<style lang="scss" scoped>
.page-container {
  padding: 1rem;
}

.search-form {
  background-color: #fff;
  border-radius: var(--radius-base);
  padding: 0;
  margin-bottom: 0;
}

.table-actions {
  margin-bottom: 15px;
}
</style>
