<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button type="primary" icon="el-icon-refresh" @click="syncData" :loading="syncLoading">同步</el-button>
      </div>
      <div class="right-panel">
        <el-select v-model="areaId" placeholder="选择区域">
          <el-option v-for="item in areaoptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"></el-button>
      </div>
    </el-header>
    <el-main class="nopadding">
      <scTable ref="table" :apiObj="apiObj" row-key="id" :params="apiParams" :pageStr="pageStr" :data="pageData"
        :pageSizeStr="pageSizeStr" :orderStr="orderStr" :parseData="parseData" @selection-change="selectionChange" stripe
        @resetQuery="resetQuery">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="设备编号" prop="deviceCode" min-width="100"></el-table-column>
        <el-table-column label="通道编号" prop="channelCode" min-width="150"></el-table-column>
        <el-table-column label="通道名称" prop="channelName" min-width="250"></el-table-column>
        <!-- <el-table-column label="通道IP" prop="channelName" min-width="250"></el-table-column> -->
        <el-table-column label="通道状态" prop="stat" min-width="80">
          <template #default="scope">
            <span v-if="scope.row.stat === 0">未启用</span>
            <span v-else>启用</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" min-width="50">
          <template #default="scope">{{
            deviceTypes[scope.row.cameraType]
          }}</template>
        </el-table-column>
        <el-table-column label="是否在线" prop="isOnline" min-width="180">
          <template #default="scope">
            <span v-if="scope.row.isOnline === 0">
              <el-tag type="warning">离线</el-tag>
            </span>
            <span v-else>
              <el-tag type="success">在线</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="所在区域" prop="my_info.area_name" min-width="80"></el-table-column>
        <el-table-column label="所在位置" min-width="150">
          <template #default="scope">
            <div v-if="scope.row.my_info.location">
              <div>
                x:{{ scope.row.my_info.location.x }}
              </div>
              <div>
                y:{{ scope.row.my_info.location.y }}
              </div>
              <!-- <div>
              z:{{ scope.row.my_info.location.z }}
            </div> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" min-width="160"></el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="180">
          <template #default="scope">
            <el-button-group>
              <el-button text type="primary" size="small" @click="handlePosition(scope.row)">标记位置
              </el-button>
              <el-button text type="primary" size="small" @click="handleView(scope.row)">实时监控</el-button>
              <!-- <el-popconfirm title="确定删除吗？" @confirm="handleDel(scope.row, scope.$index)">
								<template #reference>
									<el-button text type="danger" size="small">删除</el-button>
								</template>
							</el-popconfirm> -->
            </el-button-group>
          </template>
        </el-table-column>
      </scTable>
    </el-main>
  </el-container>
  <el-dialog class="videoViewWrap" :title="channelName" v-model="limitedVisible" with="100%">
    <video-view id="videoView" v-if="limitedVisible" :channelCode="channelCode"></video-view>
    <template #footer>
      <el-button @click="viewClose">关闭</el-button>
    </template>
  </el-dialog>
  <channel-view v-if="dialogSave" ref="saveDialog" :channelId="channelId" :channelName="channelName"
    :channelArea="channelArea" :channelAreas="channelAreas" :channelLocation="channelLocation"
    @closed="dialogSave = false" @success="handleQuery"></channel-view>
</template>
<script>
import channelView from "./vchannel_view";
import videoView from "./videoView";

export default {
  name: "monitor",
  inject: ['reload'],
  components: {
    channelView,
    videoView
  },
  data() {
    return {
      apiObj: this.$API.am.video.list,
      apiParams: {
      },
      pageStr: "pageNum",
      pageSizeStr: "pageSize",
      orderStr: "sort",
      parseData: (res) => {
        return {
          data: res,				//分析无分页的数据字段结构
          rows: res.pageData,		//分析行数据字段结构
          total: res.totalRows,		//分析总数字段结构
        }
      },
      dialogSave: false,
      limitedVisible: false,
      syncLoading: false,
      query: {},
      selection: [],
      params: {
        json: {
          data: {
            channelId: "",
            streamType: "2",
            type: "flv",
          },
        },
        code: "video_realtime",
      },
      areaId: '',
      channelCode: '',
      channelId: '',
      channelArea: '',
      pageData: [],
      areaoptions: [],
      channelAreas: [],
      channelLocation: {},
      flvPlayer: null,
      deviceTypes: {
        1: "枪机",
        2: "球机",
        3: "半球",
      },
      canUseMap: false,
    };
  },
  created() {
    const scriptInfo = document.createElement("script");
    scriptInfo.setAttribute("data-callType", "callScript");
    scriptInfo.src = "https://cdn.bootcdn.net/ajax/libs/flv.js/1.6.2/flv.js";
    document.head.appendChild(scriptInfo);
    this.getAllVchannel();
  },
  mounted() {
    this.getArea();
    let that = this;
    let host = window.location.host;
    let jsUrl = host.indexOf('localhost') > -1 ? 'http://111.11.19.54:6013/jsmap/jsmap.js' : window.location.protocol + "//" + host+'/jsmap/jsmap.js';
    that.loadScript('mapId', jsUrl, () => {
      that.canUseMap = true;
    })
  },
  methods: {
    loadScript(id, url, callback) {
      debugger;
      //如果已经存在这个id，则证明已经加载过，已经有这个js文件了，可以直接执行回调里面的操作
      if (document.querySelector(`#${id}`)) {
        callback && callback()
        return;
      }
      //第一次加载，先创建 script 标签
      const script = document.createElement('script');
      script.src = url;
      //创建id属性
      script.setAttribute('id', id);
      //获取第一个script标签
      const firstScript = document.getElementsByTagName('script')[0];
      //获取第一个script标签的父节点 BODY,在body的第一个script引用之前插入，即把这个动态的js文件放在第一个调用
      firstScript.parentNode.insertBefore(script, firstScript);
      //script 一加载就执行
      script.onload = script.onreadystatechange = function () {
        // 加载完成
        if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
          callback && callback()
        }
      };
    },
    getAllVchannel() {
      debugger;
      this.$API.am.video.list.req({ pageSize: 999 }).then(res => {
        debugger;
        console.log(res)
        let allVchannel = JSON.stringify(res.pageData);
        localStorage.setItem('allVchannel', allVchannel)
      })
    },
    handleView(row) {
      let that = this;
      that.channelCode = row.channelCode;
      that.channelName = row.channelName;
      that.limitedVisible = true;
    },
    viewClose() {
      this.limitedVisible = false;
    },
    //区域
    getArea() {
      this.$API.am.area.list.req({ page: 0 }).then((res) => {
        this.areaoptions = res;
      });
    },
    handlePosition(row) {
      // debugger;
      console.log(row)
      if (row.my_info.id && row.my_info.id !== null) {
        this.channelId = row.my_info.id ? row.my_info.id : null;
        this.channelArea = row.my_info.area ? row.my_info.area : '';
        this.channelAreas = row.my_info.areas ? row.my_info.areas : [];
        this.channelLocation = row.my_info.location ? row.my_info.location : {};
        this.channelName = row.channelName;
        if (this.canUseMap) {
          this.dialogSave = true;
        } else {
          this.$message("地图组件加载中，请稍后")
        }

      } else {
        this.$message.error("请先完成设备同步");
      }

    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection;
    },

    //搜索
    handleQuery() {
      debugger;
      let that = this;
      let vchannel = localStorage.getItem('allVchannel');
      console.log(vchannel)
      let allVchannel = JSON.parse(vchannel);
      debugger;
      console.log(allVchannel)
      console.log(that.areaId)

      that.pageData = allVchannel.filter(item => {
        if (item.my_info.area == that.areaId) {
          debugger;
        }
        return item.my_info.area == that.areaId;
      })
      // console.log(localStorage.getItem('allVchannel'))
    },

    resetQuery() {
      this.query = {};
    },

    async syncData() {
      this.syncLoading = true;
      var res = await this.$API.third.tdevice.vchannelSync.req({});
      this.$refs.table.refresh();
      this.syncLoading = false;
    },
  },
};
</script>
<style  lang="scss" scoped>
::v-deep .el-dialog {
  width: 100% !important;
  height: 100% !important;
}
</style>
