<template>
    <div :class="['vui-cutover',{'vui-cutover-back':back}]">
        <transition :name="`vui-cutover-${type}`" v-bind="$attrs">
            <slot :style-obj="styleObj"></slot>
        </transition>
    </div>
</template>

<style>
    .vui-cutover {
        overflow: hidden;
    }

    .vui-cutover > :nth-child(1),
    .vui-cutover > :nth-child(2) {
        float: left;
        box-sizing: border-box;
        width: 100%;
    }

    .vui-cutover > :nth-child(2) {
        margin-left: -100%;
    }

    /*fade效果*/
    .vui-cutover-fade-enter-active,
    .vui-cutover-fade-leave-active {
        transition-property: opacity;
    }

    .vui-cutover-fade-enter,
    .vui-cutover-fade-leave-active {
        opacity: 0;
    }

    /*cover效果*/
    .vui-cutover-cover-enter-active,
    .vui-cutover-cover-leave-active {
        transition-property: opacity, transform;
    }

    .vui-cutover:not(.vui-cutover-back) .vui-cutover-cover-enter {
        transform: translate3d(100%, 0, 0);
    }

    .vui-cutover:not(.vui-cutover-back) .vui-cutover-cover-leave-active {
        opacity: .5;
    }

    .vui-cutover-back .vui-cutover-cover-enter {
        opacity: .5;
    }

    .vui-cutover-back .vui-cutover-cover-leave-active {
        position: relative;
        z-index: 1;
        transform: translate3d(100%, 0, 0);
    }
</style>

<script>
  export default {
    name: 'cutover',
    props: {
      type: { // 切换类型
        type: String,
        default: 'fade'
      },
      duration: {
        type: Number,
        default: 400
      },
      checkBack: { // 当作页面转场动画时，返回时动效是否相反，且此时要配合vue-router使用，其它场景使用时不要设置该属性
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        back: false // 是不是返回
      }
    },
    computed: {
      styleObj () {
        return {
          transitionDuration: `${this.duration}ms`
        }
      }
    },
    watch: {
      $route () {
        if (!window.history.state || !window.history.state.vuiCutoverTime) { // 新建历史记录，前进
          window.history.replaceState(Object.assign({}, window.history.state || {}, {
            vuiCutoverTime: Date.now()
          }), '')
          this.back = false
        } else if (!this.time || window.history.state.vuiCutoverTime === this.time) { // 刷新或者replace
          this.back = false
        } else if (window.history.state.vuiCutoverTime < this.time) { // 后退
          this.back = this.checkBack
        } else { // 前进
          this.back = false
        }

        this.time = window.history.state.vuiCutoverTime
      }
    }
  }
</script>
