<template>
  <div class="toast"
       v-if="childShow">
    <div class="toast__mask"
         v-if="mask"
         @touchmove.prevent></div>
    <!-- <div class="toast__wrapper"> -->
    <div class="toast__main bk clear-fix"
         :class="{'is-icon':icon!=='',style2}">
      <div class="toast__icon"
           v-if="icon!==''">
        <div class="icon"
             :class="[icon]"></div>
      </div>
      <div class="toast__title"
           :class="[textAlignClass]">{{typeof title==='string'?title:title.text}}</div>
    </div>
    <!-- </div> -->
  </div>
</template>

<script>
export default {
  name: 'Toast',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    mask: {
      type: Boolean,
      default: true
    },
    title: {
      type: [String, Object],
      default: ''
    },
    icon: {
      type: String,
      default: ''
    },
    duration: {
      type: Number,
      default: 1500
    }
  },
  data() {
    return {
      childShow: false,
      textAlignClass: '',
      alignMap: {
        center: 'tc',
        left: '',
        right: 'tr'
      }
    };
  },
  computed: {
    // 与UI讨论之后不需要用这个样式了【已废弃】
    style2() {
      return false;
      // 超过18个字的时候
      // const n = (6 * 2) * 3;
      // return this.getLen(this.getText()) > n && this.icon !== '';
    }
  },
  watch: {
    show: {
      handler(val, oldVal) {
        this.childShow = val;
      },
      immediate: true
    },
    title: {
      handler(val, oldVal) {
        if (val === null) {
          this.title = {};
        }
        if (typeof this.title !== 'string' && val) {
          this.textAlignClass = this.alignMap[this.title ? this.title.textAlign : 'center'];
        }
      },
      immediate: true
    }
  },
  created() {
  },
  mounted() {
    setTimeout(() => {
      this.$emit('on-hide');
      this.success && this.success();
      this.childShow = false;
    }, this.duration);
  },
  methods: {
    getText() {
      const { title } = this;
      return typeof title === 'string' ? title : title.text;
    },
    getLen(str) {
      if (str === null) return 0;
      if (typeof str !== 'string') {
        str += '';
      }
      /* eslint-disable no-control-regex */
      return str.replace(/[^\x00-\xff]/g, '01').length;
    }
  }
};
</script>

