<template>
  <div>
    <a-tag color="processing" v-model="machine_status" v-if="isOnline">
      <template #icon>
        <sync-outlined :spin="true"/>
      </template>
      在线
    </a-tag>
    <a-tag color="default" v-model="machine_status" v-else>
      <template #icon>
        <minus-circle-outlined/>
      </template>
      离线
    </a-tag>
  </div>
</template>
<script>
export default {
  name: "machine_status.vue",
  props: {
    id: String,
    type: String,
    department_id: String,
    ws: String,
    machine_status: String,
  },
  data() {
    return {
      isOnline: false
    };
  },
  created() {
    if (this.machine_status === 'online') {
      this.isOnline = true;
    }
    if (this.ws) {
      this.$nextTick(() => {
        this.loadScript('/plugin/webman/push/push.js').then(() => {
          let connection = new Push({
            url: this.ws,
            app_key: '20f94408fc4c52845f162e92a253c7a3',
            auth: '/plugin/webman/push/auth'
          });
          let type = this.type;
          let machine_id = this.id;
          let department_id = this.department_id;
          let group_channel = connection.subscribe('private-admin_group-' + type + '-' + department_id + '-' + machine_id);
          group_channel.on('message', (data) => {
            let content = JSON.parse(data.content);
            switch (content.msg_type) {
              case 'machine_now_status':
                this.isOnline = content.machine_status === 'online';
                break;
            }
          });
        });
      });
    }
  },
  methods: {
    loadScript(url) {
      return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = url;
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    }
  }
}
</script>