<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <table-dialog
      ref="tableDialog"
      size="lg"
      title="分配设备"
      :schema="deviceSchema"
      @row-dblclick="onChoosen"
    />
  </schema-table>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getDevicesByAdmin,
  getBoundDevices,
  bindDeviceToObject,
  unbindDevice
} from '@/api/device'

export default {
  name: 'Device',
  props: {
    group: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      schema: {
        list: this.getDevices,
        buttons: [
          { type: 'add', label: '分配', on: this.onAdd }
        ],
        filters: [
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        cols: [
          { prop: 'name', label: '设备名称', 'min-width': 120 },
          { prop: 'serialNumber', label: '序列号', 'min-width': 140 },
          { prop: 'mac', label: 'MAC', 'min-width': 140 },
          { prop: 'address', label: '地址' },
          { type: 'invoke', width: 100, render: [
            { label: '移除', on: this.onDel }
          ] }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['tenant']),
    deviceSchema () {
      return {
        list: getDevicesByAdmin,
        condition: { name: '', tenant: this.tenant },
        filters: [
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        cols: [
          { prop: 'name', label: '设备名称', 'min-width': 120 },
          { prop: 'serialNumber', label: '序列号', 'min-width': 140 },
          { prop: 'mac', label: 'MAC', 'min-width': 140 },
          { prop: 'address', label: '地址', 'min-width': 100 }
        ]
      }
    }
  },
  watch: {
    group () {
      this.$refs.table.pageTo(1)
    }
  },
  methods: {
    getDevices (params) {
      return getBoundDevices({
        org: this.group.path,
        ...params
      })
    },
    onAdd () {
      this.$refs.tableDialog.show()
    },
    onChoosen ({ id }) {
      bindDeviceToObject(id, this.group.path).then(() => {
        this.$message({
          type: 'success',
          message: '分配成功'
        })
        this.$refs.table.pageTo(1)
      })
    },
    onDel (device) {
      unbindDevice(device).then(() => {
        this.$refs.table.decrease(1)
      })
    }
  }
}
</script>
