<template>
  <div>
    <div class="midea-overlay" ref="midea-overlay" v-if="show_" @click="overlayClicked" :style="overlayStyle"></div>
  </div>
</template>

<style scoped>
.midea-overlay {
  /* width: 750px; */
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1000;
}
</style>

<script>
import ColmoMixin from '../../mixins/colmo'
import DiabloMixin from '../../mixins/diablo'
const animation = weex.requireModule('animation')
export default {
  mixins: [ColmoMixin, DiabloMixin],
  props: {
    show: {
      type: Boolean,
      default: true
    },
    hasAnimation: {
      type: Boolean,
      default: true
    },
    duration: {
      type: [Number, String],
      default: 300
    },
    timingFunction: {
      type: Array,
      default: () => ['ease-in', 'ease-out']
    },
    opacity: {
      type: [Number, String],
      default: undefined
    },
    canAutoClose: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      show_: false,
      isIOS: weex.config.env.osName == 'iOS'
    }
  },
  watch: {
    show: {
      handler(val, oldVal) {
        if (val) {
          this.show_ = true
          this.hasAnimation &&
            setTimeout(() => {
              this.appearOverlay(true)
            }, 20)
        } else {
          if (oldVal !== true) return
          this.hasAnimation && this.appearOverlay(false, this.duration, () => {})
          setTimeout(() => {
            this.show_ = false
          }, 0)
        }
      },
      immediate: true
    }
  },
  computed: {
    overlayStyle() {
      return {
        opacity: this.hasAnimation ? 0 : 1,
        backgroundColor: this._isColmo ? `rgba(21, 21, 21,${this._opacity})` : this._isDiablo ? 'rgba(0, 0, 0, 0.6)' : `rgba(30, 46, 55,${this._opacity})`
      }
    },
    _opacity() {
      if (this.opacity !== undefined) return this.opacity
      return this._isColmo ? 0.75 : 0.3
    }
  },
  methods: {
    overlayClicked(e) {
      this.canAutoClose ? this.appearOverlay(false) : this.$emit('dofOverlayBodyClicked', {})
    },
    appearOverlay(bool, duration = this.duration, cb = () => {}) {
      const { hasAnimation, timingFunction, canAutoClose } = this
      const needEmit = !bool && canAutoClose
      needEmit && this.$emit('dofOverlayBodyClicked', {})
      const overlayEl = this.$refs['midea-overlay']
      if (hasAnimation && overlayEl) {
        animation.transition(
          overlayEl,
          {
            styles: {
              opacity: bool ? 1 : this.isIOS ? 0.05 : 0
            },
            duration,
            timingFunction: timingFunction[bool ? 0 : 1],
            delay: 0
          },
          () => {
            cb()
            needEmit && this.$emit('dofOverlayBodyClicked', {})
          }
        )
      } else {
        cb()
        needEmit && this.$emit('dofOverlayBodyClicked', {})
      }
    }
  }
}
</script>
