import React from 'react';
import ReactDOM from 'react-dom';
import Engine from '@ali/visualengine';
// @ts-ignore
import { ActionUtil } from '@ali/visualengine-utils';

// @ts-ignore
window.epochPage = {
  jsList: [],
};
class Demo extends React.Component {
  container: HTMLDivElement;

  componentDidMount() {
    setTimeout(this.init, 0);
  }

  init = async () => {
    const { container } = this;
    await Engine.initEpochDesigner(container);
    const schema = this.ensureUrlParamsDataSource({
      componentsTree: [
        {
          componentName: 'Page',
          id: 'node_k1p231i3',
          children: [],
        },
      ],
    }) as any;
    Engine.Pages.addPage(schema);
    if (schema && schema.actions) {
      ActionUtil.setActions(schema.actions);
    }
  };

  ensureUrlParamsDataSource(schema) {
    schema.componentsTree.forEach((page) => {
      if (page.dataSource) {
        const data = page.dataSource.data || [];
        const urlParamsDs = data.find((item) => item.name === 'urlParams');
        if (!urlParamsDs) {
          data.push({
            data: {},
            reserved: true,
            name: 'urlParams',
            cname: '页面参数',
            id: 'urlParams',
          });
          page.dataSource.data = data;
        } else {
          // 不可删除
          urlParamsDs.reserved = true;
        }
      }
    });
    return schema;
  }

  render() {
    return (
      <div
        ref={(r) => {
          this.container = r;
        }}
        id="engine"
      />
    );
  }
}

ReactDOM.render(<Demo />, document.getElementById('root'));
