<template>
  <div
    v-loading="loading"
    class="l-flex--col"
  >
    <template v-if="!loading">
      <warning
        v-if="error"
        @click="getShadow"
      />
      <template v-else>
        <pre
          class="l-flex__self c-sibling-item--v u-overflow-y--auto"
          style="white-space: break-spaces;"
        ><code>{{ code }}</code></pre>
        <div class="l-flex__none c-sibling-item--v far">
          <button
            class="o-button"
            @click="onSync"
          >
            立刻同步
          </button>
        </div>
      </template>
    </template>
  </div>
</template>

<script>
import { getShadow } from '@/api/device'
import { publish } from '@/utils/mqtt'

export default {
  name: 'DeviceShadow',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      loading: true,
      error: false,
      code: ''
    }
  },
  created () {
    this.getShadow()
  },
  methods: {
    getShadow () {
      this.loading = true
      this.error = false
      getShadow(this.device.id).then(
        ({ data }) => {
          this.code = JSON.stringify(data, null, 2)
        },
        () => {
          this.error = true
        }
      ).finally(() => {
        this.loading = false
      })
    },
    onSync () {
      publish(
        `${this.device.productId}/${this.device.id}/function/invoke`,
        JSON.stringify({
          timestamp: Date.now(),
          'function': 'updateConfig',
          inputs: [
            { name: 'reboot', value: 1 }
          ]
        }),
        true
      ).then(
        () => {
          this.$message({
            type: 'success',
            message: '执行成功'
          })
        },
        () => {
          this.$message({
            type: 'warning',
            message: '正在连接，请稍后再试'
          })
        }
      )
    }
  }
}
</script>
