<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="摄像头编码" prop="cameraCode">
        <el-input
          v-model="queryParams.cameraCode"
          placeholder="请输入摄像头编码"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="摄像头名称" prop="cameraName">
        <el-input
          v-model="queryParams.cameraName"
          placeholder="请输入摄像头名称"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="协议类型" prop="protocol">
        <el-select
          v-model="queryParams.protocol"
          placeholder="请选择协议类型"
          clearable
          style="width: 220px"
        >
          <el-option
            v-for="dict in dict.type.camera_protocol"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入所属机构"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          style="width: 220px"
        >
          <el-option
            v-for="dict in dict.type.camera_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['camera:camera:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['camera:camera:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['camera:camera:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      />
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="cameraList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
      />
      <el-table-column
        label="摄像头编码"
        align="center"
        prop="cameraCode"
        :show-overflow-tooltip="true"
        min-width="130"
      />
      <el-table-column
        label="摄像头名称"
        align="center"
        prop="cameraName"
        :show-overflow-tooltip="true"
        min-width="150"
      />
      <el-table-column
        label="协议类型"
        align="center"
        prop="protocol"
        width="120"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.camera_protocol"
            :value="scope.row.protocol"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="所属机构"
        align="center"
        prop="orgName"
        :show-overflow-tooltip="true"
        min-width="150"
      />
      <el-table-column
        label="地址"
        align="center"
        prop="address"
        :show-overflow-tooltip="true"
        min-width="180"
      />
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        width="100"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.camera_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-camera"
            @click="handlePreview(scope.row)"
            v-hasPermi="['camera:camera:query']"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['camera:camera:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['camera:camera:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改摄像头对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="摄像头编码" prop="cameraCode">
              <el-input
                v-model="form.cameraCode"
                placeholder="请输入摄像头编码"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="摄像头名称" prop="cameraName">
              <el-input
                v-model="form.cameraName"
                placeholder="请输入摄像头名称"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="协议类型" prop="protocol">
              <el-select
                v-model="form.protocol"
                placeholder="请选择协议类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.camera_protocol"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属机构" prop="orgName">
              <el-input
                v-model="form.orgName"
                placeholder="请输入所属机构"
                maxlength="128"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入地址"
                maxlength="255"
              >
                <el-button
                  slot="append"
                  icon="el-icon-location-outline"
                  @click="openLocationPicker"
                >选取</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input-number
                v-model="form.longitude"
                :step="0.000001"
                :precision="6"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number
                v-model="form.latitude"
                :step="0.000001"
                :precision="6"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="form.status"
                placeholder="请选择状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.camera_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="扩展配置">
              <!-- RTSP 协议配置 -->
              <div v-if="form.protocol === 'rtsp'">
                <el-row :gutter="16" style="margin-bottom: 8px;">
                  <el-col :span="24">
                    <el-form-item label="RTSP地址" label-width="80px">
                      <el-input
                        v-model="extraConfigModel.rtsp.url"
                        placeholder="rtsp://user:pass@ip:port/stream"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-bottom: 8px;">
                  <el-col :span="12">
                    <el-form-item label="用户名" label-width="80px">
                      <el-input v-model="extraConfigModel.rtsp.username" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="密码" label-width="80px">
                      <el-input
                        v-model="extraConfigModel.rtsp.password"
                        show-password
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="码流类型" label-width="80px">
                      <el-select
                        v-model="extraConfigModel.rtsp.streamType"
                        style="width: 100%"
                      >
                        <el-option label="主码流" value="main" />
                        <el-option label="子码流" value="sub" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- GB28181 协议配置 -->
              <div v-else-if="form.protocol === 'gb28181'">
                <el-form-item label="设备ID" label-width="80px">
                  <el-input v-model="extraConfigModel.gb28181.deviceId" />
                </el-form-item>
                <el-form-item label="SIP服务器IP" label-width="100px">
                  <el-input v-model="extraConfigModel.gb28181.serverIp" />
                </el-form-item>
                <el-form-item label="SIP服务器端口" label-width="120px">
                  <el-input-number
                    v-model="extraConfigModel.gb28181.serverPort"
                    :min="1"
                    :max="65535"
                    controls-position="right"
                  />
                </el-form-item>
                <el-form-item label="本地端口" label-width="80px">
                  <el-input-number
                    v-model="extraConfigModel.gb28181.localPort"
                    :min="1"
                    :max="65535"
                    controls-position="right"
                  />
                </el-form-item>
              </div>

              <!-- RTMP 协议配置 -->
              <div v-else-if="form.protocol === 'rtmp'">
                <el-form-item label="推流地址" label-width="80px">
                  <el-input
                    v-model="extraConfigModel.rtmp.url"
                    placeholder="rtmp://ip:port/app"
                  />
                </el-form-item>
                <el-form-item label="流密钥" label-width="80px">
                  <el-input v-model="extraConfigModel.rtmp.streamKey" />
                </el-form-item>
              </div>

              <!-- ONVIF 协议配置 -->
              <div v-else-if="form.protocol === 'onvif'">
                <el-form-item label="ONVIF地址" label-width="90px">
                  <el-input
                    v-model="extraConfigModel.onvif.url"
                    placeholder="http://ip:port/onvif/device_service"
                  />
                </el-form-item>
                <el-form-item label="用户名" label-width="80px">
                  <el-input v-model="extraConfigModel.onvif.username" />
                </el-form-item>
                <el-form-item label="密码" label-width="80px">
                  <el-input
                    v-model="extraConfigModel.onvif.password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="Profile" label-width="80px">
                  <el-input v-model="extraConfigModel.onvif.profile" />
                </el-form-item>
              </div>

              <!-- 未选择协议或其他协议 -->
              <div v-else>
                <el-alert
                  type="info"
                  :closable="false"
                  show-icon
                >
                  请选择协议后配置扩展参数。当前将保存为空 JSON：<code>{}</code>
                </el-alert>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
                maxlength="500"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
      </div>
    </el-dialog>

    <LocationPickerDialog
      :visible.sync="locationDialogVisible"
      :initial-location="{
        longitude: form.longitude,
        latitude: form.latitude,
        address: form.address
      }"
      @confirm="handleLocationPicked"
    />

    <!-- 摄像头预览画中画 -->
    <CameraPipPlayer
      v-if="pipVisible"
      :visible="pipVisible"
      :src="pipSrc"
      :type="pipType"
      :title="pipTitle"
      :error="pipError"
      @close="handlePipClose"
      @retry="handleRetry"
      @player-error="handlePlayerError"
    />
  </div>
</template>

<script>
import {
  listCamera,
  getCamera,
  addCamera,
  updateCamera,
  delCamera,
  startCameraStream,
  stopCameraStream,
  getCameraPlayUrls
} from '@/api/camera'
import LocationPickerDialog from '@/components/location/LocationPickerDialog'
import CameraPipPlayer from '@/components/CameraPipPlayer'
import { buildFullPlayUrls } from '@/utils/camera/stream'

export default {
  name: 'CameraManagement',
  dicts: ['camera_protocol', 'camera_status'],
  components: {
    LocationPickerDialog,
    CameraPipPlayer
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 摄像头表格数据
      cameraList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cameraCode: undefined,
        cameraName: undefined,
        protocol: undefined,
        orgName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 位置选择对话框
      locationDialogVisible: false,
      // 预览画中画相关
      pipVisible: false,
      pipSrc: '',
      pipType: 'hls',
      pipTitle: '',
      pipError: null,
      previewCamera: null,
      heartbeatTimer: null,
      // 不同协议的扩展配置模型（在提交时序列化到 form.extraConfig）
      extraConfigModel: {
        rtsp: {
          url: '',
          username: '',
          password: '',
          streamType: 'main'
        },
        gb28181: {
          deviceId: '',
          serverIp: '',
          serverPort: 5060,
          localPort: null
        },
        rtmp: {
          url: '',
          streamKey: ''
        },
        onvif: {
          url: '',
          username: '',
          password: '',
          profile: ''
        }
      },
      // 表单校验
      rules: {
        cameraCode: [
          { required: true, message: '摄像头编码不能为空', trigger: 'blur' },
          { max: 50, message: '摄像头编码长度不能超过50个字符', trigger: 'blur' }
        ],
        cameraName: [
          { required: true, message: '摄像头名称不能为空', trigger: 'blur' },
          { max: 200, message: '摄像头名称长度不能超过200个字符', trigger: 'blur' }
        ],
        protocol: [
          { required: true, message: '协议类型不能为空', trigger: 'change' }
        ],
        orgName: [
          { max: 128, message: '所属机构长度不能超过128个字符', trigger: 'blur' }
        ],
        address: [
          { max: 255, message: '地址长度不能超过255个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  beforeDestroy() {
    this.cleanupPreview()
  },
  methods: {
    /** 查询摄像头列表 */
    getList() {
      this.loading = true
      listCamera(this.addDateRange(this.queryParams, this.dateRange))
        .then(response => {
          this.cameraList = response.rows || []
          this.total = response.total || 0
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        cameraCode: undefined,
        cameraName: undefined,
        protocol: undefined,
        orgName: undefined,
        longitude: undefined,
        latitude: undefined,
        address: undefined,
        status: 'offline',
        remark: undefined
      }
      // 重置扩展配置为默认值
      this.extraConfigModel = {
        rtsp: {
          url: '',
          username: '',
          password: '',
          streamType: 'main'
        },
        gb28181: {
          deviceId: '',
          serverIp: '',
          serverPort: 5060,
          localPort: null
        },
        rtmp: {
          url: '',
          streamKey: ''
        },
        onvif: {
          url: '',
          username: '',
          password: '',
          profile: ''
        }
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增摄像头'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row && row.id ? row.id : this.ids[0]
      if (!id) {
        return
      }
      this.reset()
      getCamera(id).then(response => {
        this.form = Object.assign({}, response.data || {})
        // 确保经纬度是数字或 undefined
        if (this.form.longitude === null) this.form.longitude = undefined
        if (this.form.latitude === null) this.form.latitude = undefined
        // 解析扩展配置到对应协议模型
        const proto = this.form.protocol
        let parsed = {}
        try {
          parsed = this.form.extraConfig ? JSON.parse(this.form.extraConfig) : {}
        } catch (e) {
          parsed = {}
        }
        if (proto && this.extraConfigModel[proto]) {
          this.extraConfigModel[proto] = {
            ...this.extraConfigModel[proto],
            ...parsed
          }
        }
        this.open = true
        this.title = '修改摄像头'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        const payload = { ...this.form }
        // 去掉空字符串的经纬度，避免类型问题
        if (payload.longitude === '' || payload.longitude === null) {
          payload.longitude = undefined
        }
        if (payload.latitude === '' || payload.latitude === null) {
          payload.latitude = undefined
        }
        // 根据协议序列化扩展配置
        const proto = payload.protocol
        if (proto && this.extraConfigModel[proto]) {
          payload.extraConfig = JSON.stringify(this.extraConfigModel[proto])
        } else {
          payload.extraConfig = '{}'
        }
        if (payload.id) {
          updateCamera(payload).then(() => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        } else {
          addCamera(payload).then(() => {
            this.$modal.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row && row.id ? [row.id] : this.ids
      if (!ids || !ids.length) {
        return
      }
      this.$confirm(
        `是否确认删除选中的摄像头数据项？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => delCamera(ids.join(',')))
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 打开位置选择对话框 */
    openLocationPicker() {
      this.locationDialogVisible = true
    },
    // 位置选择器回调
    handleLocationPicked(location) {
      if (!location) {
        this.locationDialogVisible = false
        return
      }
      this.form.address = location.address || this.form.address
      this.form.longitude = location.lng
      this.form.latitude = location.lat
      this.locationDialogVisible = false
    },
    /** 预览摄像头 */
    async handlePreview(row) {
      const id = row.id
      if (!id) {
        this.$message.warning('摄像头ID不存在')
        return
      }
      
      // 立即显示画中画（即使流还未启动）
      this.previewCamera = row
      this.pipTitle = row.cameraName || row.cameraCode || '摄像头预览'
      this.pipSrc = '' // 先不设置，等待流启动
      this.pipVisible = true
      this.pipError = null // 错误信息
      
      try {
        // 启动流
        const response = await startCameraStream(id)
        if (response.code === 200) {
          // 构建完整播放 URL
          const urls = buildFullPlayUrls(response.data)
          this.pipSrc = urls.hls || urls.flv || ''
          this.pipType = urls.hls ? 'hls' : 'flv'
          this.pipError = null
          
          // 启动心跳（每2分钟发送一次，保持流活跃）
          this.startHeartbeat(id)
        } else {
          this.pipError = response.msg || '启动视频流失败'
        }
      } catch (error) {
        this.pipError = '启动视频流失败：' + (error.message || '未知错误')
      }
    },
    /** 关闭预览画中画 */
    handlePipClose() {
      this.cleanupPreview()
      this.pipVisible = false
      this.pipSrc = ''
      this.pipTitle = ''
      this.pipError = null
      this.previewCamera = null
    },
    /** 重试预览 */
    handleRetry() {
      if (this.previewCamera && this.previewCamera.id) {
        this.pipError = null
        this.pipSrc = ''
        this.handlePreview(this.previewCamera)
      }
    },
    /** 处理播放器错误 */
    handlePlayerError(errorMsg) {
      // 将播放器错误显示在 PiP 中
      this.pipError = errorMsg || '视频播放失败'
    },
    /** 清理预览资源 */
    cleanupPreview() {
      // 停止心跳
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer)
        this.heartbeatTimer = null
      }
      
      // 停止流
      if (this.previewCamera && this.previewCamera.id) {
        stopCameraStream(this.previewCamera.id)
          .catch(err => {
            console.warn('停止流失败', err)
          })
      }
    },
    /** 启动心跳，保持流活跃 */
    startHeartbeat(cameraId) {
      // 每2分钟发送一次心跳，更新 lastAccessTime
      this.heartbeatTimer = setInterval(() => {
        getCameraPlayUrls(cameraId)
          .then(() => {
            // 心跳成功，流保持活跃
          })
          .catch(err => {
            console.warn('心跳失败', err)
            // 如果心跳失败，可能是流已关闭，停止心跳
            if (this.heartbeatTimer) {
              clearInterval(this.heartbeatTimer)
              this.heartbeatTimer = null
            }
          })
      }, 2 * 60 * 1000) // 2 minutes
    }
  }
}
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>


