<template>
  <section class="AppMonitorManage">
    <device-slider :show.sync="slider" :ins="instance" :dict="dict" @select="handleSelectMonitor"
                   :render-item="renderTreeItem" ref="DeviceSlider"/>
    <div class="monitorPane">
      <div class="headerBar">
        <el-select default-first-option size="small" v-model="splitScreen">
          <i slot="prefix" class="iconfont iconjdq_led_Led1"/>
          <el-option v-for="(op,i) in splitOps" :key="i" v-bind="op"/>
        </el-select>
        <!--        <el-button icon="el-icon-full-screen" @click="handleFullscreen">全屏</el-button>-->
      </div>
      <div class="videoList">
        <div class="videoBox" v-for="(m,i) in monitors" :key="i" :style="currentSplitStyle">
          <iframe :src="m.url" allow="autoplay *; microphone *; fullscreen *" allowfullscreen allowtransparency
                  allowusermedia frameBorder="no"/>
        </div>
      </div>
    </div>
    <ai-dialog title="修改名称" :visible.sync="dialog" width="500px" @onConfirm="handleSubmit(selected)"
               @closed="selected={}">
      <el-form ref="form" :model="selected" label-width="80px" size="small" :rules="rules">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="selected.name" clearable/>
        </el-form-item>
      </el-form>
    </ai-dialog>
    <ai-locate-dialog v-model="locate" :ins="instance" :latlng="latlng" @confirm="v=>handleLocate(selected,v)"/>
    <ai-area custom-clicker :input-clicker="false" v-model="selected.areaId" :hideLevel="hideLevel" :instance="instance" ref="BindArea"
             @change="handleSubmit(selected)"/>
  </section>
</template>

<script>
import {mapState} from 'vuex'
import DeviceSlider from "./components/deviceSlider";

export default {
  name: "AppMonitorManage",
  components: {DeviceSlider},
  label: "监控实况",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  computed: {
    splitOps() {
      return [
        {label: "单分屏", value: 1, per: "100%"},
        {label: "四分屏", value: 4, per: "49%"},
        {label: "九分屏", value: 9, per: "32%"}
      ]
    },
    currentSplitStyle() {
      let per = this.splitOps.find(e => e.value == this.splitScreen)?.per || "100%"
      return {width: per, height: per}
    },
    ...mapState(['user']),
    hideLevel: v => v.user.info.areaList?.length
  },

  data() {
    return {
      slider: true,
      fullscreen: false,
      splitScreen: 1,
      monitors: [],
      dialog: false,
      locate: false,
      selected: {
        areaId: ''
      },
      latlng: null,
      rules: {
        name: [{required: true, message: "请填写 设备名称"}]
      }
    }
  },

  created() {
    this.selected.areaId = this.user.info.areaId
  },

  methods: {
    handleFullscreen() {
      this.fullscreen = !this.fullscreen
      this.$fullscreen(this.fullscreen)
    },
    handleSelectMonitor(monitor) {
      let {id} = monitor,
          index = this.monitors.findIndex(e => e.id == id)
      if (index > -1) {
        this.monitors.splice(index, 1)
        this.monitors.map((e, i) => {
          if (i > index) {
            this.showMonitor(e, true)
          }
        })
      } else if (this.monitors.length >= this.splitScreen && this.splitScreen > 1) {
        this.$message.warning("可分屏监控已满,请先取消其他的监控")
      } else {
        this.showMonitor(monitor)
      }
    },
    showMonitor(monitor, refresh = false) {
      let {id: deviceId} = monitor
      deviceId && this.instance.post("/app/appzyvideoequipment/getWebSdkUrl", null, {
        params: {deviceId}
      }).then(res => {
        if (res?.data) {
          let data = JSON.parse(res.data)
          if (refresh) {
            monitor.url = data.url
          } else if (this.splitScreen == 1) {
            this.monitors = [{...monitor, ...data}]
          } else {
            this.monitors.push({...monitor, ...data})
          }
        }
      })
    },
    renderTreeItem: function (h, {node, data}) {
      let show = data.deviceStatus == 1 ? 'show' : ''
      if (node.isLeaf) {
        return (
            <div class="flexRow">
              <i class={['iconfont', 'iconshipinjiankong', show]}/>
              <div class="fill">{node.label}</div>
              <el-dropdown class="menuBtn" onCommand={e => this.handleSliderOption(e, data)}>
                <i class="iconfont iconMore"/>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit">修改名称</el-dropdown-item>
                  <el-dropdown-item command="area">行政地区</el-dropdown-item>
                  <el-dropdown-item command="locate">地图标绘</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
        )
      } else return (
          <div class="flexRow">
            <div class="fill">{node.label}</div>
            {data.id != 'no_area' ? <div class="sta">
                  <p>{data.online || 0}</p>/{data.sum || 0}
                </div>
                : <div/>}
          </div>
      )
    },
    handleSliderOption(command, data) {
      this.selected = JSON.parse(JSON.stringify({...data, command}))
      if (command == "edit") {//修改名称
        this.dialog = true
      } else if (command == "area") {//绑定areaId
        this.$refs.BindArea?.chooseArea()
      } else if (command == "locate") {//地图标绘
        this.latlng = data.lat && data.lng ? {
          lat: data.lat,
          lng: data.lng
        } : ''
        this.locate = true
      }
    },
    handleSubmit(row) {
      delete row.createTime
      return this.instance.post("/app/appzyvideoequipment/addOrUpdate", {
        ...row
      }).then(res => {
        if (res?.code == 0) {
          this.$message.success("提交成功!")
          this.dialog = false
          this.$refs.DeviceSlider?.getDevices()
        }
      })
    },
    handleLocate(row, locate) {
      if (locate) {
        let {lat, lng} = locate.location
        this.handleSubmit({...row, lat, lng}).then(() => {
          this.locate = false
        })
      }
    }
  },
  beforeDestroy() {
    this.monitors = []
  }
}
</script>

<style lang="scss" scoped>
.AppMonitorManage {
  display: flex;
  background: #202330;
  height: 100%;

  .monitorPane {
    color: #fff;
    flex: 1;
    min-width: 0;
    padding: 20px 20px 20px 4px;
    display: flex;
    flex-direction: column;

    ::v-deep .headerBar {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 8px;
      margin-bottom: 24px;

      .iconfont {
        color: #fff;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 20px;
      }

      .el-input__icon {
        color: #fff;
      }

      .el-input__inner, .el-button {
        color: #fff;
        max-width: 100px;
        background: #2C2F3E;
        border: none;

        &:hover {
          color: #26f;
        }
      }
    }

    .videoList {
      display: flex;
      justify-content: flex-start;
      align-content: flex-start;
      flex-wrap: wrap;
      flex: 1;
      min-height: 0;
      overflow: hidden;
      gap: 8px;
    }

    .videoBox {
      background: #000;
      flex-shrink: 0;

      iframe {
        width: 100%;
        height: 100%;
      }
    }
  }

  ::v-deep.el-tree-node__content:hover {
    .menuBtn {
      display: block;
    }
  }

  ::v-deep .flexRow {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: #fff;

    .iconfont {
      color: #89b;

      &.show {
        color: #19D286;
      }
    }

    .sta {
      display: flex;
      flex: 1;
      min-width: 0;

      & > p {
        color: #19D286;
      }
    }

    .menuBtn {
      display: none;
      position: absolute;
      right: 4px;
    }

  }
}
</style>
