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

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

export default {
  name: 'ScheduleDeployHistory',
  components: {
    PublishDetailDialog,
    WorkflowHistoryDialog
  },
  data () {
    return {
      workflow: {},
      schema: {
        list: getPublishHistory,
        transform: this.transform,
        cols: [
          { type: 'refresh' },
          { prop: 'priority', label: '优先级', width: 100, align: 'center' },
          { prop: 'type', label: '上播内容', width: 80, align: 'center' },
          { prop: 'name', label: '' },
          { prop: 'createByUsername', label: '发布人', width: 160, align: 'center' },
          { prop: 'createTime', label: '发布时间', width: 160, align: 'center' },
          { 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: 180 }
        ]
      }
    }
  },
  methods: {
    transform ({ id, status, workflowId, createByUsername, createTime, remark, ...data }) {
      return {
        id,
        status,
        workflowId,
        createByUsername,
        createTime,
        remark,
        ...parseDeploy(data)
      }
    },
    onCancel (workflowHis) {
      cancelPublish(workflowHis.id).then(() => {
        this.$refs.table.pageTo()
      })
    },
    onDetail (workflowHis) {
      this.$refs.publishDetailDialog.show(workflowHis)
    },
    onViewHistory ({ workflowId }) {
      this.$refs.workflowHistoryDialog.show(workflowId)
    }
  }
}
</script>
