<template>
  <div class="s-modal" v-show="show">
    <div class="s-modal__mask" v-show="mask"></div>
    <div class="s-modal__content">
      <div class="s-modal__body">
        <div class="s-modal__icon" v-if="type">
          <Icon :icon="typeMap[type]" :class="type" />
        </div>
        <div class="s-modal__info">
          <h5 class="s-modal__title" v-if="title">{{ title }}</h5>
          <p class="s-modal__text" v-html="text" v-if="text"></p>
          <div class="s-modal__slot">
            <slot></slot>
          </div>
        </div>
      </div>
      <div class="s-modal__action" v-if="btns">
        <Button @click="quit" v-if="btns > 1">{{ quitTxt }}</Button
        ><Button @click="ok" type="primary">{{ okTxt }}</Button>
      </div>
    </div>
  </div>
</template>

<script>
import Button from '../../button';
import Icon from '../../icon';
export default {
  name: 's-modal',
  components: { Button, Icon },
  props: {
    btns: {
      type: Number,
      default: 2,
    },
    type: {
      type: String,
      default: '',
    },
    title: {
      type: String,
      default: '',
    },
    text: {
      type: String,
      default: '',
    },
    okTxt: {
      type: String,
      default: '确定',
    },
    quitTxt: {
      type: String,
      default: '取消',
    },
    mode: {
      type: String,
      default: 'template',
    },
    async: {
      type: Boolean,
      default: false,
    },
    mask: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      show: false,
      typeMap: {
        info: 'solid-notice',
        success: 'solid-success',
        error: 'solid-close',
        warning: 'solid-notice',
      },
    };
  },
  methods: {
    open() {
      this.show = true;
    },
    close() {
      this.$emit('close');
      if (this.mode === 'template') {
        this.show = false;
      } else {
        this.$el.remove();
      }
    },
    cb(fn, emit) {
      if (this.async) {
        return new Promise(resolve => {
          this.$emit(emit, resolve);
          typeof fn === 'function' && fn(resolve);
        }).then(() => {
          this.close();
        });
      } else {
        this.$emit(emit);
        typeof fn === 'function' && fn();
        this.close();
      }
    },
    quit() {
      this.$emit('quit');
      this.close();
    },
    ok() {
      this.cb(this.onOk, 'ok');
    },
  },
};
</script>
