<template>
  <schedule-wrapper
    class="c-schedule-swiper"
    :name="name"
    :hide-header="hideHeader"
    :editable="editable"
    :dirty="dirty"
    @submit="submit"
    @save="onSave"
  >
    <template v-if="editable">
      <div class="l-flex__auto l-flex">
        <div class="l-flex__none l-flex--row has-top-padding">
          <schema-table
            ref="table"
            class="c-schedule-swiper__table"
            :schema="programSchema"
            @row-click="onRowClick"
            @selection-change="onSelectionChange"
          />
        </div>
        <div class="l-flex__none l-flex--row c-schedule-swiper__btn">
          <el-button
            type="primary"
            :disabled="!programs.length"
            @click="onAdd"
          >
            <i class="el-icon-arrow-right" />
          </el-button>
        </div>
        <el-empty
          v-if="isEmpty"
          class="l-flex__auto l-flex--row center"
          description="请添加节目"
        />
        <draggable
          v-else
          v-model="scheduleOptions.events"
          class="l-flex__auto c-schedule-swiper__list has-padding--v"
          :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 u-color--info">持续时间(秒)：</span>
            <el-input-number
              v-model="program.duration"
              class="l-flex__none c-schedule-swiper__seconds"
              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>
      </div>
    </template>
    <template v-else>
      <el-empty
        v-if="isEmpty"
        description="暂无节目"
      />
      <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 { getPrograms } from '@/api/program'
import { State } from '@/constant'
import scheduleMixin from '../mixins/schedule'
import Draggable from 'vuedraggable'
import ScheduleWrapper from '../components/ScheduleWrapper'

export default {
  name: 'ScheduleSwiper',
  components: {
    Draggable,
    ScheduleWrapper
  },
  mixins: [scheduleMixin],
  data () {
    return {
      record: null,
      programs: [],
      programSchema: {
        pagination: { small: true, layout: 'prev,pager,next' },
        condition: { status: State.AVAILABLE, resolutionRatio: this.ratio, name: '' },
        list: getPrograms,
        filters: [
          { key: 'name', type: 'search', placeholder: '节目名称' }
        ],
        cols: [
          { type: 'selection' },
          { prop: 'name', label: '节目名称' },
          { type: 'invoke', width: 80, render: [
            { label: '查看', on: this.onView }
          ] }
        ]
      }
    }
  },
  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
    }
  },
  created () {
    this.init()
  },
  methods: {
    transformEvents (events) {
      return events.sort((a, b) => a.index - b.index).map(this.transformEvent)
    },
    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)
    },
    onRowClick (row) {
      this.$refs.table.getInst().toggleRowSelection(row)
    },
    onSelectionChange (programs) {
      this.programs = programs
    },
    onAdd () {
      this.programs.forEach(this.add)
      this.$refs.table.getInst().clearSelection()
    },
    add ({ id, name, duration, buckets, itemConfigName }) {
      this.events.push({
        key: Math.random().toString(16).slice(2),
        id, name,
        url: `${buckets}/${itemConfigName}`,
        duration: duration || 60
      })
    },
    onView ({ id }) {
      this.$viewProgram(id)
    },
    onDel (event, index) {
      this.events.splice(index, 1)
    }
  }
}
</script>

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

  &__table {
    width: 318px;
    align-self: flex-start;
    max-height: 100%;
  }

  &__btn {
    padding: 0 $spacing $spacing;
    margin: 0 $spacing;
    border-left: 1px solid $border;
    border-right: 1px solid $border;
  }

  &__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: $radius--mini;

    &.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;
  }

  &__mover + &__program {
    padding-left: 0;
  }

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

  &__seconds {
    width: 140px;
  }

  &__del {
    padding: 10px 16px;
    margin-left: 6px;
    color: $gray;
    font-size: 18px;

    &:hover {
      color: $primary;
    }
  }
}
</style>
