<template>
  <div class="n-notice-item" :class="classes" @click="stopDuration">
    <div class="n-notice-header">
      <n-icon v-if="icon" class="n-notice-icon" :size="notify ? 16 : 20" :type="icon"></n-icon>
      <h2 class="n-notice-title ellipsis">{{title}}</h2>
      <n-circle :rate="rate" :size="20" :strokeWidth="8" @click.native="onDestroy">
        <n-icon scene="gray" size="12" type="x"></n-icon>
      </n-circle>
    </div>
    <n-builder v-if="isRender" class="n-notice-builder" :name="info" :close="onDestroy"></n-builder>
    <div class="n-notice-content" v-else-if="info">{{info}}</div>
    <div class="n-notice-footer" v-if="confirmText">
      <n-button type="primary" @click="onConfirmClick">{{confirmText}}</n-button>
    </div>
  </div>
</template>
<script>
import NCircle from '@uif/next/lib/components/circle'
import NIcon from '@uif/next/lib/components/icon'
import NButton from '@uif/next/lib/components/button'
import NBuilder from '@uif/next/lib/components/builder'
import {prop, isFunction, delay, loop} from '@uif/next/lib/utils/tools'

const icons = new Map([
  ['info', 'convention'],
  ['success', 'prosperity'],
  ['warning', 'hint'],
  ['error', 'notice']
])

export default {
  components: {NIcon, NButton, NCircle, NBuilder},
  props: {
    // 弱通知 用于系统消息等
    notify: prop.boolean(),
    // 类型 icon
    type: prop.string(),
    // 消息标题
    title: prop.string(),
    // 文本 或 render 函数
    info: {
      type: [String, Function],
      default: ''
    },
    // 自动关闭延时，不关闭可以写0
    duration: prop.number(),
    // 确认按钮文本
    confirmText: prop.string(),
    // 确认按钮回调事件
    onConfirm: prop.function(null)
  },
  data () {
    return {
      rate: 0,
      timer: 0
    }
  },
  computed: {
    icon ({type}) {
      return icons.get(type)
    },
    isRender ({info}) {
      return isFunction(info)
    },
    classes ({notify, type, icon, duration, timer}) {
      return {
        'n-notice-notify': notify,
        'n-notice-notification': !notify,
        [`n-notice-type-${type}`]: type,
        'n-notice-has-icon': icon,
        'n-notice-hidden-circle': !duration || !timer
      }
    }
  },
  mounted () {
    if (this.duration !== 0) {
      this.startDuration()
    }
  },
  beforeDestroy () {
    this.timer = 0
  },
  methods: {
    // 启动定时
    startDuration () {
      this.timer = +new Date() + this.duration * 1000
      loop(100, () => {
        if (this.timer) {
          this.rate = Math.min(1 - (this.timer - +new Date()) / (this.duration * 1000), 1)
          return this.rate >= 1
        }
        return true
      }).then(() => {
        if (this.timer) {
          delay(200).then(() => {
            this.onDestroy()
          })
        }
      })
    },
    onDestroy () {
      this.$emit('destroy')
    },
    // 取消定时
    stopDuration () {
      this.timer = 0
    },
    onConfirmClick () {
      this.onDestroy()
      if (this.onConfirm) {
        this.onConfirm()
      }
    }
  }
}
</script>
