<template>
  <div id="channelList" style="width: 100%">
    <div class="page-header">
      <div class="page-title">
        <el-button icon="el-icon-back" size="mini" style="font-size: 20px; color: #000;" type="text"
                   @click="showDevice"></el-button>
        <el-divider direction="vertical"></el-divider>
        {{ $t('device.channelList') }}
      </div>
      <div class="page-header-btn">
        <div v-if="!showTree" style="display: inline;">
          <el-button size="medium" type="text" @click="switchUsePs()">{{ isUsePs ? $t('device.enablePs') : $t('device.disablePs') }}</el-button>
          {{ $t('search') }}:
          <el-input @input="search" style="margin-right: 1rem; width: auto;" size="mini" :placeholder="$t('keyword')"
                    prefix-icon="el-icon-search" v-model="searchSrt" clearable></el-input>

          {{ $t('device.channelType') }}:
          <el-select size="mini" @change="search" style="margin-right: 1rem;" v-model="channelType" :placeholder="$t('pleaseSelect')"
                     default-first-option>
            <el-option :label="$t('all')" value=""></el-option>
            <el-option :label="$t('device.title')" value="false"></el-option>
            <el-option :label="$t('device.subDir')" value="true"></el-option>
          </el-select>
          {{ $t('device.onlineState') }}:
          <el-select size="mini" style="margin-right: 1rem;" @change="search" v-model="online" :placeholder="$t('pleaseSelect')"
                     default-first-option>
            <el-option :label="$t('all')" value=""></el-option>
            <el-option :label="$t('device.online')" value="true"></el-option>
            <el-option :label="$t('device.offline')" value="false"></el-option>
          </el-select>
        </div>
        <el-button icon="el-icon-refresh-right" circle size="mini" @click="refresh()"></el-button>
        <el-button v-if="showTree" icon="iconfont icon-list" circle size="mini" @click="switchList()"></el-button>
        <el-button v-if="!showTree" icon="iconfont icon-tree" circle size="mini" @click="switchTree()"></el-button>
      </div>
    </div>
    <ptz-control ref="ptzControl"/>
    <!--  <devicePlayer ref="devicePlayer" ></devicePlayer>-->
    <!--    <custom-player ref="devicePlayer" @close="closeHandle()"></custom-player>-->
    <new-play
        :show.sync="showPlayDialog"
        :enableDebug="false"
        :info="streamInfo"
        :device-id="deviceId"
        :channel-id="playChannelId"
        :shareUrl="shareUrl"
        @repush="rePushHandle()"
        @sharePlay="sharePlayHandle"
        ref="devicePlayer"
        @close="closeHandle()"></new-play>
    <el-container v-loading="isLoging" style="height: 82vh;">
      <el-aside width="auto" style="height: 82vh; background-color: #ffffff; overflow: auto" v-if="showTree">
        <DeviceTree ref="deviceTree" :device="device" :onlyCatalog="true" :clickEvent="treeNodeClickEvent"></DeviceTree>
      </el-aside>
      <el-main style="padding: 5px;">
        <el-table ref="channelListTable" :data="deviceChannelList"
                  :height="winHeight" style="width: 100%"
                  :row-key="record=>record.id"
                  header-row-class-name="table-header">
          <el-table-column prop="channelId" :label="$t('device.channelId')" min-width="200">
          </el-table-column>
          <el-table-column prop="deviceId" :label="$t('device.id')" min-width="200">
          </el-table-column>
          <el-table-column prop="name" :label="$t('device.channelName')" min-width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <el-input size="mini" v-model="editName" clearable></el-input>
                <el-button size="mini" type="text" @click="saveEditName(scope.row)">{{ $t('save') }}</el-button>
                <el-button size="mini" type="text" @click="exitEditName(scope.row)">{{ $t('cancel') }}</el-button>
              </div>
              <span v-else @click="toEditMode(scope.row)">{{ scope.row.name }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="subCount" :label="$t('device.channelCount')" min-width="120">
          </el-table-column>
          <el-table-column prop="manufacture" :label="$t('device.manufacturer')" min-width="120">
          </el-table-column>
          <el-table-column :label="$t('device.position')" min-width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.longitude*scope.row.latitude > 0">
                {{scope.row.longitude}},
                <br>
                {{ scope.row.latitude }}
              </span>
              <span v-if="scope.row.longitude*scope.row.latitude === 0">
                {{ $t('unknown') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="ptztypeText" :label="$t('device.ptzType')" min-width="120"/>
          <el-table-column :label="$t('device.enableAudio')" min-width="120">
            <template slot-scope="scope">
              <el-switch @change="updateChannel(scope.row)" v-model="scope.row.hasAudio" active-color="#409EFF">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column :label="$t('state')" min-width="120">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium" v-if="scope.row.status === 1">{{ $t('device.online') }}</el-tag>
                <el-tag size="medium" type="info" v-if="scope.row.status === 0">{{ $t('device.offline') }}</el-tag>
              </div>
            </template>
          </el-table-column>


          <el-table-column :label="$t('operation')" min-width="280" fixed="right">
            <template slot-scope="scope">
              <el-button size="medium" icon="el-icon-coordinate" type="text" @click="showPtzControl(scope.row)">
                {{ $t('device.ptz') }}
              </el-button>
              <el-button size="medium" v-bind:disabled="device == null || device.online === 0" icon="el-icon-video-play"
                         type="text" @click="sendDevicePush(scope.row)">
                {{ $t('device.play') }}
              </el-button>
              <el-button size="medium" v-bind:disabled="device == null || device.online === 0"
                         icon="el-icon-switch-button" type="text" style="color: #f56c6c" v-if="!!scope.row.streamId"
                         @click="stopDevicePush(scope.row)">
                {{ $t('device.stop') }}
              </el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button size="medium" icon="el-icon-s-open" type="text"
                         v-if="scope.row.subCount > 0 || scope.row.parental === 1"
                         @click="changeSubchannel(scope.row)">
                {{ $t('view') }}
              </el-button>
              <el-divider v-if="scope.row.subCount > 0 || scope.row.parental === 1" direction="vertical"></el-divider>
              <el-button size="medium" v-bind:disabled="device == null || device.online === 0"
                         icon="el-icon-video-camera" type="text" @click="queryRecords(scope.row)">
                {{ $t('device.record') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            style="float: right"
            @size-change="handleSizeChange"
            @current-change="currentChange"
            :current-page="currentPage"
            :page-size="count"
            :page-sizes="[15, 25, 35, 50]"
            layout="total, sizes, prev, pager, next"
            :total="total">
        </el-pagination>
      </el-main>
    </el-container>

    <!--设备列表-->

  </div>
</template>

<script>
import devicePlayer from './dialog/devicePlayer.vue'
import uiHeader from '../layout/UiHeader.vue'
import DeviceService from "./service/DeviceService";
import DeviceTree from "./common/DeviceTree";
import PtzControl from "./dialog/dialogPtzControl";
import CustomPlayer from "@/components/dialog/customPlayer";
import newPlay from "@/components/dialog/newPlay.vue";
import handle from "@/until/handle";
import copy from "@/until/copy";

export default {
  name: 'channelList',
  components: {
    CustomPlayer,
    PtzControl,
    devicePlayer,
    uiHeader,
    DeviceTree,
    newPlay
  },
  data() {
    return {
      showPlayDialog: false,
      deviceService: new DeviceService(),
      device: null,
      deviceId: this.$route.params.deviceId,
      parentChannelId: this.$route.params.parentChannelId,
      playChannelId: '',
      deviceChannelList: [],
      videoComponentList: [],
      currentPlayerInfo: {}, //当前播放对象
      updateLooper: 0, //数据刷新轮训标志
      searchSrt: "",
      channelType: "",
      online: "",
      winHeight: window.innerHeight - 200,
      currentPage: 1,
      count: 15,
      total: 0,
      beforeUrl: "/deviceList",
      isLoging: false,
      showTree: false,
      loadSnap: {},
      isUsePs: true,
      editName: '',
      streamInfo: {},
      shareUrl: ""
    };
  },

  mounted() {
    if (this.deviceId) {
      this.deviceService.getDevice(this.deviceId, (result) => {
        this.device = result;

      }, (error) => {
        console.log("获取设备信息失败")
        console.error(error)
      })
    }
    this.initData();

  },
  destroyed() {
    this.$destroy('videojs');
    clearTimeout(this.updateLooper);
  },
  methods: {
    async copy(str) {
      let [err, res] = await handle(copy(str))
      if (err) {
        return this.$message.error(err.message);
      }
      this.$message.success('复制播放地址成功');
    },
    initData: function () {
      if (typeof (this.parentChannelId) == "undefined" || this.parentChannelId == 0) {
        this.getDeviceChannelList();
      } else {
        this.showSubchannels();
      }
    },
    initParam: function () {
      this.deviceId = this.$route.params.deviceId;
      this.parentChannelId = this.$route.params.parentChannelId;
      this.currentPage = 1;
      this.count = 15;
      if (this.parentChannelId == "" || this.parentChannelId == 0) {
        this.beforeUrl = "/deviceList"
      }
    },
    currentChange: function (val) {
      this.currentPage = val;
      this.initData();
    },
    handleSizeChange: function (val) {
      this.count = val;
      this.getDeviceChannelList();
    },
    getDeviceChannelList: function () {
      let that = this;
      if (typeof (this.$route.params.deviceId) == "undefined") return;
      this.$axios.axios({
        method: 'get',
        url: `/api/device/query/devices/${this.$route.params.deviceId}/channels`,
        params: {
          page: that.currentPage,
          count: that.count,
          query: that.searchSrt,
          online: that.online,
          channelType: that.channelType
        }
      }).then(function (res) {
        if (res.data.code === 0) {
          let list = res.data.data.list;
          that.total = res.data.data.total;
          list.forEach(item => {
            // 是否为编辑状态
            item.isEdit = false;
          });
          that.deviceChannelList = list;
          // 防止出现表格错位
          that.$nextTick(() => {
            that.$refs.channelListTable.doLayout();
          })
        }

      }).catch(function (error) {
        console.log(error);
      });
    },
    showPtzControl(itemData) {
      let deviceId = this.deviceId;
      let channelId = itemData.channelId;
      this.isLoging = true;
      this.isLoging = false;
      this.$refs.ptzControl.showPtzControl(deviceId, channelId);
    },

    switchUsePs() {
      this.isUsePs = !this.isUsePs;
    },
    //通知设备上传媒体流
    async sendDevicePush(itemData) {
      let deviceId = this.deviceId;
      this.showPlayDialog = false;
      this.isLoging = true;

      let channelId = itemData.channelId;
      let isUsePs = this.isUsePs ? 1 : 0;
      let pushUrl = `/api/play/start/${deviceId}/${channelId}?isUsePs=${isUsePs}`
      console.log(pushUrl);
      console.log("通知设备推流1：" + deviceId + " : " + channelId);
      let [err, res] = await handle(this.$axios.axios({
        method: 'get',
        url: pushUrl
      }));
      if (err) {
        console.log(err);
        this.isLoging = false;
        this.$message.error(`请求失败,${err.message}`);
        return;
      }
      console.log(res);
      this.isLoging = false;
      let msg = ''
      if (res.data.code !== 0) {
        msg = this.$t(`video.pushFailCode.${res.data.code}`, { msg: res.data.msg })
        if (!msg) {
          msg = this.$t("notification.pushFail", { msg: res.data.msg })
        }
        console.log(msg)
        this.$message.error(msg);
        return;
      }
      setTimeout(() => {
        this.loadSnap[deviceId + channelId] = 0;
        this.getSnapErrorEvent(`${deviceId}_${channelId}`)
      }, 5000);

      this.showPlayDialog = true;
      itemData.streamId = res.data.data.stream;
      // 强制更新 this.streamInfo
      console.log(res.data.data)
      this.$set(this, 'streamInfo', res.data.data);
      this.$nextTick(() => {
        this.$set(this, 'streamInfo', res.data.data);
      })
      this.playChannelId = channelId;
      console.log("streamInfo：");
      console.log(this.streamInfo);
      setTimeout(() => {
        this.initData();
      }, 1000)
    },
    queryRecords: function (itemData) {
      let deviceId = this.deviceId;
      let channelId = itemData.channelId;

      this.$router.push(`/gbRecordDetail/${deviceId}/${channelId}`)
    },
    stopDevicePush: function (itemData) {
      var that = this;
      this.$axios.axios({
        method: 'get',
        url: '/api/play/stop/' + this.deviceId + "/" + itemData.channelId
      }).then(function (res) {
        that.initData();
      }).catch(function (error) {
        if (error.response.status === 402) { // 已经停止过
          that.initData();
        } else {
          console.log(error)
        }
      });
    },
    getSnap: function (row) {
      let url = (process.env.NODE_ENV === 'development' ? "debug" : "") + '/api/device/query/snap/' + row.deviceId + '/' + row.channelId
      return url
    },
    getBigSnap: function (row) {
      return [this.getSnap(row)]
    },
    getSnapErrorEvent: function (deviceId, channelId) {

      if (typeof (this.loadSnap[deviceId + channelId]) != "undefined") {
        console.log("下载截图" + this.loadSnap[deviceId + channelId])
        if (this.loadSnap[deviceId + channelId] > 5) {
          delete this.loadSnap[deviceId + channelId];
          return;
        }
        setTimeout(() => {
          let url = (process.env.NODE_ENV === 'development' ? "debug" : "") + '/api/device/query/snap/' + deviceId + '/' + channelId
          this.loadSnap[deviceId + channelId]++
          document.getElementById(deviceId + channelId).setAttribute("src", url + '?' + new Date().getTime())
        }, 1000)

      }
    },
    showDevice: function () {
      this.$router.push(this.beforeUrl).then(() => {
        this.initParam();
        this.initData();
      })
    },
    changeSubchannel(itemData) {
      this.beforeUrl = this.$router.currentRoute.path;

      var url = `/${this.$router.currentRoute.name}/${this.$router.currentRoute.params.deviceId}/${itemData.channelId}`
      this.$router.push(url).then(() => {
        this.searchSrt = "";
        this.channelType = "";
        this.online = "";
        this.initParam();
        this.initData();
      })
    },
    showSubchannels: function (channelId) {
      if (!this.showTree) {
        this.$axios.axios({
          method: 'get',
          url: `/api/device/query/sub_channels/${this.deviceId}/${this.parentChannelId}/channels`,
          params: {
            page: this.currentPage,
            count: this.count,
            query: this.searchSrt,
            online: this.online,
            channelType: this.channelType
          }
        }).then((res) => {
          if (res.data.code === 0) {
            this.total = res.data.data.total;
            this.deviceChannelList = res.data.data.list;
            // 防止出现表格错位
            this.$nextTick(() => {
              this.$refs.channelListTable.doLayout();
            })
          }

        }).catch(function (error) {
          console.log(error);
        });
      } else {
        this.$axios.axios({
          method: 'get',
          url: `/api/device/query/tree/channel/${this.deviceId}`,
          params: {
            parentId: this.parentChannelId,
            page: this.currentPage,
            count: this.count,
          }
        }).then((res) => {
          if (res.data.code === 0) {
            this.total = res.data.total;
            this.deviceChannelList = res.data.list;
            // 防止出现表格错位
            this.$nextTick(() => {
              this.$refs.channelListTable.doLayout();
            })
          }
        }).catch(function (error) {
          console.log(error);
        });
      }

    },
    search: function () {
      this.currentPage = 1;
      this.total = 0;
      this.initData();
    },
    updateChannel: function (row) {
      this.$axios.axios({
        method: 'post',
        url: `/api/device/query/channel/update/${this.deviceId}`,
        params: row
      }).then(function (res) {
        console.log(JSON.stringify(res));
      });
    },
    refresh: function () {
      this.initData();
    },
    switchTree: function () {
      this.showTree = true;
      this.deviceChannelList = [];
      this.parentChannelId = 0;
      this.currentPage = 1;

    },
    switchList: function () {
      this.showTree = false;
      this.deviceChannelList = [];
      this.parentChannelId = 0;
      this.currentPage = 1;
      this.initData();
    },
    treeNodeClickEvent: function (device, data, isCatalog) {
      console.log(device)
      if (!!!data.channelId) {
        this.parentChannelId = device.deviceId;
      } else {
        this.parentChannelId = data.channelId;
      }
      this.initData();
    },
    closeHandle() {
      // 刷新页面
      this.refresh();
    },
    saveEditName(row) {
      if (this.editName === "") {
        this.$message({
          message: '名称不能为空',
          type: 'warning'
        });
        return;
      }
      row.name = this.editName;
      this.updateChannel(row);
      row.isEdit = false;
      this.editName = "";
      this.$notify.info({
        title: 'Tips',
        message: '在编辑通道名称后,请前往设备编辑界面选择不跟随sip更新数据,用以持久化数据',
      })
    },
    exitEditName(row) {
      row.isEdit = false;
      this.editName = "";
    },
    toEditMode(row) {
      row.isEdit = true;
      this.editName = row.name;
    },
    // 播放器重新拉流
    rePushHandle(){
      // 获取对应的 item ;
      let channelItem = this.deviceChannelList.find(item => item.channelId === this.playChannelId)
      if (channelItem) {
        this.sendDevicePush(channelItem);
      } else {
        this.$message.error('重新拉流失败,无法找到对应的通道信息');
      }
    },
    sharePlayHandle(){
      this.$message.info("尝试开启分享中...");
      this.queryOpenShare(this.deviceId, this.playChannelId);

    },
    async queryOpenShare(deviceId, channelId){
      let err,res;
      let url = `/api/device/query/share/open`;
      url += `?deviceId=${deviceId}&channelId=${channelId}`;
      this.loading = true;
      [err, res] = await handle(this.$axios.get(url));
      this.loading = false;
      if(err){
        this.$message.error("开启分享失败,请稍后重试");
        console.error(err);
        return;
      }
      if(res.data.code !== 0){
        this.$message.error("开启分享失败,请稍后重试");
        return;
      }
      this.$message.success("开启分享成功");
      let shareCode = res.data.data;
      console.log(shareCode);
      this.shareUrl = `${window.location.origin}/share?shareCode=${shareCode}`;
      await this.copy(this.shareUrl);
    },
    async queryCloseShare(deviceId){
      let err,res;
      let url = `/api/device/query/share/close`;
      url += `?deviceId=${deviceId}`;
      [err, res] = await handle(this.$axios.get(url));
      this.loading = false;
      if(err){
        this.$message.error("关闭分享失败,请稍后重试");
        console.error(err);
        return;
      }
      if(res.data.code !== 0){
        this.$message.error("关闭分享失败,请稍后重试");
        return;
      }
      this.$message.success("关闭分享成功");
    }
  }
};
</script>

<style>
.videoList {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.video-item {
  position: relative;
  width: 15rem;
  height: 10rem;
  margin-right: 1rem;
  background-color: #000000;
}

.video-item-img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  height: 100%;
}

.video-item-img:after {
  content: "";
  display: inline-block;
  position: absolute;
  z-index: 2;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 3rem;
  height: 3rem;
  background-image: url("../assets/loading.png");
  background-size: cover;
  background-color: #000000;
}

.video-item-title {
  position: absolute;
  bottom: 0;
  color: #000000;
  background-color: #ffffff;
  line-height: 1.5rem;
  padding: 0.3rem;
  width: 14.4rem;
}
</style>
