import * as React from 'react';
import { Modal, Button, Text } from 'tea-component';
import 'tea-component/es/tea.css';

export default async function showModal({ data }) {
  const {
    title,
    content,
    showCancel,
    cancelText = '取消',
    cancelColor,
    confirmText = '确定',
    confirmColor,
    success = () => {},
    fail = () => {},
    complete = () => {},
  } = data;

  return new Promise((resolve) => {
    const base = { cancel: false, confirm: false, content: null };

    const modal = Modal.show({
      caption: title,
      children: (
        <>
          <Modal.Body>{content}</Modal.Body>
          <Modal.Footer>
            <Button
              // type="primary"
              onClick={() => {
                resolve({ ...base, confirm: true });
                modal.destroy();
              }}
            >
              <Text style={{ color: confirmColor }}>{confirmText}</Text>
            </Button>
            {showCancel && (
              <Button
                onClick={() => {
                  resolve({ ...base, cancel: true });
                  modal.destroy();
                }}
              >
                <Text style={{ color: cancelColor }}>{cancelText}</Text>
              </Button>
            )}
          </Modal.Footer>
        </>
      ),
      onClose: () => {
        resolve({ ...base, cancel: true });
        modal.destroy();
      },
    });
  }).then(
    (res) => {
      success && success(res);
      return res;
    },
    (e) => {
      // console.log(e);
      fail && fail();
      complete && complete();
      throw e;
    }
  );
}
