import _Promise from "@babel/runtime-corejs2/core-js/promise";
import _Object$keys from "@babel/runtime-corejs2/core-js/object/keys";
import "core-js/modules/web.dom.iterable";
import _Object$assign from "@babel/runtime-corejs2/core-js/object/assign";

/*
 * @Author: lijianzhang
 * @Date: 2019-02-18 17:40:00
 * @Last Modified by: lijianzhang
 * @Last Modified time: 2019-02-27 00:56:50
 * 将vue组建建改成Promise方法渲染的形式
 */
import Vue from 'vue';
export default function render(component, defaultData) {
  const VueComponent = Vue.extend(component);
  return (data = {}) => {
    let vm = new VueComponent();
    const {
      on,
      onOk,
      onCancel,
      ...other
    } = data;

    _Object$assign(vm, defaultData, other);

    if (on) {
      _Object$keys(on).forEach(key => {
        vm.$on(key, on[key]);
      });
    }

    vm.run = () => {
      vm.$mount();
      vm.visible = true;
      let done = false;
      return new _Promise(resolve => {
        vm.onOk = async data => {
          if (onOk) {
            const res = await onOk(data);
            if (res === false) return;
          }

          done = true;
          resolve(data || true);
        };

        vm.onCancel = async () => {
          if (onCancel) {
            const res = await onCancel();
            if (res === false) return;
          }

          done = true;
          resolve(false);
        };

        vm.afterClose = () => {
          if (done) vm.$destroy();
        };
      }).then(v => {
        if (!vm.visible) vm.$destroy();
        vm.visible = false;
        return v;
      });
    };

    vm.update = (data = {}) => {
      _Object$assign(vm, data);
    };

    return vm;
  };
}