<template>
  <schedule-wrapper
    class="c-schedule-swiper"
    :name="name"
    :hide-header="hideHeader"
    :editable="editable"
    :dirty="dirty"
    @add="onAdd"
    @submit="submit"
    @save="onSave"
  >
    <el-empty
      v-if="isEmpty"
      description="暂无节目"
    />
    <template v-if="editable">
      <draggable
        v-model="scheduleOptions.events"
        class="l-flex__auto c-schedule-swiper__list"
        :class="{ disabled }"
        handle=".mover"
        animation="300"
        :disabled="disabled"
      >
        <div
          v-for="(program, index) in events"
          :key="program.key"
          class="l-flex--row c-schedule-swiper__item"
        >
          <div class="l-flex__auto l-flex--row mover">
            <i class="l-flex__none c-schedule-swiper__mover el-icon-sort" />
            <div
              class="l-flex__auto c-schedule-swiper__program u-ellipsis u-pointer"
              @click="onView(program)"
            >
              {{ program.name }}
            </div>
          </div>
          <span class="l-flex__none">持续时间(秒)：</span>
          <el-input-number
            v-model="program.duration"
            class="l-flex__none"
            controls-position="right"
            :min="1"
            :max="2592000"
            :step="1"
            step-strictly
          />
          <i
            class="l-flex__none c-schedule-swiper__del o-icon--active el-icon-delete u-pointer"
            @click="onDel(program, index)"
          />
        </div>
      </draggable>
      <el-dialog
        :visible.sync="choosing"
        title="选择节目"
        custom-class="c-dialog hidden-footer"
        append-to-body
      >
        <program-choose
          v-if="choosing"
          :ratio="ratio"
          @choose="onChoose"
        />
      </el-dialog>
    </template>
    <template v-else>
      <div class="c-schedule-swiper__list">
        <div
          v-for="program in events"
          :key="program.key"
          class="l-flex--row c-schedule-swiper__item readonly u-pointer"
          @click="onView(program)"
        >
          <div class="c-schedule-swiper__program u-ellipsis">
            {{ program.name }}
          </div>
          <span class="l-flex__none">持续{{ program.duration }}</span>
        </div>
      </div>
    </template>
  </schedule-wrapper>
</template>

<script>
import scheduleMixin from '../mixins/schedule'
import Draggable from 'vuedraggable'
import ScheduleWrapper from '../components/ScheduleWrapper'
import ProgramChoose from '../components/ProgramChoose'

export default {
  name: 'ScheduleSwiper',
  components: {
    Draggable,
    ScheduleWrapper,
    ProgramChoose
  },
  mixins: [scheduleMixin],
  data () {
    return {
      choosing: false,
      record: null
    }
  },
  computed: {
    disabled () {
      return this.events.length < 2
    },
    dirty () {
      if (this.editable && this.record) {
        const { events, count } = this.record
        const currEvents = this.events
        if (count !== currEvents.length) {
          return true
        }
        for (let i = 0; i < events.length; i++) {
          if (events[i].id !== currEvents[i].id || events[i].duration !== currEvents[i].duration) {
            return true
          }
        }
      }
      return false
    }
  },
  methods: {
    _transformEvents (events) {
      return events.sort((a, b) => a.index - b.index)
    },
    _transformEvent (event) {
      const { programId, programName, programUrl, spend } = event
      return {
        key: Math.random().toString(16).slice(2),
        id: programId,
        name: programName,
        url: programUrl,
        duration: this.transformDuration(spend)
      }
    },
    _getEvents () {
      return this.events.map(({ id, name, url, duration }, index) => {
        return {
          index,
          freq: 'SECONDLY',
          spend: duration,
          programId: id,
          programName: name,
          programUrl: url
        }
      })
    },
    transformDuration (duration) {
      if (this.editable) {
        return duration
      }
      const seconds = duration % 60
      let minutes = duration / 60 | 0
      let s = ''
      if (minutes > 60) {
        let hours = minutes / 60 | 0
        s += `${hours / 24 | 0}天`
        hours %= 24
        if (hours) {
          s += `${hours}小时`
        }
        minutes %= 60
      }
      if (minutes) {
        s += `${minutes}分`
      }
      if (seconds) {
        s += `${seconds}秒`
      }
      return s
    },
    init () {
      this.record = {
        events: this.events.map(({ id, duration }) => {
          return { id, duration }
        }),
        count: this.events.length
      }
    },
    onSave () {
      this.save().then(this.init)
    },
    onAdd () {
      this.choosing = true
    },
    onChoose ({ id, name, duration, buckets, itemConfigName }) {
      this.choosing = false
      this.events.push({
        key: Math.random().toString(16).slice(2),
        id, name,
        url: `${buckets}/${itemConfigName}`,
        duration: duration || 60
      })
    },
    onView ({ id }) {
      window.open(this.$router.resolve({
        name: 'view',
        params: { id }
      }).href, '_blank')
    },
    onDel ({ name }, index) {
      this.$confirm(
        `确定移除节目 ${name}？`,
        { type: 'warning' }
      ).then(() => {
        this.events.splice(index, 1)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.c-schedule-swiper {
  color: $black;

  &__tip {
    line-height: 1;
  }

  &__list {
    display: flex;
    flex-direction: column;
    font-size: 14px;
    line-height: 1;
    overflow-y: auto;
  }

  &__list.disabled &__mover {
    visibility: hidden;
  }

  &__item {
    border: 1px solid $gray;
    border-radius: 6px;

    &.sortable-chosen {
      border-color: #c6e2ff;
      background-color: $blue--light;
    }

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

    &.readonly {
      padding-right: 10px;

      &:hover {
        color: #409eff;
        border-color: #c6e2ff;
        background-color: $blue--light;
      }

      .c-schedule-swiper__program {
        font-size: 14px;
      }
    }
  }

  &__mover {
    padding: 10px 16px;
    font-size: 18px;
    cursor: move;
  }

  &__program {
    padding: 16px 10px;
    font-size: 16px;
  }

  &__del {
    padding: 10px 16px;
    margin-left: 6px;
    font-size: 18px;
  }
}
</style>
