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

<script>
import { getPublishWorkflows } from '@/api/workflow'
import {
  PublishType,
  EventPriority,
  State
} from '@/constant'
import { getEventDescription } from '@/utils/event'

export default {
  name: 'WorkflowList',
  data () {
    return {
      schema: {
        condition: { status: State.SUBMITTED },
        list: getPublishWorkflows,
        transform: this.transform,
        cols: [
          { type: 'expand', refresh: true, render (data, h) {
            return h('div', {
              staticClass: 'o-info'
            }, [
              h('div', null, data.desc),
              h('div', null, `设备：${data.device}`)
            ])
          } },
          { prop: 'type', label: '类型', align: 'center', width: 100 },
          { prop: 'name', label: '', 'min-width': 100 },
          { prop: 'createBy', label: '申请人' },
          { prop: 'updateTime', label: '提交时间' },
          { type: 'invoke', render: [
            { label: '审核', on: this.onReview }
          ] }
        ]
      }
    }
  },
  activated () {
    this.$refs.table.pageTo()
  },
  methods: {
    transform (item) {
      const { id, status, updateTime, calendarRelease } = item
      return {
        workflowId: id,
        status,
        updateTime,
        ...this.getSame(calendarRelease),
        ...this.getDiff(calendarRelease)
      }
    },
    getSame ({
      id,
      programCalendarName,
      createBy,
      createByUsername,
      calendarReleaseDeviceList
    }) {
      return {
        id,
        name: programCalendarName,
        createBy: createByUsername || createBy,
        device: calendarReleaseDeviceList?.map(({ deviceName }) => deviceName).join('，')
      }
    },
    getDiff (item) {
      const target = JSON.parse(item.target)
      let type = ''
      switch (target.type) {
        case PublishType.CALENDAR:
          type = '排期'
          break
        case PublishType.EVENT:
          type = ['', '默认播放', '单播', '插播'][target.detail.priority]
          break
        default:
          break
      }
      return {
        type,
        target,
        desc: this.getDesc(target)
      }
    },
    getDesc (target) {
      if (target.type === PublishType.EVENT && target.detail.priority === EventPriority.INSERTED) {
        return getEventDescription(target.detail)
      }
      return ''
    },
    onToggle (row) {
      this.$refs.table.getInst().toggleRowExpansion(row)
    },
    onReview (item) {
      this.$router.push({
        name: 'workflow-detail',
        params: { id: item.workflowId }
      })
    }
  }
}
</script>
