<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 { ThirdPartyDevice } from '@/constant'
import {
  getThirdPartyDevicesByThirdPartyDevice,
  getFollowThirdPartyDevicesByThirdPartyDevice
} from '@/api/mesh'
import { plcCommand } from '@/api/external'

export default {
  name: 'ScreenSwitchPLC',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  methods: {
    onInvoke () {
      const loading = this.$showLoading()
      getThirdPartyDevicesByThirdPartyDevice(this.device.id, [ThirdPartyDevice.GATEWAY])
        .then(({ data }) => {
          const gateway = data.find(({ instance }) => instance)
          if (!gateway) {
            this.$message({
              type: 'warning',
              message: '暂未绑定网关，请联系管理员'
            })
            return Promise.reject()
          }
          return getFollowThirdPartyDevicesByThirdPartyDevice(gateway.instance.id, [ThirdPartyDevice.PLC])
        })
        .then(({ data }) => {
          const plc = data.find(({ instance }) => instance)
          if (!plc) {
            this.$message({
              type: 'warning',
              message: '网关暂未绑定PLC，请联系管理员'
            })
            return Promise.reject()
          }
          return Promise.resolve()
        })
        .finally(() => {
          this.$closeLoading(loading)
        })
        .then(() => {
          this.$refs.dialog.show()
        })
    },
    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>
