<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <el-tabs
      :value="active"
      class="c-tabs has-bottom-padding"
      @tab-click="onTabClick"
    >
      <el-tab-pane
        label="待审核"
        name="1"
      />
      <el-tab-pane
        label="已审核"
        name="2"
      />
      <el-tab-pane
        label="驳回"
        name="3"
      />
    </el-tabs>
    <schema-table
      ref="table"
      :schema="schema"
      @row-click="onToggle"
    />
    <program-dialog ref="programDialog" />
    <schedule-dialog ref="scheduleDialog" />
    <preview-dialog ref="previewDialog" />
    <table-dialog
      ref="tableDialog"
      title="流程详细"
      :schema="historySchema"
    />
  </wrapper>
</template>

<script>
import {
  getMyWorkflows,
  calendarPublishRestart,
  viewHistory,
  deleteWorkflow
} from '@/api/workflow'
import {
  PublishType,
  EventPriority,
  State,
  EventTarget
} from '@/constant'
import { getEventDescription } from '@/utils/event'

const Type = {
  minio: '媒资',
  item: '节目',
  carousel: '轮播',
  program: '排期',
  calendar: '发布'
}

export default {
  name: 'MyWorkflows',
  data () {
    return {
      active: `${State.SUBMITTED}`,
      workflowId: ''
    }
  },
  computed: {
    schema () {
      const isRejected = this.active === `${State.REJECTED}`

      return {
        condition: { status: Number(this.active) },
        list: getMyWorkflows,
        transform: this.transform,
        cols: [
          { type: 'expand', render: this.renderRelative },
          { prop: 'type', label: '类型', width: 100 },
          { prop: 'name', label: '名称', 'min-width': 100 },
          { prop: 'resolutionRatio', label: '分辨率' },
          { prop: 'createTime', label: '创建时间' },
          isRejected ? { prop: 'reason', label: '驳回原因', 'min-width': 100 } : null,
          { type: 'invoke', width: isRejected ? 200 : 120, render: [
            isRejected ? { label: '编辑', on: this.onEdit } : { label: '查看', on: this.onView },
            isRejected ? { label: '重提交', on: this.onResubmit } : null,
            { label: '历史', on: this.onViewHistory },
            isRejected ? { label: '删除', on: this.onDel } : null
          ].filter(Boolean) }
        ]
      }
    },
    historySchema () {
      return {
        props: { rowClassName: this.isShowExpend },
        listeners: { 'row-click': this.onToggleHistory },
        condition: { workflowId: this.workflowId },
        list: viewHistory,
        transform: row => {
          return { ...row, rejectEvent: JSON.parse(row.rejectEvent) }
        },
        cols: [
          { type: 'expand', render: this.renderReason },
          { prop: 'handledBy', label: '处理人', width: 100 },
          { prop: 'createTime', label: '时间' },
          { label: '状态', type: 'tag', render ({ status }) {
            return {
              type: ['', 'primary', 'success', 'danger'][status],
              label: ['草稿', '提交', '通过', '驳回'][status]
            }
          } },
          { prop: 'reason', label: '备注' }
        ]
      }
    }
  },
  methods: {
    isShowExpend ({ row }) {
      if (row.status !== State.REJECTED) {
        return 'hide-expend'
      }
      return ''
    },
    renderRelative (row, h) {
      return h('div', { staticClass: 'o-info' }, [
        h('div', null, row.desc),
        h('div', { staticClass: 'c-sibling-item--v' }, `设备：${row.device}`),
        ...this.renderRelativeItems(row, h, false)
      ])
    },
    renderReason (row, h) {
      return h('div', { staticClass: 'o-info' }, [
        ...this.renderRelativeItems(row, h)
      ])
    },
    renderRelativeItems (row, h, isView = true) {
      const children = []
      if (
        row.status === State.REJECTED
        && row.rejectEvent?.length
      ) {
        if (
          row.rejectEvent.length === 1
          && row.rejectEvent[0].type === 'calendar'
        ) {
          children.push(h('div', {
            staticClass: 'c-sibling-item--v u-color--error'
          }, '发布驳回'))
        } else {
          children.push(h('div', {
            staticClass: 'c-sibling-item--v'
          }, '驳回对象：'))
          children.push(
            h('div', {
              staticClass: 'l-flex--col',
              staticStyle: { 'align-items': 'flex-start' }
            }, row.rejectEvent
              .filter(i => i.type !== 'calendar')
              .map(item => h('div', {
                staticClass: isView || item.type === 'minio' ? 'u-color--black' : 'u-color--blue u-pointer',
                staticStyle: { padding: '4px 0' },
                on: isView || item.type === 'minio'
                  ? null
                  : {
                    click: $event => {
                      $event.stopPropagation()
                      this.onViewOrEditItem(item)
                    }
                  }
              }, `${Type[item.type]} ${item.name}`)))
          )
        }
      }
      return children
    },
    onViewHistory ({ workflowId }) {
      this.workflowId = workflowId
      this.$refs.tableDialog.show()
    },
    onTabClick ({ name: active }) {
      if (this.active !== active) {
        this.active = active
      }
    },
    transform ({ id, status, reason, calendarRelease, rejectEvent }) {
      const same = this.getSame(calendarRelease)
      const diff = this.getDiff(calendarRelease)
      return {
        ...same,
        ...diff,
        workflowId: id,
        status,
        reason,
        rejectEvent: JSON.parse(rejectEvent)
      }
    },
    getSame ({
      id,
      programCalendarName,
      resolutionRatio,
      createBy,
      createByUsername,
      createTime,
      calendarReleaseDeviceList
    }) {
      return {
        id,
        name: programCalendarName,
        resolutionRatio,
        createBy: createByUsername || createBy,
        createTime,
        device: calendarReleaseDeviceList
          ?.map(item => item.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)
    },
    onToggleHistory (row) {
      if (row.status === State.REJECTED) {
        this.$refs.tableDialog.getTable().getInst().toggleRowExpansion(row)
      }
    },
    onView ({ target: { type, detail } }) {
      switch (type) {
        case PublishType.CALENDAR:
          this.$refs.scheduleDialog.show(detail)
          break
        case PublishType.EVENT:
          if (detail.target.type === EventTarget.RECUR) {
            this.$refs.scheduleDialog.show(detail.target.id)
          } else {
            this.$refs.programDialog.show(detail.target.id)
          }
          break
        default:
          break
      }
    },
    onEdit ({ target: { type, detail } }) {
      switch (type) {
        case PublishType.CALENDAR:
          this.$router.push({
            name: 'schedule-design',
            params: { id: detail }
          })
          break
        case PublishType.EVENT:
          if (detail.target.type === EventTarget.RECUR) {
            this.$router.push({
              name: 'recur-design',
              params: { id: detail.target.id }
            })
          } else {
            this.$designProgram(detail.target.id)
          }
          break
        default:
          break
      }
    },
    onViewOrEditItem (row) {
      switch (row.type) {
        case 'minio':
          this.$refs.previewDialog.show(row)
          break
        case 'item':
          this.$designProgram(row.id)
          break
        case 'carousel':
          this.$router.push({
            name: 'recur-design',
            params: { id: row.id }
          })
          break
        case 'program':
          this.$router.push({
            name: 'schedule-design',
            params: { id: row.id }
          })
          break
        default:
          break
      }
    },
    onResubmit (item) {
      calendarPublishRestart(item.workflowId, item.name).then(() => {
        this.$refs.table.decrease(1)
      })
    },
    onDel ({ workflowId }) {
      deleteWorkflow(workflowId).then(() => {
        this.$refs.table.decrease(1)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .hide-expend .el-table__expand-icon {
  display: none;
}
</style>
