<template>
  <box title="大屏实时画面">
    <template #title>
      <div
        class="has-active"
        @click="onSelect"
      >
        大屏实时画面
      </div>
    </template>
    <multi-device-dialog
      ref="dialog"
      :cols="cols"
      :max="4"
      sortable
      append-to-body
      @confirm="onChange"
    />
    <div
      v-if="devices.length"
      class="l-flex__auto c-record-grid"
    >
      <div
        v-for="item in devices"
        :key="item.id"
        class="c-record-wrapper"
        :class="{ fullscreen: item.id === fullscreenId} "
      >
        <i
          v-if="item.id === fullscreenId"
          class="el-icon-circle-close c-record-close has-active"
          @click="onToggleFullscreen(item)"
        />
        <device-player
          :key="item.id"
          :device="item"
          controls
          autoplay
          retry
          keep
          check-online
          @click="onClick"
          @fullscreen="onToggleFullscreen(item)"
        >
          <!-- <template #header>
            <div class="l-flex--row l-flex__fill">
              <div class="l-flex__fill u-ellipsis">
                温度: {{ item.temperature || '-' }}
              </div>
              <div class="l-flex__fill u-ellipsis u-text--right">
                亮度: {{ item.brightness || '-' }}
              </div>
            </div>
          </template> -->
        </device-player>
      </div>
    </div>
    <div
      v-else
      class="l-flex__auto l-flex--col jcenter"
    >
      <status-wrapper />
    </div>
  </box>
</template>

<script>
import { ThirdPartyDevice } from '@/constant'
import { parseTime } from '@/utils'
import { getSensorRecords } from '@/api/external'
import { getSensorMap } from './api'
import Box from './Box'

export default {
  name: 'Record',
  components: {
    Box
  },
  data () {
    return {
      fullscreenId: '',
      devices: JSON.parse(window.localStorage.getItem('MSR_DASHBOARD_DEVICES') || '[]').map(this.transformDevice)
    }
  },
  computed: {
    cols () {
      return [
        { type: 'tag', render: ({ onlineStatus }) => onlineStatus === 0
          ? { type: 'primary', label: '待接入' }
          : onlineStatus === 1
            ? { type: 'success', label: '在线' }
            : { type: 'danger', label: '离线' } }
      ]
    }
  },
  beforeDestroy () {
    clearInterval(this.$timer)
  },
  methods: {
    transformDevice ({ id, name }) {
      return { id, name }
    },
    onSelect () {
      this.$refs.dialog.show([...this.devices])
    },
    onChange ({ value, done }) {
      this.devices = value.map(this.transformDevice)
      window.localStorage.setItem('MSR_DASHBOARD_DEVICES', JSON.stringify(this.devices))
      done()
    },
    onClick ({ id }) {
      if (this.fullscreenId !== id) {
        this.fullscreenId = id
      }
    },
    onToggleFullscreen ({ id }) {
      if (this.fullscreenId === id) {
        this.fullscreenId = ''
      } else {
        this.fullscreenId = id
      }
    },
    transfromData (data) {
      const map = {}
      const arr = []
      data.forEach(sensor => {
        if (sensor.value > -1000 && !map[sensor.port]) {
          map[sensor.port] = 1
          arr.push(this.transformSensorData(sensor))
        }
      })
      return arr
    },
    transformSensorData (data) {
      const { port, type, value, time } = data
      return {
        port, value, type,
        time: parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}'),
        info: this.transformValue(type, value, data)
      }
    },
    transformValue (type, value, data) {
      switch (type) {
        case ThirdPartyDevice.SMOKE_SENSOR:
          return `${value}ppm`
        case ThirdPartyDevice.TEMPERATURE_SENSOR:
          return `${value}℃`
        case ThirdPartyDevice.LIGHT_SENSOR:
          return `${value}Lux`
        case ThirdPartyDevice.FLOODING_SENSOR:
          return value ? '是' : '否'
        case ThirdPartyDevice.TRANSLOCATION_SENSOR:
          return `x ${data.xvalue?.toFixed(3)}  y ${data.yvalue?.toFixed(
            3
          )}  z ${data.zvalue?.toFixed(3)}`
        default:
          return value
      }
    },
    // 单独接口 目前使用
    getSensorMap () {
      const devices = this.devices
      if (!devices.length) {
        return
      }
      const now = Date.now()
      for (const device of devices) {
        this.getData(device, ThirdPartyDevice.TEMPERATURE_SENSOR, 'temperature', now)
        this.getData(device, ThirdPartyDevice.LIGHT_SENSOR, 'brightness', now)
      }
    },
    getData (device, type, key, now) {
      getSensorRecords({
        deviceId: device.id,
        sensorType: type,
        startTime: now - 10000,
        endTime: now
      }).then(({ data }) => {
        if (data.length) {
          const sensor = data.find(({ value }) => value > -1000)
          this.$set(device, key, sensor ? this.transformSensorData(sensor).info : null)
        }
      })
    },
    // 批量接口 目前不用
    getSensorMapM () {
      const devices = this.devices
      if (!devices.length) { return }
      const now = Date.now()
      function getParams (item, sensorType) {
        return {
          deviceId: item.id,
          sensorType,
          startTime: now - 10000,
          endTime: now
        }
      }
      getSensorMap(
        devices
          .map(i => getParams(i, ThirdPartyDevice.TEMPERATURE_SENSOR))
          .concat(
            devices.map(i => getParams(i, ThirdPartyDevice.LIGHT_SENSOR))
          )
      ).then(({ data }) => {
        for (const deviceid in data) {
          if (Object.hasOwnProperty.call(data, deviceid)) {
            const map = this.transfromData(data[deviceid])
            for (const device of devices) {
              if (device.id === deviceid) {
                this.$set(device, 'temperature', map.filter(i => i.type === ThirdPartyDevice.TEMPERATURE_SENSOR)[0]?.info)
                this.$set(device, 'brightness', map.filter(i => i.type === ThirdPartyDevice.LIGHT_SENSOR)[0]?.info)
                break
              }
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.c-record-grid {
  display: grid;
  grid-template-rows: 1fr 1fr;
  grid-template-columns: 1fr 1fr;
  grid-row-gap: 20px;
  grid-column-gap: 20px;
}

.c-record-close {
  position: absolute;
  top: -60px;
  right: -60px;
  font-size: 64px;
}

.c-record-wrapper.fullscreen {
  position: fixed;
  width: 3072px;
  top: 50%;
  left: 50%;
  border-bottom: none;
  transform: translate(-50%, -50%);
  overflow: visible;
  z-index: 999;

  &::before {
    content: "";
    position: absolute;
    top: -216px;
    left: -384px;
    width: 3840px;
    height: 2160px;
    background-color: rgba(#000, 0.6);
    z-index: -1;
  }

  ::v-deep .c-footer {
    padding: 32px 48px;
    font-size: 64px;

    .o-quality-menu__list {
      margin-bottom: 16px;
      font-size: 48px !important;
    }

    .o-quality-menu__item {
      padding: 12px 0;
    }

    .el-icon-full-screen {
      margin-left: 48px !important;
    }
  }
}
</style>
