import sdLoading from '../pages/sd-loading.vue'
/**
 * 把一个组件包装成异步加载，增加Loading提示等
 * @param {function} getComponentFn
 * @returns {function}
 */
function asyncComponent(getComponentFn) {
  if (typeof getComponentFn !== 'function') {
    throw new Error('asyncComponent的参数必须是function，不能直接传import进来的组件')
  }

  let componentPromise

  // 获取异步组件信息，返回一个闭包函数
  function getComponentInfo() {
    return (componentPromise || getComponentFn()).then((module) => {
      return module.default
    })
  }
  const AsyncHandler = () => {
    return {
      component: componentPromise || getComponentFn(),
      loading: sdLoading,
      delay: 200,
    }
  }

  return () =>
    Promise.resolve({
      functional: true,
      getComponentInfo,
      render(h, { data, children }) {
        // Transparently pass any props or children
        // to the view component.
        return h(AsyncHandler, data, children)
      },
    })
}

export default asyncComponent
