<template>
  <div
    v-loading="loading"
    class="l-flex--col"
  >
    <template v-if="!loading">
      <warning
        v-if="error"
        @click="getGateway"
      />
      <template v-else>
        <template v-if="gateway">
          <div class="c-sibling-item--v c-info">
            <div class="l-flex--row has-bottom-padding u-bold">
              <span class="c-sibling-item">网关信息</span>
              <span
                v-if="isSuperAdmin"
                class="c-sibling-item c-info__edit u-pointer"
                @click="onUnbindGateway"
              >
                <i class="el-icon-edit" />
                解绑
              </span>
            </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>
                <auto-text
                  class="l-flex__fill c-info__value"
                  :text="gateway.name"
                />
              </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 c-info__value">{{ gateway.ip }}</div>
              </div>
            </div>
          </div>
          <div class="c-sibling-item--v far c-info">
            <div class="l-flex--row has-bottom-padding u-bold">
              <span class="c-sibling-item">PLC信息</span>
              <span
                v-if="isSuperAdmin"
                class="c-sibling-item c-info__edit u-pointer"
                @click="onBindPLC"
              >
                <i class="el-icon-edit" />
                绑定
              </span>
            </div>
            <div
              v-if="plcs.length === 0"
              class="u-color--info"
            >暂未绑定</div>
            <div
              v-for="plc in plcs"
              :key="plc.id"
              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">
                  <span
                    class="c-info__edit u-pointer"
                    @click="onUnbindPLC(plc)"
                  >
                    解绑
                  </span>
                  名称
                </div>
                <auto-text
                  class="l-flex__fill c-info__value"
                  :text="plc.thirdPartyDevice.name"
                />
              </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 c-info__value">{{ plc.thirdPartyDevice.identifier }}</div>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="l-flex__fill l-flex--row center u-color--info">
            <div class="l-flex--col center">
              <div class="has-padding">未绑定网关，请联系管理员</div>
              <button
                v-if="isSuperAdmin"
                class="o-button"
                @click="onBindGateway"
              >
                绑定网关
              </button>
            </div>
          </div>
        </template>
      </template>
    </template>
    <table-dialog
      ref="chooseDialog"
      :title="dialogTitle"
      :schema="schema"
      @choosen="onChoose"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getGateway,
  getGateways,
  bindGateway,
  getBoundPLCs,
  getPLCs,
  bindPLC,
  unbind
} from '@/api/external'

export default {
  name: 'Gateway',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      error: false,
      info: null,
      deviceType: 'GATEWAY'
    }
  },
  computed: {
    ...mapGetters(['isSuperAdmin']),
    dialogTitle () {
      switch (this.deviceType) {
        case 'PLC':
          return 'PLC选择'
        default:
          return '网关选择'
      }
    },
    schema () {
      switch (this.deviceType) {
        case 'PLC':
          return {
            list: this.getPLCs,
            cols: [
              { prop: 'name', label: '名称' },
              { prop: 'identifier', label: '地址' },
              { prop: 'remark', label: '备注' }
            ]
          }
        default:
          return {
            list: getGateways,
            cols: [
              { prop: 'name', label: '名称' },
              { prop: 'ip', label: '地址' }
            ]
          }
      }
    },
    gateway () {
      return this.info?.gateway?.thirdPartyDevice
    },
    plcs () {
      return this.info?.plcs || []
    }
  },
  activated () {
    !this.info && this.getInfo()
  },
  methods: {
    getInfo (type) {
      if (this.loading) {
        return
      }
      this.loading = true
      this.error = false

      let arr
      if (this.info && type) {
        switch (type) {
          case 'PLC':
            arr = [Promise.resolve(this.info.gateway), this.getBoundPLCs()]
            break
          default:
            arr = [this.getGateway(), Promise.resolve(this.info.plcs)]
            break
        }
      } else {
        arr = [this.getGateway(), this.getBoundPLCs()]
      }

      this.info = null
      Promise.all(arr).then(
        data => {
          this.info = {
            gateway: data[0],
            plcs: data[1]
          }
        },
        () => {
          this.error = false
        }
      ).finally(() => {
        this.loading = false
      })
    },
    getGateway () {
      return getGateway(this.device.id)
    },
    getBoundPLCs () {
      return getBoundPLCs(this.device.id)
    },
    onChoose ({ value, done }) {
      (this.deviceType === 'PLC' ? bindPLC : bindGateway)(this.device.id, value.id).then(() => {
        done()
        this.getInfo(this.deviceType)
      })
    },
    onBindGateway () {
      this.deviceType = 'GATEWAY'
      this.$refs.chooseDialog.show()
    },
    onUnbindGateway () {
      if (this.plcs.length) {
        this.$message({
          type: 'warning',
          message: '请先解绑所有PLC'
        })
        return
      }
      this.$confirm(
        '解绑网关？',
        { type: 'warning' }
      ).then(() => {
        unbind(this.info.gateway.id).then(() => {
          this.info = null
        })
      })
    },
    getPLCs (params) {
      return getPLCs({
        gatewayId: this.gateway.id,
        ...params
      })
    },
    onBindPLC () {
      this.deviceType = 'PLC'
      this.$refs.chooseDialog.show()
    },
    onUnbindPLC (plc) {
      this.$confirm(
        `解绑PLC ${plc.thirdPartyDevice.name}？`,
        { type: 'warning' }
      ).then(() => {
        unbind(plc.id).then(() => {
          this.plcs.splice(this.plcs.indexOf(plc), 1)
        })
      })
    }
  }
}
</script>
