<template>
  <div class="uif-notice" :class="classes" @click="stopDuration">
    <div class="uif-notice-header">
      <u-icon class="uif-notice-icon" :type="icons[type]"></u-icon>
      <h2 class="uif-notice-title">{{title}}</h2>
      <u-circle :visible="Boolean(duration && timer)" class="uif-notice-close" :rate="rate" :size="32" :strokeWidth="5">
        <u-icon scene="action" type="x" @click="handleClose"></u-icon>
      </u-circle>
    </div>
    <u-base-render v-if="isRender" :render="desc" :close="handleClose"></u-base-render>
    <div class="uif-notice-desc" v-else-if="desc">{{desc}}</div>
    <div class="uif-notice-confirm" v-if="confirm">
      <u-button type="primary" @click="handleConfirm">{{confirm}}</u-button>
    </div>
  </div>
</template>
<script>
import {oneOf, isFunction} from '@uif/core/lib/utils/assist'
import UCircle from '@uif/core/lib/components/circle'
import UIcon from '@uif/core/lib/components/icon'
import UButton from '@uif/core/lib/components/button'
import UBaseRender from '@uif/core/lib/components/base-render'
import {delay, loop} from '@uif/core/lib/utils/delay'

export default {
  components: {UIcon, UButton, UCircle, UBaseRender},
  props: {
    type: {
      validator (value) {
        return oneOf(value, ['info', 'success', 'warning', 'error'])
      },
      default: 'success'
    },
    title: {
      type: String,
      default: ''
    },
    desc: {
      type: [String, Function],
      default: ''
    },
    duration: {
      type: Number,
      default: 2.5
    },
    confirm: {
      type: String,
      default: ''
    },
    onConfirm: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
      icons: {
        info: 'circle-info-filled',
        success: 'circle-checked-filled',
        warning: 'circle-alert-filled',
        error: 'circle-x-filled'
      },
      rate: 0,
      timer: 0
    }
  },
  computed: {
    isRender () {
      return isFunction(this.desc)
    },
    classes () {
      return [
        'uif-notice-' + this.type,
        {
          'uif-notice-long': this.desc
        }
      ]
    }
  },
  methods: {
    // 启动定时
    startDuration () {
      if (this.duration !== 0) {
        this.timer = +new Date() + this.duration * 1000
        loop(100, () => {
          if (!this.timer) return true
          const nearly = (this.timer - +new Date()) / (this.duration * 1000)
          this.rate = Math.min(1 - nearly, 1)
          return this.rate >= 1
        }).then(() => {
          if (this.timer) {
            delay(200).then(() => {
              this.handleClose()
            })
          }
        })
      }
    },
    // 取消定时
    stopDuration () {
      this.timer = 0
    },
    handleClose () {
      this.$emit('close')
    },
    handleConfirm () {
      this.handleClose()
      if (this.onConfirm) {
        this.onConfirm()
      }
    }
  },
  mounted () {
    this.startDuration()
  },
  beforeDestroy () {
    this.timer = 0
  }
}
</script>
