<template>
  <div class="l-flex--col c-device-grid-item o-sensor has-border radius">
    <div class="l-flex--row l-flex__none">
      <i
        class="l-flex__none c-sibling-item o-icon"
        :class="sensorType"
      />
      <span class="l-flex__fill c-sibling-item near u-color--info u-ellipsis">{{ title }}</span>
      <i
        v-if="enough"
        class="l-flex__none c-sibling-item u-font-size--md u-color--blue el-icon-s-operation has-active"
        @click="onShowAll"
      />
    </div>
    <div class="l-flex__fill l-flex--row center u-font-size--md u-color--black u-bold">
      <div
        class="u-text--center"
        :style="{ color }"
      >
        <template v-if="sensor">
          {{ tip }}
          <div class="o-sensor__current">
            {{ sensor }}
          </div>
        </template>
        <i
          v-else-if="loading"
          class="el-icon-loading"
        />
        <template v-else>
          未知
        </template>
      </div>
    </div>
    <div
      v-for="item in more"
      :key="item.port"
      class="l-flex__none l-flex--row o-sensor__more"
    >
      <div class="l-flex__none">{{ item.time }}</div>
      <div class="l-flex__none o-sensor__name">传感器{{ item.port }}</div>
      <div class="l-flex__fill u-text--right">{{ item.info }}</div>
    </div>
    <table-dialog
      ref="tableDialog"
      :title="listTitle"
      :schema="schema"
    />
  </div>
</template>

<script>
import {
  ThirdPartyDevice,
  ThirdPartyDeviceInfo
} from '@/constant'
import { parseTime } from '@/utils'
import { getSensorRecords } from '@/api/external'

export default {
  name: 'Sensor',
  props: {
    type: {
      type: Number,
      required: true
    },
    title: {
      type: String,
      default: ''
    },
    color: {
      type: String,
      default: ''
    },
    deviceId: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      list: [],
      schema: {
        nonPagination: true,
        list: this.getSensors,
        cols: [
          { prop: 'port', label: '端口' },
          { prop: 'info', label: '数据' },
          { prop: 'time', label: '采集时间' }
        ]
      }
    }
  },
  computed: {
    listTitle () {
      return ThirdPartyDeviceInfo[this.type]
    },
    sorted () {
      if (this.type === ThirdPartyDevice.TRANSLOCATION_SENSOR) {
        return this.list
      }
      return this.list.slice().sort((a, b) => Number(a.value) < Number(b.value) ? 1 : -1)
    },
    sensorType () {
      return `sensor_${this.type}`
    },
    tip () {
      return this.sorted.length ? this.sorted[0].info : null
    },
    sensor () {
      const length = this.sorted.length
      return length
        ? length === 1
          ? this.sorted[0].time
          : `${this.sorted[0].time} 传感器${this.sorted[0].port}`
        : null
    },
    more () {
      return this.list.length > 1 ? this.sorted.slice(1, 3) : []
    },
    enough () {
      return this.list.length > 3
    }
  },
  created () {
    this.$running = true
    this.$timer = -1
    this.startRun()
  },
  beforeDestroy () {
    this.$running = false
    clearTimeout(this.$timer)
  },
  methods: {
    startRun () {
      if (!this.$running) {
        return
      }
      const now = Date.now()
      this.loading = true
      getSensorRecords({
        deviceId: this.deviceId,
        sensorType: this.type,
        startTime: now - 10000,
        endTime: now
      }, { custom: true }).then(({ data }) => {
        this.list = this.transfromData(data)
        this.$refs.tableDialog?.getTable()?.pageTo()
      }).finally(() => {
        this.loading = false
        if (this.$running) {
          this.$timer = setTimeout(this.startRun, 10000)
        }
      })
    },
    transfromData (data) {
      const map = {}
      const arr = []
      data.forEach(sensor => {
        if (!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,
        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:
          console.log(data)
          return `x ${data.xvalue?.toFixed(3)}  y ${data.yvalue?.toFixed(3)}  z ${data.zvalue?.toFixed(3)}`
        default:
          return value
      }
    },
    getSensors () {
      return Promise.resolve({ data: this.list })
    },
    onShowAll () {
      this.$refs.tableDialog.show()
    }
  }
}
</script>

<style lang="scss" scoped>
.o-icon {
  &.sensor_9 {
    background-image: url("~@/assets/icon_smoke.png");
  }

  &.sensor_10 {
    background-image: url("~@/assets/icon_temperature.png");
  }

  &.sensor_11 {
    background-image: url("~@/assets/icon_light.png");
  }

  &.sensor_12 {
    background-image: url("~@/assets/icon_flooding.png");
  }

  &.sensor_13 {
    background-image: url("~@/assets/icon_shift.png");
  }
}

.o-sensor {
  &__current {
    margin-top: 6px;
    color: $info;
    font-size: 12px;
  }

  &__more {
    padding: 8px 0;
    color: $info--dark;
    font-size: 14px;
    border-bottom: 1px solid $border;
  }

  &__name {
    margin: 0 16px 0 24px;
  }
}
</style>
