import Vue from 'vue';
import { IModalUtil, ModalParams } from '@ibiz-template/runtime';
import { ModalConfig, ModalInstance } from 'view-design';

function convertParams(params: ModalParams): ModalConfig {
  const config: IData = { ...params };
  if (config.desc) {
    config.content = config.desc;
    delete config.desc;
  }
  return config;
}

/**
 * 简洁确认操作框
 *
 * @author chitanda
 * @date 2022-08-17 16:08:52
 * @export
 * @class ModalUtil
 * @implements {IModalUtil}
 */
export class ModalUtil implements IModalUtil {
  protected modal: ModalInstance = Vue.prototype.$Modal;

  async info(params: ModalParams): Promise<void> {
    return new Promise(resolve => {
      this.modal.info({
        ...convertParams(params),
        onOk: () => {
          resolve();
        },
      });
    });
  }

  async success(params: ModalParams): Promise<void> {
    return new Promise(resolve => {
      this.modal.success({
        ...convertParams(params),
        onOk: () => {
          resolve();
        },
      });
    });
  }

  async warning(params: ModalParams): Promise<void> {
    this.modal.warning(convertParams(params));
    return new Promise(resolve => {
      this.modal.success({
        ...convertParams(params),
        onOk: () => {
          resolve();
        },
      });
    });
  }

  async error(params: ModalParams): Promise<void> {
    return new Promise(resolve => {
      this.modal.error({
        ...convertParams(params),
        onOk: () => {
          resolve();
        },
      });
    });
  }

  async confirm(params: ModalParams): Promise<boolean> {
    return new Promise(resolve => {
      this.modal.confirm({
        ...convertParams(params),
        onOk: () => {
          resolve(true);
        },
        onCancel: () => {
          resolve(false);
        },
      });
    });
  }
}
