<template>
  <div class="el-bio-notice" @click="$emit('click', $event)">
    <bio-icon v-if="leftIcon" :name="leftIcon"/>

    <div class="bio-notice__wrap" ref="wrap">
      <div
        ref="content"
        class="bio-notice__content"
        v-html="content"
        :style="{
          transform: offset ? 'translateX(' + offset + 'px)' : '',
          transitionDuration : duration + 's'
        }"
        @transitionend="onTransitionEnd"/>
    </div>
  </div>
</template>

<script>
import {isDef, raf, doubleRaf} from '../../../src/utils/bioknow/utils';

export default {
  name: 'BioNotice',
  props: {
    leftIcon: {
      type: String,
      default: 'notice'
    },

    content: {
      required: true
    },

    scrollable: {
      type: Boolean,
      default: null
    },

    delay: {
      type: [Number, String],
      default: 1
    },

    speed: {
      type: [Number, String],
      default: 60
    }
  },

  data() {
    return {
      show: true,
      offset: 0,
      duration: 0,
      wrapWidth: 0,
      contentWidth: 0,
      startTimer: null
    };
  },

  watch: {
    scrollable: 'start',
    text: {
      handler: 'start',
      immediate: true
    }
  },

  created() {
    this.start();
  },

  activated() {
    this.start();
  },

  methods: {
    reset() {
      this.offset = 0;
      this.duration = 0;
      this.wrapWidth = 0;
      this.contentWidth = 0;
    },

    start() {
      let _this3 = this;

      let delay = isDef(this.delay) ? this.delay * 1000 : 0;
      this.reset();
      clearTimeout(this.startTimer);

      this.startTimer = setTimeout(function() {
        // eslint-disable-next-line one-var
        let _this3$$refs = _this3.$refs,
          wrap = _this3$$refs.wrap,
          content = _this3$$refs.content;

        if (!wrap || !content || _this3.scrollable === false) {
          return;
        }

        let wrapWidth = wrap.getBoundingClientRect().width;
        let contentWidth = content.getBoundingClientRect().width;

        if (_this3.scrollable || contentWidth > wrapWidth) {
          doubleRaf(function() {
            _this3.offset = -contentWidth;
            _this3.duration = contentWidth / _this3.speed;
            _this3.wrapWidth = wrapWidth;
            _this3.contentWidth = contentWidth;
          });
        }
      }, delay);
    },

    onTransitionEnd() {
      let _this2 = this;

      this.offset = this.wrapWidth;
      this.duration = 0; // wait for Vue to render offset
      // using nextTick won't work in iOS14

      raf(function() {
        // use double raf to ensure animation can start
        doubleRaf(function() {
          _this2.offset = -_this2.contentWidth;
          _this2.duration = (_this2.contentWidth + _this2.wrapWidth) / _this2.speed;

          _this2.$emit('replay');
        });
      });
    }
  },

  destroyed() {
    clearTimeout(this.startTimer);
  }
};
</script>
