<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      :schema="schema"
    />
    <workflow-detail-dialog ref="workflowDetailDialog" />
    <workflow-history-dialog ref="workflowHistoryDialog" />
  </wrapper>
</template>

<script>
import { State } from '@/constant'
import {
  getPublishHistory,
  cancelPublish
} from '../api'
import { transformCalendarRelease } from '../utils'
import WorkflowDetailDialog from '../components/WorkflowDetailDialog.vue'
import WorkflowHistoryDialog from '../components/WorkflowHistoryDialog.vue'

export default {
  name: 'ScheduleDeployHistory',
  components: {
    WorkflowDetailDialog,
    WorkflowHistoryDialog
  },
  data () {
    return {
      workflow: {},
      schema: {
        list: getPublishHistory,
        transform: this.transform,
        cols: [
          { type: 'refresh', render: ({ priority }) => priority },
          { prop: 'priorityInfo', label: '优先级', width: 80, align: 'center' },
          { prop: 'targetInfo', label: '上播内容', width: 80, align: 'center' },
          { prop: 'targetName', label: '', 'min-width': 100 },
          { prop: 'createBy', label: '发布人' },
          { prop: 'createTime', label: '发布时间', 'min-width': 100 },
          { type: 'tag', render: ({ status, remark }) => {
            switch (status) {
              case State.SUBMITTED:
                return {
                  type: 'primary',
                  label: '发布中'
                }
              case State.RESOLVED:
                return {
                  type: 'success',
                  label: '已发布'
                }
              case State.CANCEL:
                return {
                  type: 'danger',
                  label: '已下架'
                }
              default:
                return {
                  type: 'danger',
                  label: '异常',
                  msg: remark
                }
            }
          } },
          { type: 'invoke', render: [
            this.$store.getters.isGroupAdmin && { label: '下架', allow: ({ status }) => status === State.RESOLVED, on: this.onCancel },
            { label: '详情', on: this.onDetail },
            { label: '流程历史', allow: ({ workflowId }) => !!workflowId, on: this.onViewHistory }
          ].filter(Boolean), width: 200 }
        ]
      }
    }
  },
  methods: {
    transform (item) {
      return {
        workflowId: item.workflowId,
        status: item.status,
        ...transformCalendarRelease(item)
      }
    },
    onCancel (workflowHis) {
      cancelPublish(workflowHis.id).then(() => {
        this.$refs.table.pageTo()
      })
    },
    onDetail (workflowHis) {
      this.$refs.workflowDetailDialog.show(workflowHis, { history: true })
    },
    onViewHistory ({ workflowId }) {
      this.$refs.workflowHistoryDialog.show(workflowId)
    }
  }
}
</script>
