<template>
  <view>
    <!--  confirm modal  -->
    <u-modal :value="alertType === 'confirm'" @confirm="onConfirm" :content="confirmModal.content" />
    <!--  prompt modal  -->
    <u-modal :value="alertType === 'prompt'" :content="promptModal.content" :confirm-text="promptModal.confirmText" :cancel-text="promptModal.cancelText" :show-cancel-button="true" @confirm="onConfirm" @cancel="onCancel" />
  </view>
</template>

<script lang="ts">
import Vue from 'vue';
import { ConfirmOption, offConfirm, offPrompt, PromptOption, subscribeConfirm, subscribePrompt } from '@/components/alert/alert';

type AlertType = null | 'confirm' | 'prompt';

export default Vue.extend({
  name: 'Alerts',
  data() {
    return {
      alertType: null as AlertType,
      promise: {
        resolve: null as any,
        reject: null as any,
      },
      confirmModal: {
        content: '',
      },
      promptModal: {
        content: '',
        confirmText: '',
        cancelText: '',
      },
    };
  },
  mounted() {
    subscribeConfirm(this.onConfirmOpen.bind(this));
    subscribePrompt(this.onPromptOpen.bind(this));
  },
  beforeDestroy() {
    offConfirm();
    offPrompt();
  },
  methods: {
    onConfirmOpen(value?: ConfirmOption): Promise<undefined> {
      if (!value) {
        throw new Error('Alert Option not provided!');
      } else {
        this.alertType = 'confirm';
        this.confirmModal.content = value.content;
        return new Promise((resolve) => {
          this.promise.resolve = resolve;
        });
      }
    },
    onPromptOpen(value?: PromptOption): Promise<undefined> {
      if (!value) {
        throw new Error('Prompt Option not provided!');
      } else {
        this.alertType = 'prompt';
        this.promptModal.content = value.content;
        this.promptModal.confirmText = value.confirmText ? value.confirmText : '确认';
        this.promptModal.cancelText = value.cancelText ? value.cancelText : '取消';
        return new Promise((resolve, reject) => {
          this.promise.resolve = resolve;
          this.promise.reject = reject;
        });
      }
    },
    onConfirm() {
      if (this.promise.resolve !== null) {
        this.promise.resolve();
      }
      this.onCloseAlert();
    },
    onCancel() {
      if (this.promise.reject !== null) {
        this.promise.reject();
      }
      this.onCloseAlert();
    },
    onCloseAlert() {
      // 重置全部状态
      const initialState = (this.$options as any).data();
      Object.keys(this.$data).forEach((key: string) => {
        (this as any)[key] = initialState[key];
      });
    },
  },
});
</script>
