<template>
  <div class="mu-carousel" :style="{width:currentConfig.width}">
    <el-carousel
      ref="carousel"
      :class="'mu-carousel-'+ currentConfig.direction"
      :direction="currentConfig.currentDirection"
      :allow="currentConfig.allow"
      :height="currentConfig.height"
      :indicator-position="currentConfig.indicator"
      :interval="currentConfig.interval"
      :loop="currentConfig.loop"
      :autoplay="currentConfig.autoplay"
      :trigger="currentConfig.trigger"
      :initial-index="currentConfig.initialIndex"
      @change="handleChange">
      <template v-for="(item, index) in currentConfig.items">
        <el-carousel-item :label="currentConfig.label" :name="currentConfig.name" :key="index">
          <slot :data="item" v-if="!$scopedSlots[item.name]"></slot>
          <slot :name="item.name" :data="item" v-else></slot>
        </el-carousel-item>
      </template>
    </el-carousel>
  </div>
</template>

<script lang="ts">
  import { Component, Vue, Prop } from 'vue-property-decorator';

  type Type = 'none' | 'outside'
  type Allow = 'always' | 'never'

  interface carouselConfig {
    height?: string,
    indicator?: Type,
    width?: string,
    name?: string,
    label?: string,
    allow?: Allow,
    direction?: string,
    interval?: number,
    loop?: boolean,
    autoplay?: boolean,
    trigger?: string,
    initialIndex?: number,
    isDirTop?: boolean,
    isDirLeft?: boolean,
    currentDirection?: string,
    items?: {
      name?: string,
      label?: string,
      data?: any
    }
  }

  @Component({
    name: 'dtCarousel'
  })
  export default class extends Vue {
    @Prop({ default: () => {} }) private config!: carouselConfig;
    @Prop() private extension?: (value: any) => void;
    private defaultConfig: any = {
      height: 100,
      indicater: 'none',
      direction: "bottom",
      autoplay: false,
      currentDirection: 'horizontal'
    };

    get currentConfig() {
      const result = this.config;
      Object.keys(this.defaultConfig).forEach((key: string) => {
        if (this.config[key] === undefined) result[key] = this.defaultConfig[key];
      });
      result.currentDirection =
        (result.direction === 'left' || result.direction === 'right') ? 'vertical' : 'horizontal';
      return result;
    }

    handleChange(newval, oldval) {
      this.$emit('on-change', newval, oldval);
    }
  }
</script>

<style lang="scss" scoped>
  .el-carousel__item {
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
