<template>
  <confirm-dialog
    ref="configDialog"
    title="定时重启设置"
    @confirm="onSave"
  >
    <div class="c-grid-form auto u-align-self--center">
      <span class="c-grid-form__label">启用</span>
      <div class="l-flex--row c-grid-form__option u-width--sm">
        <el-switch
          v-model="config.enable"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </div>
      <span class="c-grid-form__label u-required">时间</span>
      <el-time-picker
        v-model="config.time"
        class="has-info"
        data-info="设备会进行0~5分钟内的随机时间延长"
        placeholder="请选择重启时间"
        value-format="HH:mm:ss"
        :disabled="!config.enable"
        :clearable="false"
      />
    </div>
  </confirm-dialog>
</template>

<script>
import {
  AUTORESTART,
  getTenantAttribute,
  updateTenantAttribute
} from '../api'

export default {
  name: 'AutoRestartConfigDialog',
  data () {
    return {
      config: { enable: false }
    }
  },
  methods: {
    show () {
      getTenantAttribute(AUTORESTART).then(({ data }) => {
        if (data) {
          const time = data.attributeValue
          this.config = {
            enable: !!time,
            time: time || ''
          }
        } else {
          this.config = {
            enable: false,
            time: ''
          }
        }
        this.$temp = this.config.time
        this.$refs.configDialog.show()
      })
    },
    onSave (done) {
      const { enable, time } = this.config
      if (enable && !time) {
        this.$message({
          type: 'warning',
          message: '请选择重启时间'
        })
        return
      }
      const val = enable ? time : ''
      if (this.$temp === val) {
        done()
        return
      }
      updateTenantAttribute(AUTORESTART, val).then(done)
    }
  }
}
</script>
