<template>
  <div class="c-info">
    <template v-if="info">
      <div class="l-flex--row c-info__block">
        <div class="l-flex--row l-flex__fill c-info__item">
          <div class="l-flex__none c-info__title">厂家名称</div>
          <el-select
            v-model="defaults.manufacturerKey"
            class="l-flex__fill c-info__value"
            placeholder="请选择厂家"
            :loading="manufacturers.loading"
            @visible-change="getReceivingCardManufacturers"
            @change="onChangeProp('manufacturerKey')"
          >
            <el-option
              v-for="manufacturer in manufacturers.list"
              :key="manufacturer.value"
              :label="manufacturer.label"
              :value="manufacturer.value"
            />
          </el-select>
        </div>
        <div class="l-flex--row l-flex__fill c-info__item">
          <div class="l-flex__none c-info__title">拓扑结构文件</div>
          <el-upload
            ref="upload"
            class="l-flex__fill o-upload"
            action="none"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="onChangeTopology"
            drag
          >
            <div class="u-color--black">
              {{ defaults.topology }}
            </div>
          </el-upload>
        </div>
      </div>
      <div class="l-flex--row c-info__block">
        <div class="l-flex--row l-flex__fill c-info__item">
          <div class="l-flex__none c-info__title">设备型号</div>
          <edit-input
            v-model.trim="defaults.screen"
            class="l-flex__fill c-info__value"
            @edit="onChangeProp('screen')"
          />
        </div>
        <div class="l-flex--row l-flex__fill c-info__item">
          <div class="l-flex__none c-info__title">异步盒</div>
          <div class="l-flex__fill">
            <el-switch
              v-model="defaults.async"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeProp('async')"
            />
          </div>
        </div>
      </div>
      <div class="l-flex--row c-info__block">
        <div class="l-flex--row l-flex__fill c-info__item">
          <div class="l-flex__none c-info__title">支持温度监测</div>
          <div class="l-flex__fill">
            <el-switch
              v-model="defaults.temperature"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeProp('temperature')"
            />
          </div>
        </div>
        <div class="l-flex--row l-flex__fill c-info__item">
          <div class="l-flex__none c-info__title">支持电压监测</div>
          <div class="l-flex__fill">
            <el-switch
              v-model="defaults.voltage"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeProp('voltage')"
            />
          </div>
        </div>
      </div>
      <div class="l-flex--row c-info__block">
        <div class="l-flex--row l-flex__fill c-info__item">
          <div class="l-flex__none c-info__title">设备IP</div>
          <edit-input
            v-model.trim="defaults.ip"
            class="l-flex__fill c-info__value"
            @edit="onChangeProp('ip')"
          />
        </div>
        <div class="l-flex__fill c-info__item" />
      </div>
    </template>
    <template v-else>
      <button
        class="o-button"
        @click="onAdd"
      >
        <i class="o-button__icon el-icon-circle-plus-outline" />
        新增接收卡
      </button>
      <confirm-dialog
        ref="addDialog"
        title="新增"
        @confirm="onSave"
      >
        <el-upload
          ref="upload"
          class="o-upload has-bottom-padding"
          action="none"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onChange"
          drag
        >
          <div class="l-flex--row">
            <template v-if="receivingCard.topologyFile">
              <div class="o-upload__file">{{ receivingCard.topologyFile.name }}</div>
            </template>
            <template v-else>
              添加拓扑结构文件将文件拖动到本窗口上传或
              <span class="o-upload__tip">点击选择文件</span>
            </template>
          </div>
        </el-upload>
        <div class="c-grid-form u-align-self--center">
          <span class="c-grid-form__label required">厂家：</span>
          <el-select
            v-model="receivingCard.manufacturerKey"
            placeholder="请选择厂家"
            :loading="manufacturers.loading"
            @visible-change="getReceivingCardManufacturers"
          >
            <el-option
              v-for="manufacturer in manufacturers.list"
              :key="manufacturer.value"
              :label="manufacturer.label"
              :value="manufacturer.value"
            />
          </el-select>
          <span class="c-grid-form__label required">设备型号：</span>
          <el-input
            v-model.trim="receivingCard.screen"
            placeholder="最多50个字符"
            maxlength="50"
            clearable
          />
          <span class="c-grid-form__label">异步盒：</span>
          <div class="l-flex--row c-grid-form__option">
            <el-switch
              v-model="receivingCard.async"
              class="c-sibling-item"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span class="c-sibling-item far">支持温度监测：</span>
            <el-switch
              v-model="receivingCard.temperature"
              class="c-sibling-item"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span class="c-sibling-item far">支持电压监测：</span>
            <el-switch
              v-model="receivingCard.voltage"
              class="c-sibling-item"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </div>
          <span class="c-grid-form__label required">设备IP：</span>
          <el-input
            v-model.trim="receivingCard.ip"
            placeholder="192.168.0.1"
            maxlength="15"
            clearable
          />
        </div>
      </confirm-dialog>
    </template>
    <el-dialog
      class="c-progress"
      :visible.sync="showProgress"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-progress
        :percentage="progress"
        :stroke-width="24"
        text-inside
        status="success"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getReceivingCardManufacturers,
  addReceivingCard,
  updateReceivingCard
} from '@/api/external'
import { validIPv4 } from '@/utils/validate'

export default {
  name: 'ReceivingCardInfoEdit',
  props: {
    info: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      show: false,
      receivingCard: {},
      showProgress: false,
      progress: 0,
      manufacturers: {
        loading: false,
        loaded: false,
        list: []
      },
      defaults: null
    }
  },
  watch: {
    info: {
      handler () {
        this.getDefaults()
      },
      immediate: true
    }
  },
  methods: {
    getDefaults () {
      if (this.info) {
        this.defaults = {
          manufacturerKey: this.info.manufacturerKey,
          screen: this.info.screen,
          async: this.info.async,
          temperature: this.info.temperature,
          voltage: this.info.voltage,
          topology: this.info.topology ? '已上传' : '未上传',
          ip: this.info.ip
        }
        if (!this.manufacturers.loaded) {
          this.manufacturers.list = [{ value: this.info.manufacturerKey, label: this.info.manufacturerName }]
        }
      }
    },
    getReceivingCardManufacturers (visible) {
      if (visible && !this.manufacturers.loading && !this.manufacturers.loaded) {
        this.manufacturers.loading = true
        getReceivingCardManufacturers().then(({ data }) => {
          this.manufacturers.list = data.map(({ manufacturerKey, manufacturerName }) => {
            return { value: manufacturerKey, label: manufacturerName }
          })
          this.manufacturers.loading = false
          this.manufacturers.loaded = true
        }, () => {
          this.manufacturers.loading = false
        })
      }
    },
    onAdd () {
      this.receivingCard = {
        manufacturerKey: '',
        topologyFile: null,
        screen: '',
        async: false,
        temperature: false,
        voltage: false,
        ip: ''
      }
      this.$refs.addDialog.show()
    },
    onSave (done) {
      if (!this.receivingCard.topologyFile) {
        this.$message({
          type: 'warning',
          message: '请选择拓扑结构文件'
        })
        return
      }
      if (!this.receivingCard.manufacturerKey) {
        this.$message({
          type: 'warning',
          message: '请选择厂家'
        })
        return
      }
      if (!this.receivingCard.screen) {
        this.$message({
          type: 'warning',
          message: '请填写设备型号'
        })
        return
      }
      if (!this.receivingCard.ip) {
        this.$message({
          type: 'warning',
          message: '请填写设备IP'
        })
        return
      }
      if (!validIPv4(this.receivingCard.ip)) {
        this.$message({
          type: 'warning',
          message: '设备IP格式错误'
        })
        return
      }
      const formData = new FormData()
      formData.append('deviceId', this.$route.params.id)
      formData.append('manufacturerKey', this.receivingCard.manufacturerKey)
      formData.append('topologyFile', this.receivingCard.topologyFile)
      formData.append('screen', this.receivingCard.screen)
      formData.append('temperature', this.receivingCard.temperature)
      formData.append('voltage', this.receivingCard.voltage)
      formData.append('async', this.receivingCard.async)
      formData.append('ip', this.receivingCard.ip)
      this.progress = 0
      this.showProgress = true
      addReceivingCard(formData, ({ loaded, total }) => {
        this.progress = Math.min(99, loaded * 100 / total | 0)
      }).finally(() => {
        this.progress = 100
        this.showProgress = false
      }).then(() => {
        done()
        this.emitChange('all')
      })
    },
    onChange ({ raw }) {
      this.$refs.upload.clearFiles()
      this.receivingCard.topologyFile = raw
    },
    onChangeTopology ({ raw }) {
      this.$refs.upload.clearFiles()
      this.progress = 0
      this.showProgress = true
      this.updateProp('topologyFile', raw, ({ loaded, total }) => {
        this.progress = Math.min(99, loaded * 100 / total | 0)
      }).finally(() => {
        this.progress = 100
        this.showProgress = false
      })
    },
    checkProp (key) {
      const val = this.defaults[key]
      switch (key) {
        case 'type':
          if (!val) {
            this.$message({
              type: 'warning',
              message: '请填写设备型号'
            })
            return false
          }
          break
        case 'ip':
          if (!val) {
            this.$message({
              type: 'warning',
              message: '请填写设备IP'
            })
            return false
          }
          if (!validIPv4(val)) {
            this.$message({
              type: 'warning',
              message: '设备IP格式错误'
            })
            return false
          }
          break
        default:
          break
      }
      return true
    },
    onChangeProp (key) {
      if (this.defaults[key] === this.info[key]) {
        return
      }
      if (!this.checkProp(key)) {
        this.defaults[key] = this.info[key]
        return
      }
      this.updateProp(key, this.defaults[key]).catch(() => {
        this.defaults[key] = this.info[key]
      })
    },
    updateProp (key, data, options) {
      const formData = new FormData()
      formData.append('deviceId', this.$route.params.id)
      formData.append(key, data)
      return updateReceivingCard(formData, options).then(() => {
        this.emitChange(key)
      })
    },
    emitChange (key) {
      console.log('receiving card', key, 'changed')
      this.$emit('change')
    }
  }
}
</script>
