<template>
  <div class="c-info large">
    <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.manufacturerId"
            class="l-flex__fill c-info__value"
            placeholder="请选择厂家"
            :loading="manufacturers.loading"
            @visible-change="getReceivingCardManufacturers"
            @change="onChangeProp('manufacturerId')"
          >
            <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"
            align="left"
            @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.temperature"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeProp('temperature')"
            />
          </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.voltage"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeProp('voltage')"
            />
          </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.async"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeProp('async')"
            />
          </div>
        </div>
      </div>
    </template>
    <template v-else>

      <button
        class="o-button"
        @click="onAdd"
      >
        <i class="o-button__icon el-icon-circle-plus-outline" />
        新增
      </button>
      <el-dialog
        title="新增"
        :visible.sync="show"
        custom-class="c-dialog"
        :close-on-click-modal="false"
      >
        <el-upload
          ref="upload"
          class="o-upload"
          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-form">
          <div class="c-form__section">
            <span class="c-form__label large required">厂家：</span>
            <el-select
              v-model="receivingCard.manufacturerId"
              class="c-form__item"
              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>
          </div>
          <div class="c-form__section">
            <span class="c-form__label large">型号：</span>
            <el-input
              v-model.trim="receivingCard.screen"
              class="c-form__item"
              maxlength="50"
              show-word-limit
            />
          </div>
          <div class="c-form__section">
            <span class="c-form__label large">是否为异步盒：</span>
            <el-switch
              v-model="receivingCard.async"
              class="c-form__item"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </div>
          <div class="c-form__section">
            <span class="c-form__label large">是否支持卡温度监测：：</span>
            <el-switch
              v-model="receivingCard.temperature"
              class="c-form__item"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </div>
          <div class="c-form__section">
            <span class="c-form__label large">是否支持卡电压监测：：</span>
            <el-switch
              v-model="receivingCard.voltage"
              class="c-form__item"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </div>
        </div>
        <template #footer>
          <button
            class="o-button"
            @click="save"
          >
            确定
          </button>
          <button
            class="o-button cancel"
            @click="close"
          >
            取消
          </button>
        </template>
      </el-dialog>
      <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>
    </template>
  </div>
</template>

<script>
import {
  getReceivingCardManufacturers,
  addReceivingCard,
  updateReceivingCard
} from '@/api/device'

export default {
  name: 'DeviceReceivingCardInfoEdit',
  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 = {
          manufacturerId: this.info.manufacturerId,
          screen: this.info.screen,
          temperature: this.info.temperature,
          voltage: this.info.voltage,
          async: this.info.async,
          topology: this.info.topology?.version ?? '未上传'
        }
        if (!this.manufacturers.loaded) {
          this.manufacturers.list = [{ value: this.info.manufacturerId, label: this.info.manufacturer }]
        }
      }
    },
    getReceivingCardManufacturers (visible) {
      if (visible && !this.manufacturers.loading && !this.manufacturers.loaded) {
        this.manufacturers.loading = true
        getReceivingCardManufacturers().then(({ data }) => {
          this.manufacturers.list = data.map(({ id, name }) => {
            return { value: id, label: name }
          })
          this.manufacturers.loading = false
          this.manufacturers.loaded = true
        }, () => {
          this.manufacturers.loading = false
        })
      }
    },
    onAdd () {
      this.receivingCard = {
        manufacturerId: '',
        topologyFile: null,
        screen: '',
        temperature: false,
        voltage: false,
        async: false
      }
      this.show = true
    },
    close () {
      this.show = false
    },
    save () {
      if (!this.receivingCard.topologyFile) {
        this.$message({
          type: 'warning',
          message: '请选择拓扑结构文件'
        })
        return
      }
      if (!this.receivingCard.manufacturerId) {
        this.$message({
          type: 'warning',
          message: '请选择厂家'
        })
        return
      }
      const formData = new FormData()
      formData.append('manufacturerId', this.receivingCard.manufacturerId)
      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)
      this.progress = 0
      this.showProgress = true
      addReceivingCard(this.$route.params.id, formData, ({ loaded, total }) => {
        this.progress = Math.min(99, loaded * 100 / total | 0)
      }).finally(() => {
        this.progress = 100
        this.showProgress = false
      }).then(() => {
        this.close()
        this.emitChange('all')
      })
    },
    updateReceivingCard () {
      updateReceivingCard()
    },
    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
      })
    },
    onChangeProp (key) {
      if (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(key, data)
      return updateReceivingCard(this.$route.params.id, formData, options).then(() => {
        this.emitChange(key)
      })
    },
    emitChange (key) {
      let tip = null
      let reset = false
      switch (key) {
        case 'manufacturerId':
          tip = '厂商'
          break
        case 'topologyFile':
          tip = '拓扑图'
          reset = true
          break
        case 'all':
          tip = '数据'
          reset = true
          break
        default:
          break
      }
      if (!reset) {
        this.info[key] = this.defaults[key]
      }
      this.$emit('refresh', { tip, reset })
    }
  }
}
</script>
