<template>
  <confirm-dialog
    ref="dialog"
    title="新增PDU"
    @confirm="onConfirm"
  >
    <div class="c-grid-form u-align-self--center">
      <span class="c-grid-form__label u-required">
        厂商
      </span>
      <schema-select
        ref="manufacturer"
        v-model="item.manufacturerKey"
        class="u-width"
        placeholder="请选择厂商"
        :schema="manufacturerSelectSchema"
      />
      <span class="c-grid-form__label u-required">
        型号
      </span>
      <el-input
        v-model.trim="item.model"
        placeholder="最多50个字符"
        maxlength="50"
        clearable
      />
      <span class="c-grid-form__label u-required">
        PDU地址
      </span>
      <el-input
        v-model.trim="item.ip"
        placeholder="10.180.88.84"
        clearable
      />
      <span class="c-grid-form__label u-required">
        唯一标识
      </span>
      <el-input
        v-model.trim="item.identifier"
        placeholder="设备mac，例：18d79350592b"
        maxlength="50"
        clearable
      />
    </div>
  </confirm-dialog>
</template>

<script>
import { ThirdPartyDevice } from '@/constant'
import {
  getManufacturersByType,
  addPdu
} from '@/api/external'

export default {
  name: 'PduConfigDialog',
  data () {
    return {
      manufacturerSelectSchema: {
        remote: this.getManufacturersByType,
        value: 'manufacturerKey',
        label: 'manufacturerName'
      },
      item: {}
    }
  },
  methods: {
    show () {
      this.item = {
        identifier: '',
        manufacturerKey: '',
        model: '',
        ip: ''
      }
      this.$refs.dialog.show()
    },
    getManufacturersByType () {
      return getManufacturersByType(ThirdPartyDevice.PDU)
    },
    onConfirm (done) {
      if (!this.item.manufacturerKey) {
        this.$message({
          type: 'warning',
          message: '请选择厂商'
        })
        return
      }
      if (!this.item.model) {
        this.$message({
          type: 'warning',
          message: '请填写型号'
        })
        return
      }
      if (!this.item.identifier) {
        this.$message({
          type: 'warning',
          message: '请填写唯一标识'
        })
        return
      }
      if (!this.item.ip) {
        this.$message({
          type: 'warning',
          message: '请填写网关服务器地址'
        })
        return
      }
      const key = this.item.manufacturerKey
      addPdu({
        manufacturerName: this.$refs.manufacturer.getOptions().find(({ value }) => value === key).label,
        ...this.item
      }).then(() => {
        done()
        this.$emit('confirm', this.item)
      })
    }
  }
}
</script>

