<template>
  <basic-container>
    <el-row>
      <el-col>
        <el-select v-model="value" filterable placeholder="请选择" @change="selectResidential">
          <el-option
            v-for="(item, idx) in residentialList"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        <el-button type="warning" size="small" icon="el-icon-remove" style="margin-left: 20px"
                   v-if="permission.elevator_sync"
                   @click="stopAll">停 止
        </el-button>
        <el-button type="success" size="small" icon="el-icon-remove" style="margin-left: 20px"
                   v-if="permission.elevator_sync"
                   @click="alarmName = '告警列表',alarmVisible = true">告警列表
        </el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col v-for="(item, index) in data" :key="index" :span="8"><div class="grid-content bg-purple" :style="styleObject">
        <el-card class="box-card" :body-style="{background: 'lightgrey'}">
          <el-button class="play-btn" type="success" size="mini" icon="el-icon-video-play" @click="playOne(index)">播 放</el-button>
          <label style="padding: 15px"><span>{{item.nbhdName}} - {{item.liftName}} - {{item.elevatorNo}}</span></label>
          <el-dropdown class="card-btn" size="mini" split-button type="primary" @click="videoDetail(index)">
            放 大
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item><el-button size="mini" type="primary" plain @click="getLiftStatusInfo(item)">实时梯况</el-button></el-dropdown-item>
              <el-dropdown-item><el-button size="mini" type="warning" plain @click="getLiftPointInfo(item)">梯内环境</el-button></el-dropdown-item>
              <el-dropdown-item><el-button size="mini" type="success" plain @click="getHisAlarm(item)">历史告警</el-button></el-dropdown-item>
<!--              <el-dropdown-item><el-button size="mini" type="warning" plain>警告按钮</el-button></el-dropdown-item>-->
<!--              <el-dropdown-item><el-button size="mini" type="danger" plain>危险按钮</el-button></el-dropdown-item>-->
            </el-dropdown-menu>
          </el-dropdown>
          <video :id="'myvideo' + index" autoplay  style="background-color: black; width:100%;height:100%"></video>
        </el-card>
      </div></el-col>
    </el-row>

    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" width="40%" top="1vh"
                :title="bigVideoName" :visible.sync="bigVideoVisible" @close="videoClose">
      <video id="bigVideo" autoplay  style="background-color: black; width:100%;height:100%"></video>
    </el-dialog>

    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" width="80%" top="2vh"
                :title="alarmName" :visible.sync="alarmVisible" center @close="registerCode = ''">
      <elevator-alarm v-if="alarmVisible" :register-code="registerCode"></elevator-alarm>
    </el-dialog>

    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" width="40%"
                title="实时梯况" :visible.sync="liftStatusVisible" center>
      <el-row>
        <el-form ref="liftStatusForm" :inline="true" label-width="auto">
          <div>
            <el-col :span="12" :push="1">
              <el-form-item label="运行速度：">
                <span>{{ liftStatus.speed + 'mm/s'}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="运行方向：">
                <span v-if="liftStatus.direction == 1">向下</span>
                <span v-if="liftStatus.direction == 2">向上</span>
                <span v-if="liftStatus.direction == 3">静止</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="梯门状态：">
                <span v-if="liftStatus.doorStatus == 1">开门</span>
                <span v-if="liftStatus.doorStatus == 2">关门</span>
                <span v-if="liftStatus.doorStatus == 3">正在开</span>
                <span v-if="liftStatus.doorStatus == 4">正在关</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="平层状态：">
                <span v-if="liftStatus.flatStatus == 1">平层</span>
                <span v-if="liftStatus.flatStatus == 2">非平层</span>
                <span v-if="liftStatus.flatStatus == 3">运动</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="当前楼层：">
                <span>{{ liftStatus.currentFloor + '层'}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="运行状态：">
                <span v-if="liftStatus.runModel == 0">停止</span>
                <span v-if="liftStatus.runModel == 1">运行</span>
              </el-form-item>
            </el-col>
          </div>
        </el-form>
      </el-row>
    </el-dialog>

    <el-dialog :append-to-body="true" :close-on-click-modal="false" :modal-append-to-body="false" width="40%"
                title="梯内环境" :visible.sync="liftPointVisible" center>
      <el-row>
        <el-form ref="liftStatusForm" :inline="true" label-width="auto">
          <div>
            <el-col :span="12" :push="1">
              <el-form-item label="轿厢烟感状态：">
                <span v-if="liftPoint.smokeDetector == false">OFF</span>
                <span v-if="liftPoint.smokeDetector == true">ON</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="轿厢顶温度：">
                <span>{{ liftPoint.carTopTemperature + '℃'}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="机房温度：">
                <span>{{ liftPoint.roomTemperature + '℃'}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="适配器电压：">
                <span>{{ liftPoint.dcValue}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="轿厢顶人感：">
                <span v-if="liftPoint.carTopHuman == 0">无人</span>
                <span v-if="liftPoint.carTopHuman == 1">有人</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="轿厢内人感：">
                <span v-if="liftPoint.carHuman == 0">无人</span>
                <span v-if="liftPoint.carHuman == 1">有人</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" :push="1">
              <el-form-item label="机房人感：">
                <span v-if="liftPoint.roomHuman == 0">无人</span>
                <span v-if="liftPoint.roomHuman == 1">有人</span>
              </el-form-item>
            </el-col>
          </div>
        </el-form>
      </el-row>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getLiftList, getDetail, add, update, remove, getLiftResidentialSelect,getLiftStatus, getLiftPointData, getRealvideo} from "@/api/device/elevatordevice";

  import {mapGetters} from "vuex";
  import {startPlay, stopPlay} from "@/api/device/elevatorUtil";
  import ElevatorAlarm from "./elevatoralarm";

  export default {
    components: {ElevatorAlarm},
    data() {
      return {
        registerCode: '',
        value: '',
        residentialList: [],
        plays: {},
        styleObject: {
          width: "300px",
          height: "450px",
        },
        bigVideoVisible: false,
        alarmVisible: false,
        liftStatusVisible: false,
        liftStatus: {},
        liftPointVisible: false,
        liftPoint: {},
        bigVideoName: '',
        alarmName: '',
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          addBtn: false,
          editBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "电梯注册编码",
              prop: "registerCode",
              rules: [{
                required: true,
                message: "请输入电梯注册编码",
                trigger: "blur"
              }]
            },
            {
              label: "电梯名称",
              prop: "liftName",
              rules: [{
                required: true,
                message: "请输入电梯名称",
                trigger: "blur"
              }]
            },
            {
              label: "小区名称",
              prop: "nbhdName",
              rules: [{
                required: true,
                message: "请输入小区名称",
                trigger: "blur"
              }]
            },
            {
              label: "梯号",
              prop: "elevatorNo",
              rules: [{
                required: true,
                message: "请输入梯号",
                trigger: "blur"
              }]
            },
            {
              label: "楼层数",
              prop: "floorNum",
              rules: [{
                required: true,
                message: "请输入楼层数",
                trigger: "blur"
              }]
            },
            {
              label: "楼号",
              prop: "floorNo",
              hide: true,
              rules: [{
                required: true,
                message: "请输入楼号",
                trigger: "blur"
              }]
            },
            {
              label: "单元号",
              prop: "partNo",
              hide: true,
              rules: [{
                required: true,
                message: "请输入单元号",
                trigger: "blur"
              }]
            },

            {
              label: "云梯状态",
              prop: "ytStatus",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=yt_status",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              rules: [{
                required: true,
                message: "请输入云梯状态{10：云梯处于未上线，安装调试状态，20：云梯处于已上线，正常状态，30：云梯处于故障，维护状态}",
                trigger: "blur"
              }]
            },
            {
              label: "在线状态",
              prop: "onlineStatus",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=yt_online_status",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              rules: [{
                required: true,
                message: "请输入在离线状态{0：离线，1：在线}",
                trigger: "blur"
              }]
            },
          ]
        },
        data: [],
        alarmData: [],
        alarmOption: {
          title:'历史告警',
          page:false,
          // viewBtn: true,
          addBtn: false,
          editBtn: false,
          delBtn: false,
          align:'center',
          menuAlign:'center',
          column:[
            {
              label:'小区名称',
              prop:'nbhdName'
            },
            {
              label:'电梯名称',
              prop:'liftName'
            },
            {
              label:'告警类型',
              prop:'alarmName'
            },
            {
              label: "告警时间",
              prop: "alarmTime",
              type: "date",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
            }
          ]
        },
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.elevator_add, false),
          viewBtn: this.vaildData(this.permission.elevator_view, false),
          delBtn: this.vaildData(this.permission.elevator_delete, false),
          editBtn: this.vaildData(this.permission.elevator_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {

      this.initVideoWidth();

      getLiftResidentialSelect().then(res => {
        this.residentialList = res.data.data;
        if (this.residentialList.length > 0){
          // let nbhdName = this.residentialList[0].nbhdName;
          let nbhdName = this.residentialList[0];
          this.value = nbhdName;
          this.onLoad({nbhdName: nbhdName});
        /*}else{
          this.onLoad();*/
        }
      });
    },
    methods: {
      initVideoWidth(){
        let $main = document.querySelector('.avue-main');
        let mainWidth = $main.clientWidth;
        let width = mainWidth * 0.30;
        let height = width / 0.76;
        this.styleObject.width = width + 'px';
        this.styleObject.height = height + 'px';
      },
      getHisAlarm(item){
        // let item = this.data[index];
        this.registerCode = item.registerCode;
        this.alarmVisible = true;
        this.alarmName = '【' + item.nbhdName+ ' - ' + item.liftName + ' - ' + item.elevatorNo + '】历史告警';
      },
      getLiftStatusInfo(item){
        item.registerCode && getLiftStatus(item.registerCode).then(res => {
          if (res.data.code == 200 && res.data.data.code == 0){
            this.liftStatusVisible = true;
            this.liftStatus = res.data.data.data;
          }
        });

      },
      getLiftPointInfo(item){
        item.registerCode && getLiftPointData(item.registerCode).then(res => {
          if (res.data.code == 200 && res.data.data.code == 0){
            this.liftPointVisible = true;
            this.liftPoint = res.data.data.data;
          }
        });

      },
      videoClose(){
        stopPlay(this.plays['bigVideo']);
      },
      videoDetail(index){
        this.bigVideoVisible = true;
        let item = this.data[index];
        this.bigVideoName = item.nbhdName;
        let elementId = 'bigVideo';
        let code = item.registerCode;

        getRealvideo(code).then(res => {
          // let obj = JSON.parse(res.data.data);
          let videoUrl = res.data.data.data.urls[0].httpsUrl;
          let player = startPlay(elementId, videoUrl, this.plays[elementId]);
          this.plays[elementId] = player;

        });
      },
      stopAll(){
        let _this = this;
        Object.keys(this.plays).forEach(item => {
          stopPlay(_this.plays[item]);
        })
      },
      selectResidential(value){
        this.stopAll();
        this.onLoad({nbhdName: value});
      },
      playOne(index){
        let code = this.data[index].registerCode;
        let elementId = 'myvideo' + index;
        getRealvideo(code).then(res => {
          // let obj = JSON.parse(res.data.data);
          let videoUrl = res.data.data.data.urls[0].httpsUrl;
          let player = startPlay(elementId, videoUrl, this.plays[elementId]);
          this.plays[elementId] = player;
          console.log("url=" + videoUrl)
        });
      },
      playAll(){
        this.data.forEach((item, index) => {
          this.playOne(index);
        })
      },
      /*handleSync(){
        this.loading = true;
        sync().then(() => {
          this.loading = false;
          let nbhdName = this.residentialList[0].nbhdName;
          this.onLoad({nbhdName: nbhdName});
        });
      },*/
      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.query);
      },
      onLoad(params = {}) {
        this.loading = true;
        getLiftList(Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.data = data;
          this.loading = false;
          this.playAll();
        });
      }
    }
  };
</script>

<style scoped>
  >>> .play-btn{
    margin-bottom: 5px;
    margin-top: -5px;
  }
  >>> .card-btn{
    float: right !important;
    margin-top: -5px;
  }
  >>> .grid-content{
    width: 380px;
    height: 500px;
  }
  >>> .el-form-item__label{
    font-weight: bold;
  }
</style>
