<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      row-key="id"
      :schema="schema"
      @row-click="onRowClick"
    />
  </wrapper>
</template>

<script>
import {
  getDevicesByAdmin,
  getSubDevices,
  activateDevice,
  deactivateDevice,
  getProducts
} from '@/api/device'

export default {
  name: 'GroupDeviceManage',
  data () {
    const productSelectSchema = {
      remote: getProducts,
      pagination: true,
      placeholder: '全部产品',
      value: 'id',
      label: 'name'
    }

    return {
      schema: {
        condition: { productId: void 0, name: '', tenant: this.$store.getters.tenant },
        list: getDevicesByAdmin,
        transform: this.transform,
        transformData: this.transformTableData,
        filters: [
          { key: 'productId', type: 'select', ...productSelectSchema },
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        cols: [
          { type: 'refresh', render (data, h) {
            return data.isMaster
              ? h('i', {
                staticClass: `o-expand-icon u-pointer ${data.loading ? 'el-icon-loading' : 'el-icon-arrow-right'}`,
                class: { expand: data.expand }
              })
              : null
          } },
          { label: '设备名称', 'min-width': 120, render (data, h) {
            return data.empty ? h('span', { staticClass: 'u-color--info' }, '暂无备份设备') : data.name
          } },
          { prop: 'productName', label: '产品' },
          { prop: 'serialNumber', label: '序列号', 'min-width': 100 },
          { prop: 'mac', label: 'MAC', 'min-width': 100 },
          { type: 'tag', 'width': 100, render ({ empty, activate, onlineStatus }) {
            return empty
              ? null
              : {
                type: activate
                  ? activate === 1
                    ? void 0
                    : onlineStatus === 1
                      ? 'success'
                      : 'danger'
                  : 'warning',
                label: activate
                  ? activate === 1
                    ? '已激活'
                    : onlineStatus === 1
                      ? '在线'
                      : '离线'
                  : '未激活'
              }
          }, on: this.onTagClick },
          { type: 'invoke', render: [
            { label: '查看', render ({ empty }) { return !empty }, on: this.onViewDevice }
          ] }
        ]
      }
    }
  },
  methods: {
    transform (data) {
      return {
        ...data,
        loaded: false,
        loading: false,
        expand: false,
        subs: [],
        isMaster: true
      }
    },
    transformTableData (data) {
      const arr = []
      data.forEach(item => {
        arr.push(item)
        if (item.loaded && item.expand) {
          arr.push(...item.subs)
        }
      })
      return arr
    },
    onViewDevice (item) {
      this.$router.push({
        name: 'device-detail',
        params: {
          id: item.id
        }
      })
    },
    reloadSubDevices (item) {
      item.loaded = false
      item.children = []
      this.getSubDevices(item)
    },
    getSubDevices (item, pageSize = 999) {
      item.loading = true
      getSubDevices({
        id: item.id,
        pageNum: 1,
        pageSize
      }).then(({ data, totalCount }) => {
        if (totalCount > pageSize) {
          this.getSubDevices(item, totalCount)
        } else {
          item.loading = false
          item.loaded = true
          item.expand = true
          if (data.length === 0) {
            item.subs = [{ id: `${Math.random()}`, empty: true }]
          } else {
            item.subs = data.map(device => {
              return {
                ...device,
                isMaster: false,
                empty: false,
                parent: item
              }
            })
          }
        }
      }, () => {
        item.loading = false
      })
    },
    onRowClick (data) {
      if (data.isMaster) {
        if (data.loaded) {
          data.expand = !data.expand
        } else if (!data.loading) {
          this.getSubDevices(data)
        }
      }
    },
    onTagClick (data) {
      (data.activate ? deactivateDevice : activateDevice)(data).then(() => {
        if (data.isMaster) {
          this.$refs.table.pageTo()
        } else {
          this.reloadSubDevices(data.parent)
        }
      })
    }
  }
}
</script>
