<template>
  <div class="l-flex--col center has-border radius has-padding">
    <i
      class="o-icon has-bg u-pointer"
      @click="onInvoke"
    />
    <div class="has-padding u-color--black u-bold">开关大屏</div>
    <el-dialog
      :visible.sync="show"
      custom-class="c-dialog"
      title="开关大屏"
    >
      <div
        v-if="show"
        class="l-flex__fill l-flex--col jcenter center has-bottom-padding"
      >
        <div>
          <button
            class="o-button c-sibling-item"
            @click="onSwitch(true)"
          >
            即刻开机
          </button>
          <button
            class="o-button c-sibling-item far"
            @click="onSwitch(false)"
          >
            即刻关机
          </button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBoundPLCs,
  plcCommand
} from '@/api/external'

export default {
  name: 'ScreenSwitch',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      show: false
    }
  },
  methods: {
    onInvoke () {
      const loading = this.$showLoading()
      getBoundPLCs(this.device.id).finally(() => {
        this.$closeLoading(loading)
      }).then(data => {
        if (data.length) {
          this.show = true
        } else {
          this.$message({
            type: 'warning',
            message: '暂未绑定PLC，请联系管理员'
          })
        }
      })
    },
    onSwitch (open) {
      this.$confirm(
        `立即${open ? '开机' : '关机'}？`,
        { type: 'warning' }
      ).then(() => {
        plcCommand(this.device.id, open ? 1 : 0)
      })
    }
  }
}
</script>

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