<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      :schema="schema"
    />
    <confirm-dialog
      ref="editDialog"
      :title="dialogTitle"
      @confirm="onSave"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">名称：</span>
        <el-input
          v-model.trim="currObj.name"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
        <span class="c-grid-form__label">备注：</span>
        <el-input
          v-model.trim="currObj.remark"
          type="textarea"
          maxlength="100"
          :rows="3"
          show-word-limit
        />
      </div>
    </confirm-dialog>
    <table-dialog
      ref="subDeviceDialog"
      title="设备"
      :schema="subDeviceSchema"
      size="large"
    />
    <table-dialog
      ref="deviceDialog"
      title="添加设备"
      :schema="deviceSchema"
      append-to-body
      @choosen="onChoosenDevice"
    />
  </wrapper>
</template>

<script>
import {
  getDeviceGroups,
  addDeviceGroup,
  updateDeviceGroup,
  deleteDeviceGroup,
  getDevicesByGroup,
  getDevices,
  addDeviceToGroup,
  deleteDeviceFromGroup
} from '@/api/device'

export default {
  name: 'DeviceGroup',
  data () {
    return {
      isAdd: false,
      currObj: {},
      schema: {
        condition: { name: '' },
        list: getDeviceGroups,
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        filters: [
          { key: 'name', type: 'search', placeholder: '分组名称' }
        ],
        cols: [
          { prop: 'name', label: '分组名称' },
          { prop: 'remark', label: '备注' },
          { type: 'invoke', width: 160, render: [
            { label: '编辑', on: this.onEdit },
            { label: '设备', on: this.onViewDevices },
            { label: '删除', on: this.onDel }
          ] }
        ]
      },
      subDeviceSchema: {
        singlePage: true,
        list: this.getDevicesByGroup,
        buttons: [
          { type: 'add', label: '添加设备', on: this.onAddDevice }
        ],
        cols: [
          { prop: 'name', label: '设备名称' },
          { prop: 'productName', label: '产品' },
          { prop: 'serialNumber', label: '序列号' },
          { prop: 'mac', label: 'MAC' },
          { prop: 'resolutionRatio', label: '分辨率' },
          { prop: 'address', label: '地址' },
          { type: 'invoke', width: 100, render: [
            { label: '移除', on: this.onDelDevice }
          ] }
        ]
      },
      deviceSchema: {
        condition: { name: '' },
        filters: [
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        list: getDevices,
        cols: [
          { prop: 'name', label: '设备名称' },
          { prop: 'productName', label: '产品' },
          { prop: 'serialNumber', label: '序列号' },
          { prop: 'mac', label: 'MAC' },
          { prop: 'resolutionRatio', label: '分辨率' },
          { prop: 'address', label: '地址' }
        ]
      }
    }
  },
  computed: {
    dialogTitle () {
      return this.isAdd ? '新增设备分组' : '编辑设备分组'
    }
  },
  methods: {
    onAdd () {
      this.isAdd = true
      this.currObj = {
        name: '',
        remark: ''
      }
      this.$refs.editDialog.show()
    },
    onEdit (deviceGroup) {
      this.isAdd = false
      const { id, name, remark } = deviceGroup
      this.currObj = { id, name, remark }
      this.$currObj = deviceGroup
      this.$refs.editDialog.show()
    },
    onSave (done) {
      if (!this.currObj.name) {
        this.$message({
          type: 'warning',
          message: '分组名称不能为空'
        })
        return
      }
      this.save(done).then(() => {
        if (this.isAdd) {
          this.$refs.table.resetCondition({ name: this.currObj.name })
        } else {
          this.$refs.table.pageTo()
        }
      })
    },
    save (done) {
      if (!this.isAdd && Object.keys(this.currObj).every(key => this.currObj[key] === this.$currObj[key])) {
        done()
        return Promise.reject()
      }
      return (this.isAdd ? addDeviceGroup : updateDeviceGroup)(this.currObj).then(done)
    },
    onDel (deviceGroup) {
      return deleteDeviceGroup(deviceGroup).then(() => {
        this.$refs.table.decrease(1)
      })
    },
    onViewDevices ({ id }) {
      this.$devices = null
      this.$refs.subDeviceDialog.show({ id })
    },
    getDevicesByGroup ({ id }) {
      if (this.$devices) {
        return Promise.resolve({ data: this.$devices })
      }
      return getDevicesByGroup(id).then(({ data }) => {
        this.$devices = data
        return { data }
      })
    },
    onDelDevice (device) {
      const table = this.$refs.subDeviceDialog.getTable()
      deleteDeviceFromGroup(table.getCondition().id, device).then(() => {
        this.$devices = null
        table.decrease(1)
      })
    },
    onAddDevice () {
      this.$refs.deviceDialog.show()
    },
    canJoin (device) {
      const data = this.$refs.subDeviceDialog.getTable().getData()
      if (data.length === 0 || data.some(({ resolutionRatio }) => device.resolutionRatio === resolutionRatio)) {
        return Promise.resolve()
      }
      return this.$confirm(
        `设备 ${device.name} 与分组中的设备分辨率不一致，确定加入分组？`,
        { type: 'warning' }
      )
    },
    onChoosenDevice ({ value, done }) {
      const table = this.$refs.subDeviceDialog.getTable()
      this.canJoin(value).then(() => {
        addDeviceToGroup(table.getCondition().id, value.id).then(() => {
          done()
          this.$devices = null
          table.pageTo(1)
        })
      })
    }
  }
}
</script>
