<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      row-key="id"
      :schema="schema"
      @row-click="onRowClick"
    />
    <event-target-dialog
      ref="eventTargetDialog"
      :ratio="ratio"
      @choosen="onChoosen"
    />
  </wrapper>
</template>

<script>
import {
  getDevices,
  getSubDevices,
  activateDevice,
  deactivateDevice
} from '@/api/device'
import { publish } from '@/api/platform'
import {
  Access,
  EventPriority,
  EventFreq,
  PublishType
} from '@/constant'
import { toDateStr } from '@/utils/event'

export default {
  name: 'DeviceList',
  data () {
    const canEdit = this.accessSet.has(Access.MANAGE_DEVICE)

    return {
      ratio: null,
      schema: {
        keepalive: true,
        condition: { name: '' },
        list: getDevices,
        transform: this.transform,
        transformData: this.transformTableData,
        filters: [
          { 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 },
          { prop: 'address', label: '地址' },
          { 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', width: canEdit ? 160 : 120, render: [
            { label: '查看', render ({ empty }) { return !empty }, on: this.onViewDevice },
            canEdit ? { label: '默认播放', render ({ isMaster, activate }) { return isMaster && activate }, on: this.onSetDefaultProgram } : null
          ].filter(Boolean) }
        ]
      }
    }
  },
  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)
        }
      })
    },
    onSetDefaultProgram (device) {
      this.ratio = device.resolutionRatio
      this.$device = {
        id: device.id,
        name: device.name
      }
      this.$refs.eventTargetDialog.show()
    },
    onChoosen ({ value, done }) {
      this.$confirm(
        `将设备 ${this.$device.name} 的默认播放设置为 ${value.name} ？`,
        { type: 'warning' }
      ).then(() => publish(
        [this.$device.id],
        {
          type: PublishType.EVENT,
          detail: {
            priority: EventPriority.DEFAULT,
            freq: EventFreq.ONCE,
            start: `${toDateStr(new Date())} 00:00:00`,
            until: null,
            target: value
          }
        },
        {
          programCalendarName: value.name,
          resolutionRatio: this.ratio
        }
      )).then(done)
    }
  }
}
</script>
