<template>
  <el-button :size="size" :type="type" :round="round" @click="switchStatus"
  >
    {{ label }}
  </el-button>
</template>

<style scoped lang="scss">

</style>
<script>
import {updateDeviceStatus} from "@/api/ems/site";

export default {
  props: {
    size: {
      type: String,
      default: 'mini',
      required: false
    },
    round: {
      type: Boolean,
      default: false,
      required: false
    },
    type: {
      type: String,
      default: 'primary',
      required: false
    },
    data: {
      type: Object,
      default: () => {
        return {
          workStatus: null,
          deviceId: null,
          deviceName: null,
        }
      },
      required: true
    }
  },
  data() {
    return {
      runningStatusMap: ['0', '3', '4', '6']
    }
  },
  computed: {
    label() {
      return this.runningStatusMap.includes(this.data.workStatus) ? '关机' : '开机'
    }
  },
  methods: {
    switchStatus() {
      const {workStatus, deviceId, deviceName, siteId} = this.data
      this.$confirm(`确认要${this.label}设备${deviceName || ''}吗?`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        closeOnClickModal: false,
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            //做开关机操作,更新成功后刷新表格
            updateDeviceStatus({
              siteId,
              workStatus: this.runningStatusMap.includes(workStatus) ? "1" : '0',
              deviceId
            })
                .then((response) => {
                  response.code === 200 && done();
                })
                .finally(() => {
                  instance.confirmButtonLoading = false;
                });
          } else {
            done();
          }
        },
      })
          .then(() => {
            //只有在废弃成功的情况下会走到这里
            this.$message({
              type: "success",
              message: `${deviceName}${this.label}成功!`,
            });
            this.$emit('updateSuccess')
            //调用接口 更新表格数据
          })
          .catch(() => {
            //取消关机
          });
    }
  }
}

</script>
