<template>
  <wrapper
    fill
    margin
    background
  >
    <div class="l-flex__none l-flex--row c-step has-padding">
      <button
        class="l-flex__none c-sibling-item o-button"
        :class="{ hidden: active === 0 }"
        @click="onPresent"
      >
        上一步
      </button>
      <el-steps
        :active="active"
        class="l-flex__fill"
        finish-status="success"
        align-center
      >
        <el-step title="选择设备" />
        <el-step title="选择内容" />
      </el-steps>
      <button
        class="l-flex__none c-sibling-item o-button"
        :class="{ hidden: hideNext }"
        @click="onNext"
      >
        {{ btnMsg }}
      </button>
    </div>
    <div class="l-flex__fill l-flex">
      <device-group-tree
        v-show="active === 0"
        ref="tree"
        class="l-flex__fill has-padding"
        @change="onChange"
      />
      <template v-if="active > 0">
        <div class="c-list has-padding u-overflow-y--auto">
          <div class="c-list__item u-bold">{{ resolutionRatio }}</div>
          <div
            v-for="device in selectedDevices"
            :key="device.id"
            class="c-list__item"
          >
            {{ device.name }}
          </div>
        </div>
        <div class="c-list large has-padding u-overflow-y--auto">
          <div class="c-list__item">
            <div class="o-type">发布类型</div>
            <el-select v-model="eventOptions.type">
              <el-option
                v-for="option in typeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </div>
          <div
            v-if="isEvent"
            class="c-list__item"
          >
            <div class="o-type">级别</div>
            <el-select v-model="priority">
              <el-option
                v-for="option in priorityOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </div>
          <div
            v-if="isCalendar"
            class="c-list__item c-grid-form medium col"
          >
            <div class="c-grid-form__label required">播放内容</div>
            <div class="o-schedule-button u-pointer">
              <div
                class="o-schedule-button__label has-padding--h"
                @click="onChooseSchedule"
              >
                <div class="u-ellipsis">{{ msg }}</div>
              </div>
            </div>
          </div>
          <event-picker
            v-show="isEvent"
            ref="picker"
            class="c-list__item"
            :ratio="resolutionRatio"
            vertical
            @choosen="onChoosenProgram"
          />
          <table-dialog
            ref="scheduleDialog"
            title="排期选择"
            size="medium"
            :schema="scheduleSchema"
            @choosen="onChoosenSchedule"
          />
        </div>
        <div
          v-if="eventTarget"
          class="c-list fill has-padding u-overflow-y--auto"
        >
          <schedule
            v-if="scheduleId"
            :schedule="scheduleId"
          />
          <div
            v-if="programId"
            class="o-program u-pointer"
            @click="onViewProgram"
          >
            {{ eventTarget.name }}
          </div>
        </div>
      </template>
    </div>
    <program-dialog ref="programDialog" />
  </wrapper>
</template>

<script>
import { getSchedules } from '@/api/calendar'
import { publish } from '@/api/platform'
import {
  State,
  ScheduleType,
  EventTarget,
  PublishType,
  EventPriority,
  EventPriorityDescription
} from '@/constant'

export default {
  name: 'ScheduleDeploy',
  data () {
    return {
      typeOptions: [
        { value: PublishType.CALENDAR, label: '排期' },
        { value: PublishType.EVENT, label: '节目' }
      ],
      active: 0,
      selectedDevices: [],
      priority: EventPriority.INSERTED,
      priorityOptions: [
        { value: EventPriority.INSERTED, label: EventPriorityDescription[EventPriority.INSERTED] },
        { value: EventPriority.EMERGENT, label: EventPriorityDescription[EventPriority.EMERGENT] }
      ],
      eventOptions: null,
      scheduleSchema: {
        condition: { type: ScheduleType.COMPLEX, status: State.AVAILABLE, name: '' },
        list: getSchedules,
        filters: [
          { key: 'name', type: 'search', placeholder: '排期名称' }
        ],
        cols: [{ prop: 'name', label: '名称', align: 'center' }]
      }
    }
  },
  computed: {
    hideNext () {
      switch (this.active) {
        case 0:
          return this.selectedDevices.length === 0
        case 1:
          return !this.eventTarget
        default:
          return false
      }
    },
    eventTarget () {
      if (this.isCalendar) {
        return this.eventOptions?.schedule
      }
      return this.eventOptions?.program
    },
    isCalendar () {
      return this.eventOptions?.type === PublishType.CALENDAR
    },
    isEvent () {
      return this.eventOptions?.type === PublishType.EVENT
    },
    btnMsg () {
      return this.active < 1 ? '下一步' : '发布'
    },
    resolutionRatio () {
      return this.selectedDevices[0]?.resolutionRatio
    },
    typeMsg () {
      return this.typeOptions[this.eventOptions?.type - 1]?.label
    },
    scheduleId () {
      return this.eventOptions?.type === PublishType.CALENDAR || this.eventTarget?.type === EventTarget.RECUR ? this.eventTarget.id : null
    },
    programId () {
      return this.eventTarget?.type === EventTarget.PROGRAM ? this.eventTarget.id : null
    },
    msg () {
      return this.eventTarget?.name ?? '点击选择内容'
    }
  },
  methods: {
    onPresent () {
      if (this.active > 0) {
        this.active = 0
      }
    },
    onNext () {
      switch (this.active) {
        case 0:
          if (this.checkDevices()) {
            this.active += 1
          }
          break
        case 1:
        case 2:
          this.publish().then(() => {
            this.active = 0
            this.$refs.tree.reset()
            this.eventOptions = null
            this.priority = EventPriority.INSERTED
          })
          break
        default:
          break
      }
    },
    onError (message) {
      this.$message({
        type: 'warning',
        message
      })
      return false
    },
    onChange (devices) {
      this.selectedDevices = devices
    },
    checkDevices () {
      const devices = this.selectedDevices
      const length = devices.length
      if (!length) {
        return this.onError('请选择目标设备')
      }
      const resolutionRatio = this.resolutionRatio
      if (devices.some(device => device.resolutionRatio !== resolutionRatio)) {
        return this.onError('选择的设备分辨率不一致')
      }
      this.eventOptions = this.createEventOptions()
      return true
    },
    createEventOptions () {
      return {
        ratio: this.resolutionRatio,
        type: PublishType.CALENDAR,
        schedule: null,
        program: null
      }
    },
    onChoosenProgram (val) {
      this.eventOptions.program = val
    },
    onChooseSchedule () {
      this.$refs.scheduleDialog.show({ resolutionRatio: this.resolutionRatio })
    },
    onChoosenSchedule ({ value: { id, name }, done }) {
      done()
      this.eventOptions.schedule = { id, name }
    },
    onViewProgram () {
      this.$refs.programDialog.show(this.programId)
    },
    getPublishTarget () {
      if (this.eventOptions.type === PublishType.CALENDAR) {
        return Promise.resolve({
          type: PublishType.CALENDAR,
          detail: this.eventTarget.id
        })
      }
      const event = this.$refs.picker.getValue()
      if (event) {
        return Promise.resolve({
          type: PublishType.EVENT,
          detail: {
            ...event,
            priority: this.priority
          }
        })
      }
      return Promise.reject()
    },
    publish () {
      return this.getPublishTarget().then(eventTarget => {
        const devices = this.selectedDevices
        return this.$confirm(
          `对设备 ${devices.map(device => device.name)}`,
          `发布 ${this.typeMsg} ${this.eventTarget.name}`,
          { type: 'warning' }
        ).then(() => publish(
          devices.map(device => device.id),
          eventTarget,
          {
            programCalendarName: this.eventTarget.name,
            resolutionRatio: this.resolutionRatio
          }
        ))
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.c-step {
  border-bottom: 1px solid $gray--light;

  .hidden {
    visibility: hidden;
  }
}

.c-list {
  flex: 0 0 200px;
  min-width: 200px;
  padding-right: $spacing;
  color: $black;

  & + & {
    border-left: 1px solid $gray--light;
  }

  &.large {
    min-width: 336px;
    max-width: 336px;
  }

  &.fill {
    flex: 1 0 200px;
  }

  &__item {
    line-height: 1;

    & + & {
      margin-top: 8px;
    }

    &:nth-child(2) {
      margin-top: 10px;
    }
  }
}

.o-type {
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: bold;
  line-height: 1;
}

.o-schedule-button {
  position: relative;
  width: 217px;
  height: 40px;
  color: $blue;
  font-size: 14px;
  line-height: 1;
  border-radius: $radius--mini;
  border: 1px solid #dcdfe6;

  &:hover {
    border-color: #c0c4cc;
  }

  &__label {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    width: 100%;
    height: 100%;
  }
}

.o-program {
  font-size: 24px;
  font-weight: bold;

  &:hover {
    color: #409eff;
  }
}
</style>
