import { defineComponent, h } from 'vue';

export default defineComponent({
  name: 'WidgetRenderer',
  inject: ['$engine'],
  props: {
    name: String,
    type: [String, Object],
    props: Object,
    disabled: Boolean,
    extendProps: Object,
    order: Number,
    visible: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isActive: this.visible
    };
  },
  computed: {
    component() {
      const { type, $engine } = this as any;
      const { skeleton } = $engine || {};
      if (type && skeleton) {
        return skeleton.getComponent(type);
      }
      return null;
    }
  },
  render() {
    const {
      component,
      name,
      props,
      disabled,
      extendProps,
      order,
      visible,
      isActive
    } = this;

    // 实现懒加载
    if (!isActive && visible) {
      this.isActive = true;
    }

    if (component && !disabled && isActive) {
      return h(this.component, {
        ref: name,
        name,
        extendProps,
        order,
        style: {
          display: visible ? '' : 'none'
        },
        ...props
      });
    }
    return null;
  },
  mounted() {
    const { name, $engine } = this as any;
    const { skeleton } = $engine || {};
    if (name && skeleton) {
      skeleton.widgetInstances[name] = this.$refs[name];
    }
  },
  unmounted() {
    const { name, $engine } = this as any;
    const { skeleton } = $engine || {};
    if (name && skeleton) {
      delete skeleton.widgetInstances[name];
    }
  }
});
