<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" ref="crud" @row-del="rowDel"
      v-model="form" :before-open="beforeOpen" @search-change="searchChange" @search-reset="searchReset" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuLeft">
        <el-button @click="handleExport" type="warning" size="small" icon="el-icon-download" plain>导出
        </el-button>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button @click="linkVideo(row, index)" type="text" icon="el-icon-video-camera-solid" size="small"
          :disabled="row.cancelTime == ''">
          视频联动
        </el-button>
      </template>
    </avue-crud>
    <!-- 视频联动弹窗 -->
    <el-dialog title="视频联动" :visible.sync="dialogVisible" v-if="dialogVisible" :append-to-body="true" :close-on-click-modal="false"
      :close-on-press-escape="false" custom-class="video_dia" fullscreen>

      <div class="video_box">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in videoData" :key="item.id">
            <VideoPlayer :name="item.name" :id="item.id" :code="renderCode(item.tags)"
              :url="'https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv'"
              :playbackUrl="'https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv'" />
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList } from "@/api/alarm/alarm";
import { bizLogin, bizDeviceList } from "@/api/wirelessintrusion/wirelessintrusion";
import { exportBlob } from "@/api/common";
import { downloadXls } from "@/util/util";
import { dateNow } from "@/util/date";
import { getToken } from "@/util/auth";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import func from "@/util/func";
import VideoPlayer from "../components/video/video"

export default {
  components: {
    VideoPlayer
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      dialogVisible: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        border: true,
        searchShow: true,
        searchMenuSpan: 6,
        menuWidth: 200,
        viewBtn: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        index: true,
        dialogClickModal: false,
        column: [
          {
            label: "设备名称",
            prop: "deviceName",
          },
          {
            label: "设备编号",
            prop: "deviceId",
            row: true,
          },
          {
            label: "设备类型",
            prop: "productName",
          },
          {
            label: "报警类型",
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=alarm_message_condition",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
            slot: true,
            prop: "type",
            search: true,
          },
          {
            label: "楼号",
            prop: "buildId",
            width: 80
          },
          {
            label: "楼层",
            prop: "floorNo",
            width: 80
          },
          {
            label: "经纬度",
            prop: "xy",
            span: 24,
            hide: true
          },
          {
            label: "报警信息",
            prop: "content",
            overHidden: true,
            width: '200'
          },
          {
            label: "上报时间",
            prop: "reportTime",
            width: '150'
          },
        ]
      },
      data: [],
      videoData: []
    };
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        let tags = JSON.parse(ele.tags)
        ids.push(tags.sectorNo);
      });
      return ids.join(",");
    }
  },
  mounted() {
    // 添加socket通知监听
	  window.addEventListener('onmessageWS', this.getSocketData)
  },
  methods: {
    // 收到消息处理
    getSocketData (res) {
      console.log('websocket', res);
      if (res.detail.data === 'success' || res.detail.data === 'heartBath') return
      // ...业务处理
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      const { releaseTimeRange } = this.query;
      let values = {
        ...params,
        ...this.query,
        alarmType: 1
      };
      if (releaseTimeRange) {
        values = {
          ...values,
          startTime: releaseTimeRange[0],
          endTime: releaseTimeRange[1],
        };
        values.releaseTimeRange = null;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        data.records.map(item => {
          item.xy = item.longidute + ',' + item.latidute;
        })
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 视频联动按钮
    linkVideo(row) {
      let token = window.sessionStorage.getItem('bizToken');
      if (token == 'undefined' || !token) {
        bizLogin({ appKey: 'Arf7bd4f26', appSecret: 'kb207044c8' }).then(res => {
          window.sessionStorage.setItem('bizToken', res.data.data.token);
          bizDeviceList(res.data.data.token, { 'params[pmac]': row.deviceId }).then(res2 => {
            const data = res2.data;
            this.videoData = data.rows;
            if(this.videoData.length === 0){
              this.$message.warning('未查询到该报警点摄像头');
            }
            else{
              this.dialogVisible = true;
            }
          });
        })
      } else {
        bizDeviceList(token, { 'params[pmac]': row.deviceId }).then(res2 => {
          if (res2.data.code == 401) {
            window.sessionStorage.removeItem('bizToken');
            this.linkVideo(row);
          }
          else if (res2.data.code == 200) {
            const data = res2.data;
            this.videoData = data.rows;
            if(this.videoData.length === 0){
              this.$message.warning('未查询到该报警点摄像头');
            }
            else{
              this.dialogVisible = true;
            }
          }
        });
      }
    },
    renderCode(tags) {
      let obj = JSON.parse(tags);
      return obj.cameraIndexCode != 'undefined' ? obj.cameraIndexCode : '';
    },
    // 导出
    handleExport() {
      let values = {
        deviceType: func.toStr(this.query.type)
      };
      if (this.query.releaseTimeRange) {
        values = {
          ...values,
          startTime: this.queryreleaseTimeRange[0],
          endTime: this.queryreleaseTimeRange[1],
        };
      }
      let params = '';
      Object.keys(values).map(key => {
        params = '&' + key + '=' + values[key];
      })
      this.$confirm("是否导出报警数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        NProgress.start();
        exportBlob(`/api/alarmInformation/export?${this.website.tokenHeader}=${getToken()}${params}`).then(res => {
          downloadXls(res.data, `报警数据表${dateNow()}.xlsx`);
          NProgress.done();
        })
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
.video_dia {
  .video_box {
    width: 100%;

    .grid-content {
      width: 100%;
      height: 200px;
      margin-bottom: 18px;
      video {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
