<script>
import { ThirdPartyDevice } from '@/constant'
import { parseTime } from '@/utils'
import {
  addListener,
  removeListener
} from '@/utils/adapter'
import {
  Power,
  Status
} from '@/utils/adapter/nova'

export default {
  name: 'DevicePower',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      colorClass: ''
    }
  },
  computed: {
    online () {
      return this.device.onlineStatus === 1
    }
  },
  watch: {
    online (val) {
      if (val) {
        addListener(this.device.id, this.onMessage)
      } else {
        removeListener(this.device.id, this.onMessage)
      }
    }
  },
  mounted () {
    if (this.online) {
      addListener(this.device.id, this.onMessage)
    }
  },
  beforeDestroy () {
    if (this.online) {
      removeListener(this.device.id, this.onMessage)
    }
  },
  methods: {
    onMessage (value) {
      const multiCard = value[ThirdPartyDevice.MULTI_FUNCTION_CARD]
      this.device.power = multiCard.status
      if (multiCard.status === Status.OK) {
        this.device.timestamp = parseTime(multiCard.timestamp, '{y}-{m}-{d} {h}:{i}:{s}')
        switch (multiCard.realSwitchStatus) {
          case Power.ON:
            this.colorClass = 'u-color--success'
            break
          case Power.OFF:
            this.colorClass = 'u-color--error dark'
            break
          default:
            this.colorClass = 'u-color--warning'
            break
        }
      }
    }
  },
  render (h) {
    if (!this.online || this.device.power === Status.NONE) {
      return h('i', null, '-')
    }
    if (this.device.power === Status.LOADING) {
      return h('i', {
        staticClass: 'el-icon-loading'
      })
    }
    return h('i', {
      staticClass: `o-status ${this.colorClass}`
    })
  }
}
</script>
