<template>
  <div class="l-flex--col center has-border radius has-padding">
    <i
      class="o-icon lg u-pointer"
      @click="onInvoke"
    />
    <div class="has-padding u-color--black u-bold">开关电源(PLC)</div>
    <c-dialog
      ref="dialog"
      size="medium"
      title="开关电源"
    >
      <div 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>
    </c-dialog>
  </div>
</template>

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

export default {
  name: 'ScreenSwitchPLC',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  methods: {
    onInvoke () {
      const loading = this.$showLoading()
      getBoundPLCs(this.device.id).finally(() => {
        this.$closeLoading(loading)
      }).then(data => {
        if (data.length) {
          this.$refs.dialog.show()
        } 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_device_switch.png");
}
</style>
