<template>
  <div class="siteManage-main watchDog">
    <!-- 筛选start -->
    <div class="filter-container mb-20">
      <div class="left">
        <span class="" style="margin-right: 30px"> 【{{ labelCom }}】站点的所有摄像头设备 </span>
        <el-button icon="Plus" type="success" @click="addItem()" :disabled="store.state.authorities.indexOf('新增') == -1">
          新增
        </el-button>
        <a href="./static/伍继摄像头导入模板.xlsx" download class="downloadMb">
          模板下载
        </a>
      </div>

      <el-upload class="upload-demo" :action="fileUrl + '/device/deviceImport'" :on-progress="handleProgress"
        :on-success="handleUpAvatar" :on-error="handleError" multiple :limit="1" :headers="{
          accessToken: [accessToken],
        }" :file-list="fileList" style="margin:0 10px 0 auto; display: inline-block"
        :disabled="store.state.authorities.indexOf('导入') == -1">
        <el-button type="primary" :disabled="store.state.authorities.indexOf('导入') == -1"> 导入 </el-button>
      </el-upload>
      <el-button type="primary" @click="DataReportExport()" :disabled="store.state.authorities.indexOf('导出') == -1"> 导出
      </el-button>

    </div>
    <!-- 筛选end -->

    <!-- 表格start -->

    <el-table :data="deviceData" v-loading="loadingStatus" element-loading-text="摄像头打开中...."
      element-loading-background="rgba(255, 255, 255, 0.6)"> border stripe
      <el-table-column prop="status" align="center" label="状态" width="80">
        <template #default="scope">
          <el-avatar class="status" :style="scope.row.ALIVEVALUE == 3
            ? 'background-color:#04F21C'
            : 'background-color:red'
            "></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="deviceName" label="名称" align="center"></el-table-column>
      <el-table-column prop="deviceCode" label="编号" align="center" width=""></el-table-column>
      <el-table-column prop="floor" label="楼层" align="center" width="60"></el-table-column>
      <el-table-column prop="deviceAddress" label="设备安装位置" align="center" width=""></el-table-column>
      <el-table-column prop="deviceType" label="设备类型" align="center">
        <template #default="scope">
          {{ scope.row.deviceType == '2' ? '视频监控设备' : '其他' }}
        </template>
      </el-table-column>
      <el-table-column prop="installTime" label="安装时间" align="center" width="200"></el-table-column>
      <el-table-column prop="creator" label="创建人" align="center"></el-table-column>
      <el-table-column prop="sim" label="sim卡号" align="center"></el-table-column>

      <el-table-column fixed="right" label="操作" width="140">
        <template #default="scope">
          <el-button type="primary" size="small" @click.prevent="editRow(scope.row)"
            :disabled="store.state.authorities.indexOf('修改') == -1" link>
            编辑
          </el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon="el-icon-info" icon-color="red" title="确定删除?"
            @confirm="handleDelete(scope.row)" @cancel="cancelEvent">
            <template #reference>
              <el-button type="danger" size="small" :disabled="store.state.authorities.indexOf('删除') == -1" link>
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="视频画面" width="100">
        <template #default="scope">
          <a v-if="scope.row.ALIVEVALUE == 3" @click="open_video(scope.row)">
            查看
          </a>
          <span v-else style="color: #aaa">--</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格end -->

    <!-- 分页start -->
    <div class="paginationBlock">
      <el-pagination v-model:currentPage="currentPage" :page-sizes="[15, 20, 25, 30]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" background></el-pagination>
    </div>
    <!-- 分页end -->

    <!--弹框组件开始-----------------------start-->
    <dialog-component ref="dialogComponent" @handleSelect="searchData()"></dialog-component>
    <!--弹框组件开始-----------------------end-->

    <!--视频弹框组件开始-----------------------start-->
    <check-video ref="checkVideoRef"></check-video>
    <!--视频弹框组件结束-----------------------end-->
  </div>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { useStore } from 'vuex'
import { ref, onMounted, watch, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
/*----------------------------------接口引入-----------------------------------*/
/*----------------------------------组件引入-----------------------------------*/
import DialogComponent from './dialogComponent'
import checkVideo from './checkVideo'
/*----------------------------------store引入-----------------------------------*/
/*----------------------------------公共方法引入-----------------------------------*/
import axios from 'axios'
import * as api from '@/api/siteManage/camera.js'
/*----------------------------------公共变量-----------------------------------*/
const store = useStore()
const props = defineProps({
  siteId: Number,
  activeName: String,
}) //数据双向绑定
const emit = defineEmits([]); emit
const { proxy } = getCurrentInstance();
/*----------------------------------变量声明-----------------------------------*/
const total = ref(0)
const pageSize = ref(15)
const currentPage = ref(1)
const deviceData = ref([])

const fileUrl = ref(window.PLATFROM_CONFIG.baseUrl)
const fileList = ref([])
const accessToken = ref(store.state.user.accessToken)
const labelCom = ref(store.state.siteManageLabelCom)

const onLineVideoList = ref([])
const reCount = ref(0)
const loadingStatus = ref(false)

//分页操作
const handleSizeChange = (val) => {
  pageSize.value = val
  videoMonitoringDeviceList()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  videoMonitoringDeviceList()
}
//监控设备列表
function videoMonitoringDeviceList() {
  api
    .videoMonitoringDeviceList({
      siteId: props.siteId,
      size: pageSize.value,
      current: currentPage.value,
      // deviceType:2
    })
    .then((requset) => {
      if (requset.status === 'SUCCESS') {
        deviceData.value = requset.data.records
        total.value = requset.data.total
      } else {
        ElMessage.error(requset.msg)
      }
    })
}

// 添加操作
const addItem = () => {
  proxy.$refs["dialogComponent"].openDialog({
    dialogTitle: '新增',
    dialogArray: {
      deviceName: '',
      deviceCode: '',
      floor: '',
      siteId: '',
      deviceAddress: '',
      deviceType: '',
      sim: '',
    },
  })
}

// 编辑操作
const editRow = (row) => {
  proxy.$refs["dialogComponent"].openDialog({
    dialogTitle: '编辑',
    dialogArray: {
      id: row.id,
      deviceCode: row.deviceCode,
      deviceName: row.deviceName,
      floor: row.floor,
      siteId: row.siteId,
      deviceAddress: row.deviceAddress,
      deviceType: Number(row.deviceType),
      sim: row.sim,
    },
  })
}

//删除 是否删除  ---- 是
const handleDelete = (row) => {
  api.correspondDeviceDel({ id: row.id }).then((requset) => {
    if (requset.status === 'SUCCESS') {
      ElMessage.success({
        message: '删除成功',
        type: 'success',
      })
      videoMonitoringDeviceList()
    } else {
      ElMessage.error(requset.msg)
    }
  })
}

//是否删除  ---- 否
const cancelEvent = () => {
  console.log('cancel!')
}

//导入
const handleProgress = (file, fileList) => {
  if (!(fileList.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || fileList.raw.type === 'application/vnd.ms-excel')) {
    ElMessage({
      message: '上传文件只能是 xls 和 xlsx 格式!',
      type: 'error',
    })
    return false
  } else {
    return true
  }
}

const handleUpAvatar = (res, file) => {
  console.log(res, file)
  fileList.value = []
  ElMessage.success({
    message: '导入成功',
    type: 'success',
  })
  videoMonitoringDeviceList()
}

function handleError(res) {
  let myError = res.toString() //转字符串
  myError = myError.replace('Error: ', '') //去掉前面的
  myError = JSON.parse(myError) //转对象
  ElMessage.error({
    message: myError.msg,
    type: 'error',
  })
}

//导出
function DataReportExport() {
  api
    .deviceExport({
      siteId: props.siteId,
    })
    .then((requset) => {
      if (requset.status === 'SUCCESS') {
        window.location.href = window.PLATFROM_CONFIG.fileUrl + requset.data
        ElMessage.success({
          message: '导出成功',
          type: 'success',
        })
      } else {
        ElMessage.error(requset.msg)
      }
    })
}

// 初始化cgj
function initCgi() {
  axios
    .post(
      'https://fire.usky.cn:8443/YtIoT/cgi-bin/demo2.cgi',
      'queryJson:' +
      JSON.stringify({ CMD: 1, }),
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', },
      }
    )
    .then((response) => {
      onLineVideoList.value = response.data.RESULT.LIST

      for (var n = 0; n < onLineVideoList.value.length; n++) {
        for (var j = 0; j < deviceData.value.length; j++) {
          if (onLineVideoList.value[n].DEVICE == deviceData.value[j].deviceCode) {
            deviceData.value[j].ALIVEVALUE = onLineVideoList.value[n].ALIVEVALUE
          }
        }
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

// 查看视频
function open_video(item) {
  loadingStatus.value = true

  axios
    .post(
      'https://fire.usky.cn:8443/YtIoT/cgi-bin/demo2.cgi',
      'queryJson:' +
      JSON.stringify({
        CMD: 3,
        BODY: { DEVICE: item.deviceCode, ACTION: 1, IDX: 7, },
      }),
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', },
      }
    )
    .then((response) => {
      response

      for (var n = 0; n < onLineVideoList.value.length; n++) {
        if (onLineVideoList.value[n].DEVICE == item.deviceCode) {
          // console.log('第一次打开时设备及其状态')
          if (onLineVideoList.value[n].ONAIR) {
            proxy.$refs["checkVideoRef"].openDialog({
              dialogTitle: '查看视频',
              dialogArray: item,
              onLineVideoList: onLineVideoList.value,
            })
            loadingStatus.value = false
            return
          } else {
            if (reCount.value >= 7) {
              reCount.value = 0
              loadingStatus.value = false
              alert('远程摄像头链接超时，请稍后再试')
              break
            }
            store.state.siteCameraTimer = setTimeout(() => {
              initCgi();
              open_video(item);
              reCount.value++
            }, 2000)
          }
        }
      }
    })
}

function searchData() {
  reCount.value = 0
  loadingStatus.value = false
  initCgi();
  videoMonitoringDeviceList()
}

watch(
  () => props.activeName,
  (newVal) => {
    if (newVal == 'five' && props.siteId) {
      searchData()
    }
  }
)

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

<style lang="scss" scoped></style>
