<!-- 国标监控设备-->
<template>
  <basic-container>
    <div v-if="!showDeviceChannelCrud">
      <avue-crud :option="deviceOption" :table-loading="loading" :data="data" :page="page" :permission="permissionList"
                 :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
                 @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
                 @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
        <template slot="streamMode" slot-scope="{row}">
          <el-select size="mini" v-model="row.streamMode" placeholder="请选择">
            <el-option key="UDP" label="UDP" value="UDP"></el-option>
            <el-option key="TCP-ACTIVE" label="TCP主动模式" :disabled="true" value="TCP-ACTIVE"></el-option>
            <el-option key="TCP-PASSIVE" label="TCP被动模式"  value="TCP-PASSIVE"></el-option>
          </el-select>
        </template>
        <template slot="online" slot-scope="{row}">
          <el-tag size="medium" v-if="row.online == 1">在线</el-tag>
          <el-tag size="medium" v-else type="info">离线</el-tag>
        </template>
        <template slot="hostAddress" slot-scope="{row}">
          <el-tag size="medium">{{row.hostAddress}}</el-tag>
        </template>

        <template slot="menu" slot-scope="{row}">
          <el-button size="mini" v-if="row.online != 0" icon="el-icon-refresh" plain @click="handleSync(row.deviceId, row.$index)">刷 新</el-button>
          <el-button-group>
            <el-button size="mini" :disabled="row.online != 1" type="primary" icon="el-icon-video-camera-solid" @click="handleChannel(row.deviceId)">通 道</el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" v-if="row.online != 1"  @click="deleteDevice(row.deviceId)">删除</el-button>
          </el-button-group>
        </template>

      </avue-crud>
    </div>
    <basic-container v-if="showDeviceChannelCrud">
      <avue-crud :option="deviceChannelOption" :table-loading="loading" :data="data" :page="page" :permission="permissionList"
                 :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
                 @search-change="channelSearchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
                 @size-change="sizeChange" @refresh-change="refreshChannelChange" @on-load="onLoadChannel">
        <template slot-scope="{row}" slot="channelTypeSearch">
          <el-select size="mini" style="margin-right: 1rem;" v-model="row.channelType" placeholder="请选择" default-first-option>
            <el-option label="全部" value=""></el-option>
            <el-option label="设备" value="false"></el-option>
            <el-option label="子目录" value="true"></el-option>
          </el-select>
        </template>
        <template slot-scope="{row}" slot="onlineSearch">
          <el-select size="mini" style="margin-right: 1rem;" v-model="row.online" placeholder="请选择" default-first-option>
            <el-option label="全部" value=""></el-option>
            <el-option label="在线" value="true"></el-option>
            <el-option label="离线" value="false"></el-option>
          </el-select>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" size="mini" icon="el-icon-arrow-left" @click="backToDeviceList">返 回</el-button>
        </template>
        <template slot="hasAudio" slot-scope="{row}">
          <el-switch @change="updateChannel(scope.row)" v-model="row.hasAudio" active-color="#409EFF">
          </el-switch>
        </template>
        <template slot="status" slot-scope="{row}">
          <el-tag size="medium" v-if="row.status == 1">开启</el-tag>
          <el-tag size="medium" v-else="row.status == 0">关闭</el-tag>
        </template>
        <template slot="status" slot-scope="{row}">
          <el-tag size="medium" v-if="row.status == 1">开启</el-tag>
          <el-tag size="medium" v-else="row.status == 0">关闭</el-tag>
        </template>
        <template slot="menu" slot-scope="{row}">
          <el-button size="mini" icon="el-icon-video-play" v-if="permission.wvpvideodevice_play" @click="devicePlay(row)">播放</el-button>
          <el-button size="mini" icon="el-icon-switch-button" type="danger" :loading="stopBtnLoading" v-if="permission.wvpvideodevice_stop && !!row.streamId" @click="deviceStopPlay(row)">停止</el-button>
          <el-button size="mini" type="primary" icon="el-icon-video-camera" v-if="permission.wvpvideodevice_record" @click="deviceRecord(row)">设备录像</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <devicePlayer ref="devicePlayer"></devicePlayer>
    <!--    小区列表-->
    <el-dialog :modal-append-to-body="false" append-to-body :visible.sync="bindVisible" title="设备绑定" center width="20%">
      <div style="text-align: center;">
        <!-- <el-select v-model="selectValue" filterable placeholder="请选择">
          <el-option v-for="item in residentialList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <p style="margin-top: 20px;">
          <el-button type="primary" icon="el-icon-paperclip" @click="bindDevice">绑定</el-button>
        </p> -->
        <avue-form v-model="bindForm" :option="bindOption" @submit="bindDevice">

        </avue-form>
      </div>
    </el-dialog>

    <el-dialog :modal-append-to-body="false" append-to-body :visible.sync="bindBatchVisible" title="设备批量绑定" center
               width="50%">
      <div style="text-align: center;">
        <avue-form v-model="bindBatchForm" :option="bindOption" @submit="bindBatchDevice">

        </avue-form>
      </div>
    </el-dialog>

    <el-dialog :modal-append-to-body="false" append-to-body :visible.sync="videoVisible" title="视频监控" center width="50%">
      <div>
        <div align="center">{{video.name}}</div>
        <video :id="videoId" controls="true" width="100%" height="100%">
        </video>
      </div>
    </el-dialog>
    <el-dialog :modal-append-tobody="false" append-to-body :visible.sync="editVisiable" title="编辑" width="60%">
      <avue-form :option="option" v-model="editForm" @submit="submitVideoclouddevice"></avue-form>
    </el-dialog>
    <el-dialog :modal-append-tobody="false" append-to-body :visible.sync="detailVisible" title="查看" width="60%">
      <avue-form :option="option1" v-model="detailForm" ></avue-form>
    </el-dialog>

  </basic-container>
</template>

<script>
import {
  getList,
  sync,
  getChannelList,
  startPlay,
  stopPlay,
  deleteDevice
} from "../../../../api/device/wvpvideodevice.js";
import {
  mapGetters
} from "vuex";
import {
  getAllList
} from "../../../../api/community/residential.js";
import devicePlayer from "../../videodevice/devicePlayer";

export default {
  components: {devicePlayer},
  data() {
    return {
      stopBtnLoading: false,
      openVideoDialog: false,
      parentChannelId: 0,
      searchSrt: "",
      channelType: "",
      online: "",
      curDeviceId: null,
      showDeviceChannelCrud: false,
      bindBatchForm:{},
      bindForm: {},
      videoVisible: false,
      video: {},
      editVisiable: false,
      editForm: {},
      detailVisible: false,
      detailForm: {},
      selectValue: "",
      form: {},
      query: {},
      loading: true,
      bindVisible: false,
      bindBatchVisible: false,
      residentialList: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],

      deviceOption: {
        menu: true,
        menuWidth:300,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 150,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        addBtn:false,
        column: [{
            label: "设备编号",
            prop: "deviceId",
            span: 12,
          },
          {
            label: "设备名称",
            prop: "name",
            span: 12,
          },
          {
            label: "厂家",
            prop: "manufacturer",
            span: 12,
            width: 100
          },
          {
            label: "流传输模式",
            prop: "streamMode",
            span: 12,
            width: 120,
            slot: true
          },
          {
            label: "通道数",
            prop: "channelCount",
            span: 12,
            width: 80
          },
          {
            label: "状态",
            prop: "online",
            span: 12,
            width:80,
            slot: true
          },
          {
            label: "最新心跳",
            prop: "keepaliveTime",
            span: 12,
          },
          {
            label: "最新注册",
            prop: "registerTime",
            span: 12,
          },
          {
            label: "ip地址",
            prop: "hostAddress",
            span: 12,
            slot: true
          },
          {
            label: "设备安装位置",
            prop: "address",
            span: 12,
            hide: true,
            rules: [{
              required: true,
              message: "请输入设备地址",
              trigger: "blur"
            }]
          },
        ]
      },
      deviceChannelOption: {
        menu: true,
        menuWidth: 300,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 150,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        addBtn:false,
        column: [
          {
            label: "搜索关键字",
            prop: "query",
            searchLabelWidth:120,
            hide: true,
            display: false,
            search: true
          },
          {
            label: "通道类型",
            prop: "channelType",
            hide: true,
            display: false,
            search: true,
            searchslot: true
          },
          {
            label: "在线状态",
            prop: "online",
            hide: true,
            display: false,
            search: true,
            searchslot: true
          },
          {
            label: "通道编号",
            prop: "channelId",
            span: 12,
          },
          {
            label: "设备编号",
            prop: "deviceId",
            span: 12,
          },
          {
            label: "通道名称",
            prop: "name",
            span: 12,
            width: 100
          },
          {
            label: "子节点数",
            prop: "subCount",
            span: 12,
            width: 120
          },
          {
            label: "开启音频",
            prop: "hasAudio",
            span: 12,
            width: 80,
            slot: true
          },
          {
            label: "状态",
            prop: "status",
            span: 12,
            width:80,
            slot: true
          },
          {
            label: "云台类型",
            prop: "ptztypeText",
            span: 12,
          },
        ]
      },
      bindOption: {
        column: [
          {
            label: "所属小区",
            prop: "residentialId",
            type: "select",
            search: true,
            span:24,
            cascaderItem: ['buildingId'],
            dicUrl: "/api/cyzh-community/residential/list?size=9999",
            dicFormatter:(res)=>{
              return res.data.records;//返回字典的层级结构
            },
            props: {
              label: "name",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请选择所属小区",
              trigger: "blur"
            }]
          },
          {
            label: "所属楼栋",
            prop: "buildingId",
            search: true,
            type: "select",
            span:24,
            cascaderIndex: 0,
            dicUrl: "/api/cyzh-community/building/list?residentialId={{key}}",
            dicFormatter:(res) => {
              return res.data.records;//返回字典层级结构
            },
            filterable: true,
            props: {
              label: "name",
              value: "id"
            },
          }]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.wvpvideodevice_add, false),
        viewBtn: this.vaildData(this.permission.wvpvideodevice_view, false),
        delBtn: this.vaildData(this.permission.wvpvideodevice_delete, false),
        editBtn: this.vaildData(this.permission.wvpvideodevice_edit, false),
        playBtn: this.vaildData(this.permission.wvpvideodevice_play, false),
        recordBtn: this.vaildData(this.permission.wvpvideodevice_record, false),
        stopBtn: this.vaildData(this.permission.wvpvideodevice_stop, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "y+": date.getFullYear().toString(),        // 年
        "M+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "m+": date.getMinutes().toString(),         // 分
        "s+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
      };
      return fmt;
    },
    deleteDevice(deviceId) {
      let that = this;
      deleteDevice(deviceId).then(res => {
        that.onLoad(that.page);
      }).catch(error => {
        console.log(error);
      })
    },
    deviceRecord(row){
      let deviceId = row.deviceId;
      let channelId = row.channelId;
      let format = this.dateFormat("yyyy-MM-dd", new Date());
      this.$refs.devicePlayer.openDialog("record", deviceId, channelId, {date: format})
    },
    devicePlay(row){
      this.openVideoDialog = true;
      let deviceId = row.deviceId;
      let channelId = row.channelId;
      let that = this;
      startPlay(deviceId, channelId).then(res => {
        that.openVideoDialog = false;
        if (res.data.code == 200) {
          that.$refs.devicePlayer.openDialog("media", deviceId, channelId, {
            streamInfo: res.data.data,
            hasAudio: row.hasAudio
          });
          that.onLoadChannel(that.page);
        }else {
          that.$message.error(res.data.msg);
        }
      });
    },
    deviceStopPlay(row) {
      let that = this;
      let deviceId = row.deviceId;
      let channelId = row.channelId;
      this.startBtnLaoding = true;
      stopPlay(deviceId, channelId).then(res => {
        console.log(JSON.stringify(res));
        that.onLoadChannel(that.page);
        this.startBtnLaoding = false;
      }).catch(err => {
        if (err.response.status === 402) { // 已经停止过
          that.onLoadChannel(that.page);
        }else {
          console.log(err)
        }
      });
    },
    channelSearchChange(params, done){
      this.query = params;
      this.page.currentPage = 1;
      if (typeof (this.parentChannelId) == "undefined" ||  this.parentChannelId == 0) {
        this.onLoadChannel(this.page);
      }
      done();
    },
    backToDeviceList(){
      this.showDeviceChannelCrud = false;
      this.curDeviceId = null;
    },
    handleSync(deviceId, index){
      sync(deviceId).then(res => {
        let result = res.data.data;
        this.$set(this.data, index, result)
      });
    },
    handleChannel(deviceId){
      this.showDeviceChannelCrud = true;
      this.curDeviceId = deviceId;
    },
    showVideo(row) {
      this.video.url = "ws://36.103.228.148:8888/live/" + row.id + ".flv";
      this.video.name = row.deviceName;
      this.videoVisible = true;
      this.$nextTick(() => {
        try {
          let videoElement = document.getElementById('videoId');
          let flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: this.video.url
          });
          flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
            // errType是 NetworkError时，对应errDetail有：Exception、HttpStatusCodeInvalid、ConnectingTimeout、EarlyEof、UnrecoverableEarlyEof
            // errType是 MediaError时，对应errDetail是MediaMSEError
          });
          flvPlayer.on(flvjs.Events.MEDIA_SOURCE_CLOSE || flvjs.Events.MEDIA_SOURCE_ENDED, () => {})
          flvPlayer.attachMediaElement(videoElement);
          flvPlayer.load();
          flvPlayer.play();
        } catch (e) {
          console.log(e);
        }
      })
    },
    showDeviceBindBatch() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if (this.residentialList.length == 0) {
        //  请求获取小区列表
        getAllList().then(res => {
          console.log(res.data.data);
          this.residentialList = res.data.data;
          this.selectValue = "";
          this.bindBatchVisible = true;
        })
      } else {
        this.selectValue = ""
        this.bindBatchVisible = true;
      }
      // this.form = row;
    },
    showDeviceBind(row) {

      if (this.residentialList.length == 0) {
        //  请求获取小区列表
        getAllList().then(res => {
          this.residentialList = res.data.data;
          this.selectValue = ""
          this.bindVisible = true;
        })
      } else {
        this.selectValue = ""
        this.bindVisible = true;
      }
      this.bindForm = row;
    },
    bindBatchDevice(loading,done) {
      // if (this.selectValue == "") {
      //   this.$message.warning("请选择所属小区");
      //   return;
      // }
      //保存
      bindResidentialBatch(this.ids, this.bindBatchForm.residentialId,this.bindBatchForm.buildingId).then(() => {
        this.bindBatchVisible = false;
        this.bindBatchForm = {};
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    bindDevice(loading,done) {
      // this.form.residentialId = this.selectValue;
      //保存
      updateVideoDevice(this.bindForm).then(() => {
        this.onLoad(this.page);
        this.bindVisible = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    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) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    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();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    refreshChannelChange() {
      this.onLoadChannel(this.page, this.query);
    },
    edit(row) {
      console.log(row,"编辑数据")
      this.editForm = row;
      this.editVisiable = true;
    },
    view(row) {
      console.log(row,"详情数据")
      this.detailForm = row;
      this.detailVisible = true;
    },
    submitVideoclouddevice(row,done,loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    onLoadChannel(page, params = {}) {
      this.loading = true;
      getChannelList(page.currentPage, page.pageSize, this.curDeviceId, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: small;
  margin-left: 10px;
}
</style>
