<template>
  <table-dialog
    ref="tableDialog"
    title="选择播放内容"
    size="medium"
    :schema="schema"
    append-to-body
    v-bind="$attrs"
    @choosen="onChoosen"
  >
    <schedule-dialog ref="scheduleDialog" />
  </table-dialog>
</template>

<script>
import { getPrograms } from '@/api/program'
import { getSchedules } from '@/api/calendar'
import {
  State,
  ScheduleType,
  EventTarget
} from '@/constant'

export default {
  name: 'EventTargetDialog',
  props: {
    ratio: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      schema: {
        list: this.getListInvoke,
        condition: { type: EventTarget.PROGRAM, name: '' },
        filters: [
          { key: 'type', type: 'select', options: [
            { value: EventTarget.PROGRAM, label: '单节目' },
            { value: EventTarget.RECUR, label: '轮播' }
          ] },
          { key: 'name', type: 'search', placeholder: '节目名称' }
        ],
        cols: [
          { prop: 'name', label: '节目名称' },
          { type: 'invoke', render: [
            { label: '查看', on: this.onView }
          ] }
        ]
      }
    }
  },
  methods: {
    show () {
      this.$refs.tableDialog.show()
    },
    getListInvoke ({ type, name, pageSize, pageNum }) {
      switch (type) {
        case EventTarget.RECUR:
          return getSchedules({
            pageSize, pageNum,
            name,
            type: ScheduleType.RECUR,
            resolutionRatio: this.ratio,
            status: State.RESOLVED
          })
        default:
          return getPrograms({
            pageSize, pageNum,
            name,
            resolutionRatio: this.ratio,
            status: State.RESOLVED
          })
      }
    },
    onView ({ id }) {
      switch (this.$refs.tableDialog.getTable().getCondition().type) {
        case EventTarget.PROGRAM:
          window.open(this.$router.resolve({
            name: 'program',
            params: { id }
          }).href, '_blank')
          break
        case EventTarget.RECUR:
          this.$refs.scheduleDialog.show(id)
          break
        default:
          break
      }
    },
    onChoosen ({ value, done }) {
      this.$emit('choosen', {
        value: this.getValue(this.$refs.tableDialog.getTable().getCondition().type, value),
        done
      })
    },
    getValue (type, item) {
      switch (type) {
        case EventTarget.PROGRAM:
          return {
            type,
            id: item.id,
            name: item.name,
            programUrl: `${item.buckets}/${item.itemConfigName}`,
            duration: Number(item.duration)
          }
        case EventTarget.RECUR:
          return {
            type,
            id: item.id,
            name: item.name
          }
        default:
          return null
      }
    }
  }
}
</script>
