<template>
  <confirm-dialog
    ref="configDialog"
    title="属性配置"
    @confirm="onSave"
  >
    <div class="c-grid-form medium u-align-self--center">
      <span class="c-grid-form__label">回采卡拉流地址</span>
      <el-input
        v-model.trim="attributes.recoveryCardIP"
        class="c-grid-form__option"
        placeholder="rtsp://192.168.0.11:8554"
        clearable
      />
    </div>
  </confirm-dialog>
</template>

<script>
import { validIPv4Address } from '@/utils/validate'
import {
  getAttributes,
  updateAttributes
} from '../api'

const attributeSet = [
  { key: 'recoveryCardIP', valid (val) {
    if (val && !validIPv4Address(val)) {
      return '回采卡拉流地址格式错误'
    }
    return null
  } }
]

export default {
  name: 'AttibuteConfigDialog',
  data () {
    return {
      attributes: {}
    }
  },
  methods: {
    show ({ id }) {
      const loading = this.$showLoading()
      this.$deviceId = id
      getAttributes(id).then(({ data }) => {
        const attributes = {}
        attributeSet.forEach(({ key }) => {
          attributes[key] = data[key] || ''
          attributes[`_${key}`] = attributes[key]
        })
        this.attributes = attributes
        this.$refs.configDialog.show()
      }).finally(() => {
        this.$closeLoading(loading)
      })
    },
    onSave (done) {
      const attributes = this.attributes
      const attributeMap = {}
      let needUpdate = false
      for (let i = 0; i < attributeSet.length; i++) {
        const { key, valid } = attributeSet[i]
        const value = attributes[key]
        if (value === attributes[`_${key}`]) {
          continue
        }
        const message = valid(value)
        if (message) {
          this.$message({
            type: 'warning',
            message
          })
          return
        }
        attributeMap[key] = value
        needUpdate = true
      }
      if (!needUpdate) {
        done()
        return
      }
      updateAttributes(this.$deviceId, attributeMap).then(done)
    }
  }
}
</script>
