<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <preview-dialog ref="previewDialog" />
  </schema-table>
</template>

<script>
import { getDeviceAlarms } from '@/api/device'
import { createListOptions } from '@/utils'
import {
  AssetType,
  AlarmStrategy,
  AlarmStrategies,
  AlarmType
} from '@/constant'

export default {
  name: 'DeviceAlarm',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      options: createListOptions({ deviceId: this.device.id }),
      schema: {
        condition: { deviceId: this.device.id },
        list: getDeviceAlarms,
        transform: this.transform,
        cols: [
          { type: 'refresh' },
          { prop: 'asset', label: '截图', type: 'asset', on: this.onView },
          { prop: 'type', label: '类型', 'min-width': 120 },
          { prop: 'handle', label: '处理方式' },
          { prop: 'status', label: '处理结果', type: 'tag' },
          ...AlarmStrategies.map(key => {
            return {
              prop: key,
              label: `${AlarmStrategy[key]}通知`,
              type: 'tag',
              'min-width': 100
            }
          }),
          { prop: 'happenTime', label: '时间', 'min-width': 120 }
        ]
      }
    }
  },
  methods: {
    transform ({ pic, picUrl, type, handle, status, happenTime, ...data }) {
      const alarm = {
        asset: pic && picUrl
          ? {
            type: AssetType.IMAGE,
            url: picUrl
          }
          : null,
        type: this.getType(type),
        handle: ['应用重启', '设备重启', '恢复出厂', '未干预'][handle] || '-',
        status: handle <= 2 && status <= 2
          ? {
            type: ['primary', 'success', 'danger'][status],
            label: ['处理中', '成功', '失败'][status]
          }
          : null,
        happenTime
      }
      AlarmStrategies.forEach(key => {
        alarm[key] = this.getTag(data[key])
      })
      return alarm
    },
    getType (type) {
      if (type >= 1101 && type <= 1116) {
        type = 1000
      }
      return AlarmType[type] || '-'
    },
    getTag (value) {
      switch (value) {
        case 0:
          return {
            type: 'danger',
            label: '否'
          }
        case 1:
          return {
            type: 'success',
            label: '是'
          }
        default:
          return null
      }
    },
    onView (asset) {
      this.$refs.previewDialog.show(asset)
    }
  }
}
</script>
