<template>
  <div class="l-flex--col o-device-grid-item has-border radius">
    <div class="l-flex__none l-flex--row">
      <i class="l-flex__none o-device-grid-item__icon o-icon medium has-bg" />
      <span class="l-flex__fill u-color--info u-ellipsis">状态</span>
      <template v-if="online">
        <i
          v-if="asking"
          class="l-flex__none el-icon-loading u-color--black"
        />
        <i
          v-else
          class="l-flex__none o-icon mini has-bg u-pointer"
          @click="invoke"
        />
      </template>
    </div>
    <div
      v-if="!asking"
      class="l-flex__fill l-flex--row center o-device-grid-item__large has-bottom-padding u-color--black u-bold"
    >
      {{ online ? status : '离线' }}
    </div>
  </div>
</template>

<script>
import {
  addListener,
  removeListener,
  send
} from '../../monitor'

export default {
  name: 'DeviceRunning',
  props: {
    online: {
      type: [Boolean, String],
      default: false
    }
  },
  data () {
    return {
      asking: false,
      status: ''
    }
  },
  created () {
    addListener('status', this.onUpdate)
    if (this.online && !this.asking) {
      this.ask()
    }
  },
  beforeDestroy () {
    removeListener('status', this.onUpdate)
  },
  methods: {
    onUpdate (status, { loading }) {
      this.asking = loading
      switch (status) {
        case 1:
          this.status = '未播放节目，处于默认状态'
          break
        case 2:
          this.status = '正在播放节目'
          break
        case 3:
          this.status = '解析节目异常，请重新发布'
          break
        case -1:
          this.status = '解析异常，请重试'
          break
        default:
          this.status = '未知'
          break
      }
    },
    ask () {
      return send('/status/ask')
    },
    invoke () {
      this.ask().catch(() => {
        this.$message({
          type: 'warning',
          message: '正在连接，请稍后再试'
        })
      })
    }
  }
}
</script>

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

  &.o-device-grid-item__icon {
    background-image: url("~@/assets/icon_condition.png");
  }
}
</style>
