<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <table-dialog
      ref="tableDialog"
      title="关联设备"
      :schema="deviceSchema"
    />
  </schema-table>
</template>

<script>
import {
  getBroadcasts,
  disableBroadcast,
  disableDeviceRelease,
  getDeviceReleases
} from '@/api/broadcast'

export default {
  name: 'BroadcastHistoryTable',
  props: {
    tenant: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      schema: {
        condition: { tenant: this.tenant },
        list: getBroadcasts,
        filters: [
          {
            key: 'releaseStatus',
            type: 'select',
            placeholder: '全部状态',
            options: [
              { value: 1, label: '已发布' },
              { value: 0, label: '已失效' }
            ]
          }
        ],
        cols: [
          { prop: 'name', label: '模板' },
          { label: '位置', 'min-width': 60, render ({ position }) {
            return ['顶部', '底部'][position]
          } },
          { prop: 'content', label: '内容', 'min-width': 120 },
          { prop: 'startTime', label: '发布时间' },
          { prop: 'endTime', label: '失效时间', render ({ endTime }) {
            return endTime || '-'
          } },
          { label: '状态', type: 'tag', width: 100, render ({ releaseStatus }) {
            return {
              type: ['warning', 'success'][releaseStatus],
              label: ['失效', '正常'][releaseStatus]
            }
          } },
          { type: 'invoke', width: 160, render: [
            { label: '设备列表', on: this.onViewDevice },
            { label: '下架', render ({ releaseStatus }) {
              return releaseStatus !== 0
            }, on: this.onDisable }
          ] }
        ]
      },
      releaseId: ''
    }
  },
  computed: {
    deviceSchema () {
      return {
        condition: { releaseId: this.releaseId },
        list: getDeviceReleases,
        cols: [
          { prop: 'deviceId', label: '设备id' },
          { label: '状态', type: 'tag', render ({ publishStatus }) {
            return {
              type: ['warning', 'success'][publishStatus],
              label: ['失效', '正常'][publishStatus]
            }
          } },
          { type: 'invoke', render: [
            { label: '下架', render ({ publishStatus }) {
              return publishStatus !== 0
            }, on: this.disableDeviceRelease }
          ] }
        ]
      }
    }
  },
  methods: {
    onViewDevice ({ releaseId }) {
      this.releaseId = releaseId
      this.$refs.tableDialog.show()
    },
    onDisable (item) {
      disableBroadcast(item.releaseId).then(() => {
        item.releaseStatus = 0
      })
    },
    disableDeviceRelease (item) {
      disableDeviceRelease({ deviceId: item.deviceId, releaseId: this.releaseId }).then(() => {
        item.status = 0
      })
    }
  }
}
</script>
