import * as React from 'react';
import { observer } from 'mobx-react-lite';
import { observable, autorun, reaction, runInAction } from 'mobx';
import { AppRender } from '/src/handlers/RenderWrapper';
import {
  createWidgets,
  retryDataBinds,
  WidgetsContext,
  bindFuncObj,
  createComputed,
  resolveComponentProps,
} from '/src/utils/index';
import getStateFn from './lowcode/state.js';
import computed from './lowcode/computed.js';
import lifecycle from './lowcode/lifecycle.js';
// import i18n from '@tcwd/weapps-sdk/lib/i18n'

import componentAPI from './lowcode/index';
import { get } from 'lodash-es';

import handler$getColClass from './lowcode/handler/getColClass.js';

import handler$getColVisible from './lowcode/handler/getColVisible.js';

// Import Components outof sandbox

import gsdH5React from '/src/libraries/gsd-h5-react@0.0.70/web/index.js';
const { Slot: GsdH5ReactSlot } = gsdH5React.components;

import CLOUDBASESTANDARDCol from '/src/libraries/CLOUDBASE_STANDARD@1634202837896/components/Col';

import CLOUDBASESTANDARDRow from '/src/libraries/CLOUDBASE_STANDARD@1634202837896/components/Row';

const { Container: GsdH5ReactContainer } = gsdH5React.components;

import * as constObj from '../../libCommonRes/const';
import * as toolsObj from '../../libCommonRes/tools';

import './lowcode/style.css';

const libCode = 'CLOUDBASE_STANDARD';

class CompositeCompWrapper extends React.Component {
  $WEAPPS_COMP = {};

  componentDidUpdate() {
    runInAction(() => {
      const { data } = this.props;
      for (let prop in data) {
        // 更新 propsData
        if (typeof data[prop] !== 'function') {
          this.propsData[prop] = data[prop];
        }
      }
    });
  }

  constructor(props) {
    super(props);

    this.compConfig = {};

    // Import Components in sandbox

    this.virtualFields = Object.assign({}, props.pageVirtualFields || {}, {
      'gsd-h5-react:Slot': (props) => (
        <GsdH5ReactSlot {...resolveComponentProps(props, 1)} />
      ),

      'CLOUDBASE_STANDARD:Col': (props) => (
        <CLOUDBASESTANDARDCol {...resolveComponentProps(props, 0)} />
      ),

      'CLOUDBASE_STANDARD:Row': (props) => (
        <CLOUDBASESTANDARDRow {...resolveComponentProps(props, 0)} />
      ),

      'gsd-h5-react:Container': (props) => (
        <GsdH5ReactContainer {...resolveComponentProps(props, 1)} />
      ),
    });

    // 挂载给到 $comp.props.events 使用
    this.events = [].reduce((obj, trigger) => {
      obj[trigger] = (eventData, domEvent) => {
        this.props.emit(trigger, eventData, domEvent);
        this.node._listeners &&
          this.node._listeners.emit(trigger, eventData, domEvent);
      };
      return obj;
    }, {});
    this.handler = this.$WEAPPS_COMP.handler = {
      getColClass: handler$getColClass.bind(this),

      getColVisible: handler$getColVisible.bind(this),
    };
    const widgetContext = {
      id74: {
        name: 'slot0',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id62',
      },
      id62: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id75: {
        name: 'slot1',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id63',
      },
      id63: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id76: {
        name: 'slot2',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id64',
      },
      id64: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id77: {
        name: 'slot3',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id65',
      },
      id65: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id78: {
        name: 'slot4',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id66',
      },
      id66: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id79: {
        name: 'slot5',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id67',
      },
      id67: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id80: {
        name: 'slot6',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id68',
      },
      id68: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id81: {
        name: 'slot7',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id69',
      },
      id69: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id82: {
        name: 'slot8',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id70',
      },
      id70: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id83: {
        name: 'slot9',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id71',
      },
      id71: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id84: {
        name: 'slot10',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id72',
      },
      id72: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id85: {
        name: 'slot11',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id73',
      },
      id73: {
        default: '',
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Col',
        _parentId: 'id61',
      },
      id61: {
        child: '',
        reverse: false,
        flexWrap: 'wrap',
        alignItems: 'stretch',
        justifyContent: 'flex-start',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Row',
        _parentId: 'id60',
      },
      id60: {
        title: '',
        _visible: true,
        style: {},
        classList: [
          'lcap-grid-layout',
          'wa-comp-CLOUDBASE_STANDARD-GridLayout',
        ],
        widgetType: 'gsd-h5-react:Container',
      },
    };
    const dataBinds = (this._dataBinds = {
      id62: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(0);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(0);
        },
      },
      id63: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(1);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(1);
        },
      },
      id64: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(2);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(2);
        },
      },
      id65: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(3);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(3);
        },
      },
      id66: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(4);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(4);
        },
      },
      id67: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(5);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(5);
        },
      },
      id68: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(6);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(6);
        },
      },
      id69: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(7);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(7);
        },
      },
      id70: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(8);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(8);
        },
      },
      id71: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(9);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(9);
        },
      },
      id72: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(10);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(10);
        },
      },
      id73: {
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
        gutterY: () => this.$WEAPPS_COMP.props.data.rowGutter,
        classNameType: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColClass(11);
        },
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.handler.getColVisible(11);
        },
      },
      id61: {
        col: (forItems) => {
          const $for = forItems;
          return (
            this.$WEAPPS_COMP.props.data.mobileLayout === 'vertical' &&
            (app.platform === 'MP' || window.innerWidth < 1024)
          );
        },
        gutter: () => this.$WEAPPS_COMP.props.data.gutter,
      },
    });
    this.componentSchema = {
      type: 'object',
      properties: {
        id60: {
          key: 'id60',
          'x-component': 'gsd-h5-react:container',
          'x-props': {
            sourceKey: 'gsd-h5-react:Container',
            customDataForm: {},
            staticResourceAttribute: [],
            classNameList: [
              'lcap-grid-layout',
              'wa-comp-CLOUDBASE_STANDARD-GridLayout',
            ],
          },
          'x-index': 0,
          emitEvents: [
            'tap',
            'longpress',
            'touchstart',
            'touchmove',
            'touchcancel',
            'touchend',
          ],
          properties: {
            id61: {
              key: 'id61',
              'x-component': 'cloudbase_standard:row',
              'x-props': {
                sourceKey: 'CLOUDBASE_STANDARD:Row',
                customDataForm: {},
                staticResourceAttribute: [],
              },
              'x-index': 0,
              emitEvents: [],
              properties: {
                child: {
                  key: 'child',
                  properties: {
                    id62: {
                      key: 'id62',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      'x-index': 0,
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id74: {
                              key: 'id74',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id63: {
                      key: 'id63',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id75: {
                              key: 'id75',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id64: {
                      key: 'id64',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id76: {
                              key: 'id76',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id65: {
                      key: 'id65',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id77: {
                              key: 'id77',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id66: {
                      key: 'id66',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id78: {
                              key: 'id78',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id67: {
                      key: 'id67',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id79: {
                              key: 'id79',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id68: {
                      key: 'id68',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id80: {
                              key: 'id80',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id69: {
                      key: 'id69',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id81: {
                              key: 'id81',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id70: {
                      key: 'id70',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id82: {
                              key: 'id82',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id71: {
                      key: 'id71',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id83: {
                              key: 'id83',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id72: {
                      key: 'id72',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id84: {
                              key: 'id84',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 1,
                            },
                          },
                        },
                      },
                    },
                    id73: {
                      key: 'id73',
                      'x-component': 'cloudbase_standard:col',
                      'x-props': {
                        sourceKey: 'CLOUDBASE_STANDARD:Col',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      emitEvents: ['tap'],
                      properties: {
                        default: {
                          key: 'default',
                          properties: {
                            id85: {
                              key: 'id85',
                              'x-component': 'gsd-h5-react:slot',
                              'x-props': {
                                sourceKey: 'gsd-h5-react:Slot',
                                customDataForm: {},
                                staticResourceAttribute: [],
                              },
                              'x-index': 0,
                            },
                          },
                        },
                      },
                    },
                  },
                },
              },
            },
          },
        },
      },
    };

    const defaultProps = {
      slot0: '',
      slot1: '',
      slot2: '',
      slot3: '',
      slot4: '',
      slot5: '',
      slot6: '',
      slot7: '',
      slot8: '',
      slot9: '',
      gutter: 20,
      slot10: '',
      slot11: '',
      rowGutter: 20,
      columnRatio: '3:3:3:3',
      mobileLayout: 'horizontal',
    };
    this.propsData = observable(
      Object.assign({}, defaultProps, this.props.data || {})
    );
    this.$WEAPPS_COMP.lib = { const: constObj, tools: toolsObj };
    /*
    this.i18n = this.$WEAPPS_COMP.i18n = {
      ...i18n,
      t (key, data) {
        return i18n.t(libCode + ':' + key, data)
      },
    }
    */
    this.$WEAPPS_COMP.props = {
      ...this.props,
      events: this.events,
      data: this.propsData,
    };

    this.state = this.$WEAPPS_COMP.state = observable(getStateFn.bind(this)());
    this.computed = this.$WEAPPS_COMP.computed = createComputed(computed, this);
    this.node = this.$WEAPPS_COMP.node = this.createWidgetNode(this) || {};
    this.initPublicMethods();

    this.widgets = this.$WEAPPS_COMP.widgets = createWidgets(
      widgetContext,
      dataBinds
    );
    // widgets 内的 dataBinds 可能需要关联 widgets，需要重新执行 dataBinds
    retryDataBinds();
    Object.keys(this.widgets || {}).forEach((widgetId) => {
      // 将实例 ownerWidget 挂到内部组件上。内部组件就可以通过 $comp.node.ownerWidget 获取到所在的组件实例
      const node = this.widgets[widgetId];
      if (Array.isArray(node)) {
        node.forEach((item) => {
          item.ownerWidget = this.node;
          item.getOwnerWidget = () => this.node;
        });
      } else {
        node.ownerWidget = this.node;
        node.getOwnerWidget = () => this.node;
      }
      // this.widgets[widgetId].ownerWidget = this.node
      // this.widgets[widgetId].getOwnerWidget = () => this.node
    });

    this.pageListenerInstances = [];
    this.createCompAPI(this);
  }

  // publicMthods 挂载内部，使用 $comp.api。挂载到外部使用 $comp.node.api
  initPublicMethods() {
    const publicMethods = componentAPI.publicMethods || {};
    Object.keys(publicMethods).map((fnName) => {
      const bindFunc = publicMethods[fnName].bind(this);
      this[fnName] = bindFunc;
      this.$WEAPPS_COMP[fnName] = bindFunc;
      if (this.node) this.node[fnName] = bindFunc;
    });
  }

  // 创建自身节点
  createWidgetNode(compThis) {
    // 当为数组时，需要判断自己属于 widgets 的哪一项
    const { compositeParent, forIndexes, id } = compThis.props;
    let widgetData = compositeParent.$WEAPPS_COMP
      ? compositeParent.$WEAPPS_COMP.widgets[id]
      : compositeParent.$page.widgets[id];
    if (Array.isArray(widgetData)) {
      widgetData = widgetData.length > 0 ? get(widgetData, forIndexes) : {};
    }
    widgetData = widgetData || {};
    Object.assign(
      widgetData,
      {
        getConfig: () => compThis.compConfig,
      },
      bindFuncObj(componentAPI.publicMethods || {}, compThis)
    );

    return widgetData;
  }

  createCompAPI(compThis) {
    compThis.$WEAPPS_COMP = {
      _dataBinds: compThis._dataBinds,
      compConfig: compThis.compConfig,
      widgets: compThis.widgets,
      node: compThis.node,
      handler: compThis.handler,
      lib: { const: constObj, tools: toolsObj },
      // i18n: compThis.i18n,
      get props() {
        return {
          ...compThis.props,
          events: compThis.events,
          data: compThis.propsData,
        };
      },
      get state() {
        return compThis.state;
      },
      get computed() {
        return compThis.computed;
      },
    };
  }

  initWatchMethods() {
    const {
      watch = {},
      watchState = {},
      watchWidget = {},
      watchEffects = {},
    } = componentAPI;
    const _this = this;
    const weappInst = _this.$WEAPPS_COMP;

    // # watch effect
    this.watchEffectDisposers = Object.keys(watchEffects).map((fnName) => {
      return autorun(watchEffects[fnName].bind(this));
    });
    const disposers = this.watchEffectDisposers;

    // # watch props
    Object.keys(watch).map((key) =>
      runWatcher(parseWatcher(watch[key]), weappInst.props.data, key, 'watch')
    );

    // # watch state
    Object.keys(watchState).map((key) =>
      runWatcher(
        parseWatcher(watchState[key]),
        weappInst.state,
        key,
        'watchState'
      )
    );

    // # watch widgets
    Object.keys(watchWidget).map((key) =>
      runWatcher(
        parseWatcher(watchWidget[key]),
        weappInst.widgets,
        key,
        'watchWidgets'
      )
    );

    function runWatcher({ handler, immediate } = {}, target, key, label) {
      if (!handler) {
        console.error(
          `Invalid ${label}(${key}) of ${weappInst.node.widgetType}, watch must a function or {handler: function}`
        );
        return;
      }
      const disposer = reaction(() => get(target, key), handler.bind(_this), {
        fireImmediately: immediate,
      });
      disposers.push(disposer);
    }
  }

  componentDidMount() {
    this.initPublicMethods();
    this.initWatchMethods();

    lifecycle.onAttached && lifecycle.onAttached.bind(this)();
    lifecycle.onReady && lifecycle.onReady.bind(this)();
  }

  componentWillUnmount() {
    if (this.watchEffectDisposers) {
      this.watchEffectDisposers.forEach((disposer) => disposer());
      this.watchEffectDisposers = null;
    }
    this.node._listeners && this.node._listeners.clear();
    lifecycle.onDetached && lifecycle.onDetached.bind(this)();
  }

  render() {
    return (
      <WidgetsContext.Provider value={{ parent: this }}>
        <AppRender
          className={this.props.className}
          virtualFields={this.virtualFields}
          componentSchema={this.componentSchema}
          codeContext={this}
        />
      </WidgetsContext.Provider>
    );
  }
}

CompositeCompWrapper.contextType = WidgetsContext;

export default observer((props) => (
  <CompositeCompWrapper {...props}></CompositeCompWrapper>
));

function parseWatcher(watcher) {
  if (!watcher) return;
  if (watcher instanceof Function) {
    return { handler: watcher, immediate: false };
  }
  const { handler, immediate = false } = watcher;
  if (!(handler instanceof Function)) return;
  return { handler, immediate };
}
