<template>
  <wrapper
    fill
    margin
    padding
    background
    horizontal
  >
    <department-tree
      class="c-sibling-item c-sidebar u-width--md"
      remember
      @change="onGroupChanged"
    />
    <schema-table
      ref="table"
      class="c-sibling-item far"
      row-key="id"
      :schema="schema"
    />
  </wrapper>
</template>

<script>
import { getDevicesByQuery } from '@/api/device'

export default {
  name: 'DeviceList',
  data () {
    return {
      schema: {
        keepalive: true,
        autoRefreshEachPage: true,
        list: this.getDevicesByQuery,
        filters: [
          { key: 'name', type: 'search', placeholder: '设备名称' },
          { type: 'refresh' }
        ],
        cols: [
          { prop: 'name', label: '设备名称', 'min-width': 120 },
          { type: 'tag', render: ({ activate, onlineStatus }) => activate
            ? onlineStatus === 0
              ? { type: 'primary', label: '待接入' }
              : onlineStatus === 1
                ? { type: 'success', label: '在线' }
                : { type: 'danger', label: '离线' }
            : { type: 'warning', label: '未激活' }, 'width': 120 },
          { label: '运行时间', render: ({ openTime, closeTime }) => openTime && closeTime
            ? `${openTime} - ${closeTime}`
            : '-', width: 140 },
          { prop: 'address', label: '地址', 'min-width': 160 },
          { type: 'invoke', render: [
            { label: '详情', on: this.onViewDevice }
          ] }
        ]
      }
    }
  },
  methods: {
    onGroupChanged (group) {
      this.$group = group
      this.$refs.table?.pageTo(1)
    },
    getDevicesByQuery (params) {
      if (!this.$group) {
        return Promise.resolve({ data: [] })
      }
      return getDevicesByQuery({
        org: this.$group.path,
        ...params
      })
    },
    onViewDevice (item) {
      this.$router.push({
        name: 'device-detail',
        params: {
          id: item.id
        }
      })
    }
  }
}
</script>
