<template>
  <basic-container>
    <!-- <el-row>
      <el-col span="4">
        <el-tree
        ref="tree"
          :data="treeDatas"
          lazy
          show-checkbox
          node-key="id"
          :props="defaultProps"
          :load="loadChild"
          @check="checkClick">
        </el-tree>
      </el-col>
      <el-col span="20">

      </el-col>
    </el-row> -->
    <el-row>
      <el-col v-if="tenantType == 0" span="4" align="right" style="font-size: large;">所属小区：</el-col>
      <el-col v-if="tenantType == 1" span="4" align="right" style="font-size: large;">所属区域：</el-col>
      <el-col span="4" align="left">
        <el-select size="small" v-model="selectResidential" filterable  clearable @change="residentialIdChange">
          <el-option v-for="item in residentialList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col span="4" align="right" style="font-size: large;">所属楼栋：</el-col>
      <el-col span="4" align="left">
        <el-select size="small" v-model="selectBuilding" filterable placeholder="所属楼栋"  clearable>
          <el-option v-for="item in buildingList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col span="4" align="right" style="font-size: large;">设备名称：</el-col>
      <el-col span="4" align="left">
        <el-input v-model="deviceName" size="mini" clearable></el-input>
      </el-col>
    </el-row>
    <div id="videoSurveillance" style="margin-top: 20px;">
      <div class="item" v-for="(item,index) in data" :key="index">
        <div align="center">{{item.name}}</div>
        <video :id="'videoId'+index" controls="true" width="100%" height="100%">
        </video>
      </div>
    </div>
  </basic-container>
</template>


<script>
import {
  getList as getAgencyList
} from "@/api/community/agency"
import {
 getList as getResdList
} from "@/api/community/residential";
import {
  getList as getBuildList
} from "@/api/community/building"
import {
  getList as getDevicesList
} from "@/api/device/videoclouddevice";
import {
  mapGetters
} from "vuex";
  import {pushStream} from "@/api/device/videoclouddevice"
export default {
  data() {
    // http://139.9.103.171/live?port=1935&app=myapp&stream=mystream
    // http://139.9.103.171/live?port=1935&app=myapp&stream=mystream1
    // http://139.9.103.171/live?port=1935&app=myapp&stream=mystream3
    return {
      tenantType: '',
      selectBuilding: "",
      buildingList:[],
      deviceName: "",
      selectResidential: "",
      loading: false,
      residentialList: [],
      value: [],
      // baseUrlVedio: "http://139.9.103.171/live?port=1935&app=myapp&stream=",
      baseUrlVedio: "ws://36.103.228.148:8888/live/",
      data: [],
      treeDatas:[],
      defaultProps:{
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      }
    }
  },
  computed:{
    ...mapGetters(["userInfo","orgInfo"])
  },
  mounted() {
    var _this = this
    // let orgInfo = this.$store.getters.orgInfo
    // if(orgInfo.deptType=="5"||orgInfo.deptType=="7"||orgInfo.deptType=="8"||orgInfo.deptType=="9"){
    //   getAgencyList(1,10000).then(res => {
    //     _this.treeDatas = res.data.data.records
    //   })
    // }else{
    //   getResdList(1,10000).then(res => {
    //     _this.treeDatas = res.data.data.records
    //   })
    // }
    //  请求获取小区列表
    getResdList(1,10000).then(res => {
      _this.residentialList = res.data.data.records;
    })
    this.onLoad()
  },
  watch:{
    "selectResidential":function(){
      this.onLoad()
    },
    "selectBuilding":function(){
      this.onLoad()
    },
    "deviceName":function(){
      this.onLoad()
    }
  },
  created() {
    this.tenantType = localStorage.getItem("tenantType");
  },
  methods: {
    checkClick(e1,e2){
      console.log(e1,e2)
    },
    loadChild(node,resolve){
      var _this = this
      let orgInfo = this.$store.getters.orgInfo
      if(orgInfo.deptType=="5"||orgInfo.deptType=="7"||orgInfo.deptType=="8"||orgInfo.deptType=="9"){
        if(node.level=="1"){
          getResdList(1,10000,{agencyId:node.key}).then(res => {
            let datas = res.data.data.records
            resolve(datas?datas:[])
          })
        }else if(node.level=="2"){
          getBuildList(1,10000,{residentialId:node.key}).then(res => {
            let datas = res.data.data.records.map((item)=>{
              return Object.assign(item,{"leaf":true})
            })
            resolve(datas?datas:[])
          })
        }else{
          resolve([])
        }
      }else{
        if(node.level=="1"){
          getBuildList(1,10000,{residentialId:node.key}).then(res => {
            let datas = res.data.data.records.map((item)=>{
              return Object.assign(item,{"leaf":true})
            })
            resolve(datas?datas:[])
          })
        }else{
          resolve([])
        }
      }

    },
    play() {
      this.data.map((item, index) => {
        try {
          let videoElement = document.getElementById('videoId' + index);
          let flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: item.src
          });
          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);
        }

      })
    },
    residentialIdChange(){
      let params = {}
      params['residentialId'] = this.selectResidential;
      getBuildList(1,10000,params).then((res)=>{
          this.selectBuilding = ""
          this.buildingList = res.data.data.records;
      })
    },
    onLoad() {
        let _this = this;
        if (this.value&&(this.selectResidential != ""||this.selectBuilding != "" || this.deviceName !="")) {
          getDevicesList("1","10000",{"residentialId":this.selectResidential,"buildingId":this.selectBuilding,"deviceName":this.deviceName}).then(res => {
            if (res.data.code == 200) {
              this.data = [];
              const data = res.data.data.records;
              data.forEach(item => {
                pushStream({deviceNum: item.deviceNum}).then((psres)=>{
                  let psdata = psres.data.data
                  if(psdata&&psdata.videoExists){
                    let obj = {};
                    obj.src = psdata.flvUrl;
                    obj.name = psdata.deviceName;
                    _this.data.push(obj);
                    _this.$nextTick(()=>{
                      _this.play();
                    })
                  }
                })
              })
            }
          });
        }else{
          this.data = [];
        }
    }
  }
}
</script>


<style lang="less">
#videoSurveillance {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;

  .item {
    width: calc(~"25% - 10px");
    overflow: hidden;
    border-radius: 5px;
    margin: 5px;
  }
}
</style>
