<template>
  <div class="siteManage-main watchDog">
    <!-- 筛选start -->
    <div class="filter-container mb-20">
      <div class="left">
        <div>
          <a class="" style="margin-right: 30px">
            【{{ labelCom }}】站点的所有摄像头设备
          </a>
          <el-button icon="el-icon-plus" type="success" @click="addItem()">
            新增
          </el-button>
        </div>
      </div>

      <div class="right">
        <el-upload
          class="upload-demo"
          :action="fileUrl + '/device/deviceImport'"
          :on-progress="handleProgress"
          :on-success="handleUpAvatar"
          multiple
          :limit="1"
          :headers="{
            accessToken: [accessToken],
          }"
          :file-list="fileList"
          style="margin-right: 10px; display: inline-block"
        >
          <el-button size="small" type="primary">导入</el-button>
        </el-upload>
        <el-button type="primary" @click="DataReportExport()">导出</el-button>
      </div>
    </div>
    <!-- 筛选end -->

    <!-- 表格start -->

    <!-- <view v-if="loadingStatus" class="loadingMask">Loading...</view> -->
    <div></div>

    <el-table
      :data="deviceData"
      border
      stripe
      :header-cell-style="headClass"
      v-loading="loadingStatus"
      element-loading-text="摄像头打开中...."
      element-loading-background="rgba(255, 255, 255, 0.6)"
    >
      <el-table-column prop="status" align="center" label="状态" width="50">
        <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="text"
            size="small"
            @click.prevent="editRow(scope.row)"
          >
            编辑
          </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="text" size="small" class="delete-text">
                删除
              </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
      :dialogTitle="dialogTitle"
      :itemInfo="tableItem"
      @closeDialog="closeDialog"
      :flag="showDialog"
    ></dialog-component>
    <!--弹框组件开始-----------------------end-->

    <!--视频弹框组件开始-----------------------start-->
    <check-video
      :dialogTitle="dialogTitle"
      :itemInfo="tableItem"
      @closeDialog="closeDialog2"
      :flag="showDialog2"
      :deviceCode="deviceCode"
    ></check-video>
    <!--视频弹框组件结束-----------------------end-->

    <input type="hidden" v-model="openId" style="opacity: 0" />
  </div>
</template>

<script>
import { useStore } from 'vuex'
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  watch,
  onUnmounted,
} from 'vue'
import DialogComponent from './dialogComponent'
import checkVideo from './checkVideo'
import * as api from '@/api/siteManage/camera.js'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default defineComponent({
  components: { DialogComponent, checkVideo },
  props: {
    siteId: Number,
    activeName: String,
  },
  setup(props) {
    const store = useStore()
    store
    const total = ref(0)
    const pageSize = ref(15)
    const currentPage = ref(1)
    const goSiteListParam = ref('')
    const platformAreaName = ref('')
    const pageShow = ref(false)
    const showDialog = ref(false)
    const showDialog2 = ref(false)
    const deviceData = ref([])

    const tableItem = reactive([])
    const dialogTitle = 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 openId = ref('')
    const reCount = ref(0)
    const count = ref(0)
    const loadingStatus = ref(false)
    const timer = ref('')
    const deviceCode=ref('')

    // 表头样式设置
    const headClass = () => {
      return 'background:#FAFAFA;'
    }
    //分页操作
    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
            console.log('response 接口请求数据')
            console.log(deviceData.value)
          } else {
            ElMessage.error(requset.msg)
          }
        })
    }

    // 添加操作
    const addItem = () => {
      tableItem.value = {
        deviceName: '',
        deviceCode: '',
        floor: 1,
        siteId: '',
        deviceAddress: '',
        deviceType: '',
        sim: '',
      }
      dialogTitle.value = '新增'
      showDialog.value = true
    }

    // 编辑操作
    const editRow = (row) => {
      console.log
      tableItem.value = {
        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,
      }
      dialogTitle.value = '编辑'
      showDialog.value = true
    }

    // 查看视频
    // const open_video = (params) => {
    //   params
    //   tableItem.value = {
    //     id: '',
    //     stationName: '',
    //     watchName: '',
    //     watchCode: '',
    //     siteList: [],
    //     done: '',
    //     guaZai: '',
    //     checked: true,
    //     resource: '',
    //   }
    //   dialogTitle.value = '查看视频'
    //   showDialog2.value = true
    // }

    // 关闭操作
    const closeDialog = () => {
    showDialog.value = false
   
      videoMonitoringDeviceList()
      chk_video()
    }
    const closeDialog2 = () => {
      showDialog2.value = false
      count.value=0
    
    }

    //删除 是否删除  ---- 是
    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) => {
      file
      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()
    }
    //导出
    const 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)
          }
        })
    }

    //请求视频cgi数据
    const chk_video = () => {
      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) => {
          console.log('response cgi')
          console.log(response.data.RESULT.LIST)
          console.log(openId.value)
          onLineVideoList.value = response.data.RESULT.LIST

          if (openId.value.length > 0) {
            // start
            console.log('doododododododo')
            for (var n = 0; n < onLineVideoList.value.length; n++) {
              if (openId.value == onLineVideoList.value[n].DEVICE) {
                console.log('再次打开摄像头')
                console.log(openId.value)
                console.log(onLineVideoList.value[n].DEVICE)
                console.log(onLineVideoList.value[n].ONAIR)
                reCount.value++
                console.log(reCount.value)
                if (onLineVideoList.value[n].ONAIR) {
                  if (++count.value > 2) {
                    // var mask = document.getElementById('videomask');
                    // if (mask != undefined) {
                    // 	removeDIV('videomask');
                    // }
                    loadingStatus.value = false

                    alert('可以打开视频详情并传参')
                    // uni.navigateTo({
                    // 	url: '/pages/videoDetail/videoDetail?deviceType=2&companyCode=' +
                    // 		this.companyCode + '&deviceCode=' +
                    // 		onLineVideoList.value[n].DEVICE +
                    // 		'',
                    // });

                    tableItem.value = {
                      id: '',
                      stationName: '',
                      watchName: '',
                      watchCode: '',
                      siteList: [],
                      done: '',
                      guaZai: '',
                      checked: true,
                      resource: '',
                    }
                    dialogTitle.value = '查看视频'
                    showDialog2.value = true;
                  } else {
                    store.state.siteCameraTimer = setTimeout(chk_video, 5000)
                  }
                } else {
                  if (reCount.value > 20) {
                    // var mask = document.getElementById('videomask');
                    // if (mask != undefined) {
                    // 	removeDIV('videomask');
                    // }
                    loadingStatus.value = false
                    alert('远程摄像头链接超时，请稍后再试')
                    // ElMessage({
                    //   duration: 5000,
                    //   showClose: true,
                    //   message: '远程摄像头链接超时，请稍后再试.',
                    //   type: 'warning',
                    // })

                    // $("#myPopup").popup("open");
                    break
                  }
                  store.state.siteCameraTimer = setTimeout(chk_video, 5000)
                }
              }
            }
            // end
          } else {
            for (var i = 0; i < onLineVideoList.value.length; i++) {
              for (var j = 0; j < deviceData.value.length; j++) {
                if (
                  onLineVideoList.value[i].DEVICE ==
                  deviceData.value[j].deviceCode
                ) {
                  deviceData.value[j].ALIVEVALUE =
                    onLineVideoList.value[i].ALIVEVALUE
                }
              }
            }
            // console.log('处理后的，deviceData.value')
            // console.log(deviceData.value)
          }
        })
        .catch((error) => {
          console.log(error)
        })
    }

    // 查看视频
    const open_video = (item) => {
      deviceCode.value=item.deviceCode
      // alert(deviceCode.value)
      // console.log(item)
      if (openId.value != item.deviceCode) {
        openId.value = item.deviceCode
      }
      // console.log(onLineVideoList.value)
      for (var n = 0; n < onLineVideoList.value.length; n++) {
        if (onLineVideoList.value[n].DEVICE == openId.value) {
          console.log('第一次打开时设备及其状态')
          console.log(onLineVideoList.value[n].DEVICE)
          console.log(openId.value)
          console.log(onLineVideoList.value[n].ONAIR)
          if (onLineVideoList.value[n].ONAIR) {
            alert('打开详情页并传参')
            tableItem.value = {
              id: '',
              stationName: '',
              watchName: '',
              watchCode: '',
              siteList: [],
              done: '',
              guaZai: '',
              checked: true,
              resource: '',
            }
            dialogTitle.value = '查看视频'
            showDialog2.value = true
            return
          }
        }
      }
      count.value = 0
      reCount.value = 0
      loadingStatus.value = true
      axios
        .post(
          'https://fire.usky.cn:8443/YtIoT/cgi-bin/demo2.cgi',
          'queryJson:' +
            JSON.stringify({
              CMD: 3,
              BODY: {
                DEVICE: item.DEVICE,
                ACTION: 1,
                IDX: 7,
              },
            }),
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
          }
        )
        .then((response) => {
          response
          store.state.siteCameraTimer = window.setTimeout(function () {
            chk_video()
          }, 5000)
        })

      // end
    }

    // window.setInterval(() => {
    //   setTimeout(() => {
    //     chk_video()
    //   }, 0)
    // }, 100000)

    //监听变化
    watch(
      () => props.siteId,
      (newVal) => {
        console.log('newVal')
        console.log(newVal)

        labelCom.value = store.state.siteManageLabelCom
        if (props.activeName == 'five') {
          // window.clearTimeOut() //关闭定时器
          reCount.value = 0
          openId.value = ''
          loadingStatus.value = false
          videoMonitoringDeviceList()
          chk_video()
        }
      }
    )
    watch(
      () => props.activeName,
      (newVal) => {
        if (newVal == 'five') {
          //  clearTimeOut(timer.value)
          // window.clearTimeOut() //关闭定时器// alert('关闭定时器?')
          reCount.value = 0
          openId.value = ''
          loadingStatus.value = false

          videoMonitoringDeviceList()
          chk_video()
        }
      }
    )

    onMounted(() => {})
    onUnmounted(() => {
      // alert('摧毁')
      // clearTimeOut(timer.value)
    })

    return {
      deviceData,
      showDialog,
      showDialog2,

      platformAreaName,
      pageShow,
      dialogTitle,

      props,
      tableItem,
      goSiteListParam,

      total,
      pageSize,
      currentPage,
      chk_video,

      videoMonitoringDeviceList,
      headClass,
      addItem,

      editRow,
      closeDialog,
      closeDialog2,
      handleDelete,
      cancelEvent,
      handleSizeChange,
      handleCurrentChange,

      DataReportExport,

      fileList,
      fileUrl,
      accessToken,
      handleProgress,
      handleUpAvatar,

      labelCom,

      openId,
      onLineVideoList,
      reCount,
      count,
      loadingStatus,
      open_video,
      timer,
      deviceCode
    }
  },
})
</script>

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