<template>
  <section class="AppISManage">
    <device-slider :permissions="permissions" :show.sync="slider" :ins="instance" :dict="dict"
                   @treeCommand="handleSliderOption" @select="handleSelectMonitor"
                   :render-item="renderTreeItem" ref="DeviceSlider"/>
    <div class="monitorPane" v-loading="isLoading" element-loading-background="rgba(0, 0, 0, 0.6)">
      <div class="headerBar">
        <el-select default-first-option size="small" v-model="splitScreen" @change="onChange">
          <!-- <i slot="prefix" class="iconfont iconjdq_led_Led1"/> -->
          <img slot="prefix" src="https://cdn.cunwuyun.cn/slw2.0/images/fp.png">
          <el-option v-for="(op,i) in splitOps" :key="i" v-bind="op"/>
        </el-select>
        <div class="headerBar-item" v-if="monitors.length > 1" @click="isShowBar = !isShowBar" :class="[isShowBar ? '' : 'cancel-xt']">
          <img src="https://cdn.cunwuyun.cn/slw2.0/images/xt.png">
          <span>{{ isShowBar ? '视频协同' : '取消协同' }}</span>
        </div>
      </div>
      <div class="videoList">
        <div
          class="videoBox"
          v-for="(m, i) in monitors"
          :key="m.id"
          :style="currentSplitStyle">
          <AiMonitor
            :instance="instance"
            :deviceId="m.deviceId"
            :isShowBar="isShowBar"
            :id="m.id"
            :playbackUrls="playbackUrls"
            :name="m.name"
            @close="removeMonitor(i)"
            ref="AiMonitor">
          </AiMonitor>
        </div>
      </div>
      <Synergy
        ref="Synergy"
        :ids="ids"
        :instance="instance"
        @replay="onReplay"
        :isLoading.sync="isLoading"
        @backLiveing="playbackUrls = []"
        @checkChange="onCheckChange"
        v-if="!isShowBar && monitors.length"
        style="width: 100%; height: 68px;">
      </Synergy>
    </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>
    <locate-dialog v-model="locate" :ins="instance" :latlng="latlng" @confirm="v=>handleLocate(selected,v)"/>
    <ai-area custom-clicker :input-clicker="false" :hideLevel="disabledLevel" v-model="selected.areaId"
             :instance="instance" ref="BindArea"
             @change="handleSubmit(selected)"/>
  </section>
</template>

<script>
  import {mapState} from 'vuex'
  import DeviceSlider from "../components/deviceSlider"
  import LocateDialog from "../components/locateDialog"
  import AiMonitor from "../components/AiSlwVideo"
  import Synergy from "../components/Synergy"

  export default {
    name: "AppISManage",
    components: {LocateDialog, DeviceSlider, AiMonitor, Synergy},
    label: "监控实况",
    props: {
      instance: Function,
      dict: Object,
      permissions: Function
    },
    computed: {
      splitOps() {
        return [
          {label: "单分屏", value: 1, per: "100%"},
          {label: "四分屏", value: 4, per: "49.2%"},
          {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']),

      ids () {
        if (!this.monitors.length) return ''

        return this.monitors.map(v => v.id).join(',')
      }
    },

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

    watch: {
      slider () {
        this.$refs.AiMonitor && this.$refs.AiMonitor.forEach(e => {
          e.reset()
        })

        this.$refs.Synergy && this.$refs.Synergy.init()
      }
    },

    created() {
      this.selected.areaId = this.user.info.areaId
      this.disabledLevel = this.user.info.areaList.length - 1
    },

    methods: {
      handleFullscreen() {
        this.fullscreen = !this.fullscreen
        this.$fullscreen(this.fullscreen)
      },
      handleSelectMonitor(monitor) {
        if (monitor.type !== '1') return

        let {id} = monitor,
            index = this.monitors.findIndex(e => e.id == id)
        if (index > -1) {
          this.$message.error('该监控视频已存在')
        } else if (this.monitors.length >= this.splitScreen && this.splitScreen > 1) {
          this.$message.error("可分屏监控已满,请先取消其他的监控")
        } else {
          this.showMonitor(monitor)
        }
      },

      onCheckChange (e) {
        this.monitors.forEach((item, index) => {
          if (e.indexOf(item.index) === -1) {
            this.monitors.splice(index, 1)
          }
        })
      },

      onChange(e) {
        if (e === 1 && this.monitors.length) {
          this.monitors = [this.monitors[0]]
        }

        this.$refs.AiMonitor && this.$refs.AiMonitor.forEach(e => {
          e.reset()
        })
      },

      onReplay (e) {
        this.isLoading = true
        this.instance.post(`/app/appzyvideoequipment/getSlwPlaybackUrl`, null, {
          params: {
            ids: this.ids,
            startTime: e.startTime,
            endTime: e.endTime,
            nvrCodes: this.ids
          }
        }).then(res => {
          if (res.code == 0) {
            if (res.data && res.data.length) {
              this.playbackUrls = res.data
              this.isLoading = false
            }
          }
        }).catch(() => {
          this.isLoading = false
        })
      },

      removeMonitor(i) {
        this.monitors.splice(i, 1)
      },

      showMonitor(monitor, refresh = false) {
        let {id: deviceId} = monitor
        deviceId && this.instance.post("/app/appzyvideoequipment/getWebSdkUrl", null, {
          params: {deviceId}
        }).then(res => {
          if (res?.data) {
            this.videoUrl = res.data
            let data = {
              url: res.data,
              isShowPlayBtn: false
            }
            if (refresh) {
              monitor.url = data.url
            } else if (this.splitScreen == 1) {
              this.monitors = [{...monitor, ...data}]
            } else {
              if (this.monitors.findIndex(e => e.id == monitor.id) === -1 && this.monitors.length <= this.splitScreen) {
                this.monitors.push({...monitor, ...data})
              }
            }
          }
        })
      },
      renderTreeItem: function (h, {node, data}) {
        let show = data.deviceStatus == 1 ? 'show' : ''
        const ids = this.ids.split(',')
        const index = ids.indexOf(data.id) + 1
        if (node.isLeaf) {
          return (
              <div class="flexRow">
                {index > 0 ? 
                <span>{ index }</span>
                : ''
                }
                <i class={['iconfont', 'iconshipinjiankong', show]}/>
                <div>{node.label}</div>
              </div>
          )
        } else return (
            <div class="flexRow">
              <div>{node.label}</div>
              {data.id != 'no_area' ? <div class="sta">
                    <p>{data.online || 0}</p>/{data.sum || 0}
                  </div>
                  : <div/>}
            </div>
        )
      },
      handleSliderOption(e) {
        this.selected = {
          command: e.type,
          ...e.node
        }
        this.selected.areaId = e.node.areaId || this.user.info.areaId
        if (e.type == "edit") {//修改名称
          this.dialog = true
        } else if (e.type == "area") {//绑定areaId
          this.$refs.BindArea?.chooseArea()
        } else if (e.type == "locate") {//地图标绘
          this.latlng = e.node.lat && e.node.lng ? {
            lat: e.node.lat,
            lng: e.node.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>
.AppISManage {
  display: flex;
  background: #202330;
  height: 100%;

  .monitorPane {
    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;

      .headerBar-item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100px;
        height: 40px;
        background: #2C2F3E;
        border-radius: 4px;
        color: #fff;
        font-size: 12px;
        cursor: pointer;

        &.cancel-xt {
          background: linear-gradient(90deg, #299FFF 0%, #0C61FF 100%);
        }

        &:hover {
          opacity: 0.7;
        }

        span {
          margin-left: 6px;
        }
      }

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

      .el-input__icon {
        color: #fff;
      }

      .el-input--prefix .el-input__inner {
        padding-left: 16px;
      }

      .el-input--suffix .el-input__inner {
        padding-right: 16px;
      }

      .el-input__prefix {
        top: 50%;
        left: 10px;
        height: auto;
        transform: translateY(-50%);
      }

      .el-input {
        display: flex;
        align-items: center;
        font-size: 12px;
        width: 100px;
        height: 40px;
        padding: 0 12px;
        box-sizing: border-box;
        background: #2C2F3E;
      }

      input {
        text-align: center;
      }

      .el-input__inner, .el-button {
        color: #fff;
        border: none;
        background: transparent;

        &: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 {
      position: relative;
      background: #000;
      flex-shrink: 0;

      & > span {
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 11;
        width: 60%;
        height: 38px;
        line-height: 38px;
        padding: 0 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #fff;
        font-size: 16px;
      }

      .videoBox-close {
        display: flex;
        position: absolute;
        align-items: center;
        justify-content: center;
        right: 8px;
        top: 8px;
        z-index: 11;
        width: 84px;
        height: 32px;
        line-height: 1;
        background: linear-gradient(180deg, #2E3447 0%, #151825 100%);
        border-radius: 2px;
        cursor: pointer;
        font-size: 12px;
        color: #fff;

        &:hover {
          opacity: 0.8;
        }

        span {
          margin-left: 4px;
        }

        i {
          position: relative;
          font-size: 16px;
        }
      }

      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;

    span {
      width: 16px;
      height: 16px;
      line-height: 16px;
      text-align: center;
      color: #fff;
      font-size: 12px;
      border-radius: 1px;
      background: #2266FF;
    }

    .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>
