<template>
  <div class="video">
    <div class="videoTop">
      <div class="videoTopLeft">
        选择站点:
        <el-select
          filterable
          v-model="store.state.siteId"
          placeholder="请选择"
          style="width: 250px; margin-right: 20px"
        >
          <el-option
            v-for="site in store.state.siteList"
            :key="site"
            :label="site.siteName"
            :value="site.id"
          ></el-option>
        </el-select>
        <el-input
          placeholder="搜索设备名"
          v-model="filterText"
          class="videoTopLeftInput"
        >
          <!-- <template #suffix>
            <i class="el-icon-search el-input__icon"></i>
          </template> -->
        </el-input>

        <el-button
          type="primary"
          icon="el-icon-search"
          class="search-button"
          @click="searchData()"
        >
          搜索
        </el-button>
        <!-- <el-button
          class="search-button"
          icon="el-icon-plus"
          type="success"
          @click="Insert()"
        >
          新增
        </el-button> -->
      </div>

      <!-- <div class="videoRight">
        <el-button type="primary">导入</el-button>
        <el-button type="primary">导出</el-button>
      </div> -->
    </div>

    <div class="videoContent">
      <el-table
        :data="tableData"
        border
        stripe
        :header-cell-style="headClass"
        :height="Height"
        v-loading="loadingStatus"
        element-loading-text="摄像头打开中...."
        element-loading-background="rgba(255, 255, 255, 0.6)"
      >
        <el-table-column
          prop="stationStatus"
          label="状态"
          align="center"
          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 label="视频画面" align="center" width="150">
          <template #default="scope" style="text-align: center">
            <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>
      <div class="listPagination">
        <el-pagination
          v-model:currentPage="currentPage"
          :page-sizes="[15, 20, 25, 30]"
          :page-size="15"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        ></el-pagination>
      </div>

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

    <div></div>
  </div>
</template>
<script>
import { useStore } from 'vuex'
import { defineComponent, ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as api from '@/api/deviceManage/videoEquip.js'
import checkVideo from './checkVideo'
import axios from 'axios'

export default defineComponent({
  name: 'powerEquip',
  components: { checkVideo },
  props: {
    Height: String,
    activeName: String,
  },
  setup(props) {
    const store = useStore()

    const dialogTitle = ref('')
    const showDialog = ref(false)

    const total = ref(0)
    const pageSize = ref(15)
    const currentPage = ref(1)
    const filterText = ref('')
    // const activeName = 'powerEquip'
    const tableData = ref([])

    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 LookUp = (ind, row) => {
      // alert(2)
      console.log(ind, row)
      dialogTitle.value = '查看视频'
      showDialog.value = true
    }
    const handleSizeChange = (val) => {
      pageSize.value = val
      videoMonitoringDeviceList()
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
      videoMonitoringDeviceList()
    }
    // 表头样式设置
    const headClass = () => {
      return 'background:#FAFAFA !important;color: black;'
    }

    // 关闭操作
    const closeDialog = () => {
      showDialog.value = false
      // videoMonitoringDeviceList()
    }
    function searchData() {
      loadingStatus.value = false
      reCount.value = 0
      openId.value = ''
      videoMonitoringDeviceList()
      chk_video()
    }

    //视频列表
    function videoMonitoringDeviceList() {
      api
        .videoMonitoringDeviceList({
          siteId: store.state.siteId,
          size: pageSize.value,
          current: currentPage.value,
          deviceType: 2,
          deviceName: filterText.value,
        })
        .then((requset) => {
          if (requset.status === 'SUCCESS') {
            tableData.value = requset.data.records
            total.value = requset.data.total
          } 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) {
                    loadingStatus.value = false

                    dialogTitle.value = '查看视频'
                    showDialog.value = true
                  } else {
                    store.state.siteCameraTimer = setTimeout(chk_video, 5000)
                  }
                } else {
                  if (reCount.value > 7) {
                    loadingStatus.value = false
                    alert('远程摄像头链接超时，请稍后再试')

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

    // 查看视频
    const open_video = (item) => {
      deviceCode.value = item.deviceCode
      if (openId.value != item.deviceCode) {
        openId.value = item.deviceCode
      }
      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) {
            dialogTitle.value = '查看视频'
            showDialog.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.deviceCode,
                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
    }

    watch(
      () => props.activeName,
      (newVal) => {
        // alert(newVal)
        if (newVal == 'videoEquip') {
          //  clearTimeOut(timer.value)
          // window.clearTimeOut() //关闭定时器// alert('关闭定时器?')
          reCount.value = 0
          openId.value = ''
          loadingStatus.value = false

          videoMonitoringDeviceList()
          chk_video()
        }
      }
    )

    onMounted(() => {})

    return {
      headClass,
      LookUp,
      handleSizeChange,
      handleCurrentChange,
      searchData,
      videoMonitoringDeviceList,

      filterText,
      tableData,
      // activeName,
      currentPage,
      closeDialog,
      dialogTitle,
      showDialog,
      store,
      chk_video,

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

<style lang="scss" scoped>
//first样式
.video {
  margin: 15px;
  //顶部左侧样式
  .videoTop {
    display: flex;
    height: 32px;
    line-height: 32px;
    .videoTopLeft {
      width: 70%;
      .goBack {
        margin-right: 15px;
      }
      .videoTopLeftTitle {
        font-size: 14px;
        margin-right: 10px;
      }
      .videoTopLeftInput {
        width: 15rem;
      }
      .el-input__icon {
        color: #409eff;
      }
      .el-input__inner:hover {
        border-color: #409eff;
      }
      .el-input__inner:focus {
        border-color: #409eff;
      }
      .search-button {
        margin-left: 1rem;
      }
    }

    //顶部右侧样式
    .videoRight {
      width: 30%;
      button {
        margin-left: 1rem;
        float: right;
      }
    }
  }
  .videoContent {
    margin-top: 15px;
  }
}

.listPagination {
  margin-top: 15px;
  float: right;
}
</style>