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$onPcModalClose from './lowcode/handler/onPcModalClose.js';

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

// Import Components outof sandbox

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

const { Slot: GsdH5ReactSlot } = gsdH5React.components;

const { Text: GsdH5ReactText } = gsdH5React.components;

const { Button: GsdH5ReactButton } = gsdH5React.components;

import CLOUDBASESTANDARDIcon from '/src/libraries/CLOUDBASE_STANDARD@1634202837896/components/Icon';

const { Modal: GsdH5ReactModal } = 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:Container': (props) => (
        <GsdH5ReactContainer {...resolveComponentProps(props, 1)} />
      ),

      'gsd-h5-react:Slot': (props) => (
        <GsdH5ReactSlot {...resolveComponentProps(props, 1)} />
      ),

      'gsd-h5-react:Text': (props) => (
        <GsdH5ReactText {...resolveComponentProps(props, 1)} />
      ),

      'gsd-h5-react:Button': (props) => (
        <GsdH5ReactButton {...resolveComponentProps(props, 1)} />
      ),

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

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

    // 挂载给到 $comp.props.events 使用
    this.events = ['close', 'comfirm'].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 = {
      onPcModalClose: handler$onPcModalClose.bind(this),

      onPcModalConfirm: handler$onPcModalConfirm.bind(this),
    };
    const widgetContext = {
      id2: {
        title: '',
        style: {},
        classList: ['lcap-modal__mask'],
        widgetType: 'gsd-h5-react:Container',
        _parentId: 'id17',
      },
      id12: {
        name: 'customContent',
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id4',
      },
      id15: {
        space: false,
        maxLines: 2,
        userSelect: true,
        style: {
          whiteSpace: 'pre-line',
        },
        classList: [],
        widgetType: 'gsd-h5-react:Text',
        _parentId: 'id4',
      },
      id4: {
        title: 'modal-header',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Container',
        _parentId: 'id3',
      },
      id9: {
        text: '确定',
        space: '',
        decode: false,
        maxLines: 2,
        selectable: false,
        userSelect: true,
        _visible: true,
        style: {
          zIndex: 30,
          position: 'static',
          bottom: '0',
        },
        classList: [],
        widgetType: 'gsd-h5-react:Text',
        _parentId: 'id8',
      },
      id8: {
        lang: 'en',
        size: 'default',
        text: '',
        type: 'default',
        plain: false,
        divider: '',
        loading: false,
        disabled: false,
        formType: 'button',
        openType: '',
        categoryId: [],
        sessionFrom: '',
        appParameter: '',
        sendMessageImg: '',
        sendMessagePath: '',
        showMessageCard: '',
        sendMessageTitle: '',
        style: {
          width: '100%',
          color: 'rgb(255, 255, 255)',
          borderWidth: '0',
          borderRadius: '0',
          background: 'rgb(50, 129, 248)',
          position: 'fixed',
          left: '0',
          right: '0',
          bottom: '0',
        },
        classList: [],
        widgetType: 'gsd-h5-react:Button',
        _parentId: 'id5',
      },
      id13: {
        name: 'customButton',
        style: {
          color: 'rgb(255, 255, 255)',
          borderWidth: '0',
          borderRadius: '0',
          background: 'rgb(50, 129, 248)',
          position: 'fixed',
          left: '0',
          right: '0',
          bottom: '0',
        },
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id5',
      },
      id5: {
        title: '',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Container',
        _parentId: 'id3',
      },
      id14: {
        src: '',
        name: 'close',
        size: 48,
        color: 'rgb(136, 136, 136)',
        _visible: true,
        style: {},
        classList: [],
        widgetType: 'CLOUDBASE_STANDARD:Icon',
        _parentId: 'id6',
      },
      id6: {
        title: '',
        _visible: true,
        style: {},
        classList: ['lcap-modal__close_btn'],
        widgetType: 'gsd-h5-react:Container',
        _parentId: 'id3',
      },
      id3: {
        title: '',
        style: {},
        classList: ['lcap-modal__dialog'],
        widgetType: 'gsd-h5-react:Container',
        _parentId: 'id17',
      },
      id17: {
        title: '',
        style: {},
        classList: ['container'],
        widgetType: 'gsd-h5-react:Container',
        _parentId: 'id1',
      },
      id23: {
        name: 'customButton',
        style: {
          color: 'rgb(255, 255, 255)',
          borderWidth: '0',
          borderRadius: '0',
          background: 'rgb(50, 129, 248)',
          position: 'fixed',
          left: '0',
          right: '0',
          bottom: '0',
        },
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id24',
      },
      id22: {
        name: 'customContent',
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Slot',
        _parentId: 'id24',
      },
      id24: {
        style: {},
        classList: [],
        widgetType: 'gsd-h5-react:Modal',
        _parentId: 'id1',
      },
      id1: {
        title: '',
        style: {},
        classList: ['lcap-modal', 'wa-comp-CLOUDBASE_STANDARD-Modal'],
        widgetType: 'gsd-h5-react:Container',
      },
    };
    const dataBinds = (this._dataBinds = {
      id12: {
        _visible: (forItems) => {
          const $for = forItems;
          return !this.$WEAPPS_COMP.props.data.content;
        },
      },
      id15: {
        text: () => this.$WEAPPS_COMP.props.data.content,
        _visible: () => this.$WEAPPS_COMP.props.data.content,
      },
      id8: {
        _visible: () => this.$WEAPPS_COMP.props.data.isDefaultButton,
      },
      id13: {
        _visible: () => !this.$WEAPPS_COMP.props.data.isDefaultButton,
      },
      id3: {
        classList: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.props.data.visible &&
            this.$WEAPPS_COMP.computed.contentIn
            ? 'enter'
            : '';
        },
      },
      id17: {
        _visible: (forItems) => {
          const $for = forItems;
          return (
            (this.$WEAPPS_COMP.props.data.visible ||
              this.$WEAPPS_COMP.computed.contentIn) &&
            this.$WEAPPS_COMP.state._mode !== 'pc'
          );
        },
      },
      id23: {
        _visible: () => !this.$WEAPPS_COMP.props.data.isDefaultButton,
      },
      id22: {
        _visible: (forItems) => {
          const $for = forItems;
          return !this.$WEAPPS_COMP.props.data.content;
        },
      },
      id24: {
        content: () => this.$WEAPPS_COMP.props.data.content,
        visible: () => this.$WEAPPS_COMP.props.data.visible,
        isDefaultButton: () => this.$WEAPPS_COMP.props.data.isDefaultButton,
        _visible: (forItems) => {
          const $for = forItems;
          return this.$WEAPPS_COMP.state._mode === 'pc';
        },
      },
    });
    this.componentSchema = {
      type: 'object',
      properties: {
        id1: {
          key: 'id1',
          'x-component': 'gsd-h5-react:container',
          'x-props': {
            sourceKey: 'gsd-h5-react:Container',
            customDataForm: {},
            staticResourceAttribute: [],
            classNameList: ['lcap-modal', 'wa-comp-CLOUDBASE_STANDARD-Modal'],
          },
          'x-index': 1,
          emitEvents: [
            'tap',
            'longpress',
            'touchstart',
            'touchmove',
            'touchcancel',
            'touchend',
          ],
          properties: {
            id17: {
              key: 'id17',
              'x-component': 'gsd-h5-react:container',
              'x-props': {
                sourceKey: 'gsd-h5-react:Container',
                customDataForm: {},
                staticResourceAttribute: [],
                classNameList: ['container'],
              },
              'x-index': 0,
              emitEvents: [
                'tap',
                'longpress',
                'touchstart',
                'touchmove',
                'touchcancel',
                'touchend',
              ],
              properties: {
                id2: {
                  key: 'id2',
                  'x-component': 'gsd-h5-react:container',
                  'x-props': {
                    sourceKey: 'gsd-h5-react:Container',
                    customDataForm: {},
                    staticResourceAttribute: [],
                    classNameList: ['lcap-modal__mask'],
                  },
                  'x-index': 0,
                  emitEvents: [
                    'tap',
                    'longpress',
                    'touchstart',
                    'touchmove',
                    'touchcancel',
                    'touchend',
                  ],
                },
                id3: {
                  key: 'id3',
                  'x-component': 'gsd-h5-react:container',
                  'x-props': {
                    sourceKey: 'gsd-h5-react:Container',
                    customDataForm: {},
                    staticResourceAttribute: [],
                    classNameList: ['lcap-modal__dialog'],
                  },
                  'x-index': 1,
                  emitEvents: [
                    'tap',
                    'longpress',
                    'touchstart',
                    'touchmove',
                    'touchcancel',
                    'touchend',
                  ],
                  properties: {
                    id4: {
                      key: 'id4',
                      'x-component': 'gsd-h5-react:container',
                      'x-props': {
                        sourceKey: 'gsd-h5-react:Container',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      'x-index': 1,
                      emitEvents: [
                        'tap',
                        'longpress',
                        'touchstart',
                        'touchmove',
                        'touchcancel',
                        'touchend',
                      ],
                      properties: {
                        id12: {
                          key: 'id12',
                          'x-component': 'gsd-h5-react:slot',
                          'x-props': {
                            sourceKey: 'gsd-h5-react:Slot',
                            customDataForm: {},
                            staticResourceAttribute: [],
                          },
                          'x-index': 1,
                        },
                        id15: {
                          key: 'id15',
                          'x-component': 'gsd-h5-react:text',
                          'x-props': {
                            sourceKey: 'gsd-h5-react:Text',
                            customDataForm: {},
                            commonStyle: {
                              whiteSpace: 'pre-line',
                            },
                            staticResourceAttribute: [],
                          },
                          'x-index': 0,
                          emitEvents: ['tap'],
                        },
                      },
                    },
                    id5: {
                      key: 'id5',
                      'x-component': 'gsd-h5-react:container',
                      'x-props': {
                        sourceKey: 'gsd-h5-react:Container',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      'x-index': 2,
                      emitEvents: [
                        'tap',
                        'longpress',
                        'touchstart',
                        'touchmove',
                        'touchcancel',
                        'touchend',
                      ],
                      properties: {
                        id8: {
                          key: 'id8',
                          'x-component': 'gsd-h5-react:button',
                          'x-props': {
                            sourceKey: 'gsd-h5-react:Button',
                            customDataForm: {},
                            commonStyle: {
                              width: '100%',
                              color: 'rgb(255, 255, 255)',
                              borderWidth: '0',
                              borderRadius: '0',
                              background: 'rgb(50, 129, 248)',
                              position: 'fixed',
                              left: '0',
                              right: '0',
                              bottom: '0',
                            },
                            staticResourceAttribute: [],
                            listenerInstances: [
                              {
                                key: '',
                                trigger: 'tap',
                                instanceFunction: function ({
                                  data,
                                  event,
                                  forItems,
                                }) {
                                  event.detail.data = data;
                                  this.props.emit('comfirm', event.detail);
                                }.bind(this),
                                data: {
                                  target: '',
                                },
                              },
                            ],
                          },
                          'x-index': 0,
                          emitEvents: [
                            'tap',
                            'getPhoneNumber',
                            'contact',
                            'getUserInfo',
                            'launchApp',
                            'openSetting',
                          ],
                          properties: {
                            text: {
                              key: 'text',
                              properties: {
                                id9: {
                                  key: 'id9',
                                  'x-component': 'gsd-h5-react:text',
                                  'x-props': {
                                    sourceKey: 'gsd-h5-react:Text',
                                    customDataForm: {},
                                    commonStyle: {
                                      zIndex: 30,
                                      position: 'static',
                                      bottom: '0',
                                    },
                                    staticResourceAttribute: [],
                                  },
                                  'x-index': 1,
                                  emitEvents: ['tap'],
                                },
                              },
                            },
                          },
                        },
                        id13: {
                          key: 'id13',
                          'x-component': 'gsd-h5-react:slot',
                          'x-props': {
                            sourceKey: 'gsd-h5-react:Slot',
                            customDataForm: {},
                            commonStyle: {
                              color: 'rgb(255, 255, 255)',
                              borderWidth: '0',
                              borderRadius: '0',
                              background: 'rgb(50, 129, 248)',
                              position: 'fixed',
                              left: '0',
                              right: '0',
                              bottom: '0',
                            },
                            staticResourceAttribute: [],
                          },
                          'x-index': 1,
                        },
                      },
                    },
                    id6: {
                      key: 'id6',
                      'x-component': 'gsd-h5-react:container',
                      'x-props': {
                        sourceKey: 'gsd-h5-react:Container',
                        customDataForm: {},
                        staticResourceAttribute: [],
                        classNameList: ['lcap-modal__close_btn'],
                        listenerInstances: [
                          {
                            key: '',
                            trigger: 'tap',
                            instanceFunction: function ({
                              data,
                              event,
                              forItems,
                            }) {
                              event.detail.data = data;
                              this.props.emit('close', event.detail);
                            }.bind(this),
                            data: {
                              target: '',
                            },
                          },
                        ],
                      },
                      'x-index': 0,
                      emitEvents: [
                        'tap',
                        'longpress',
                        'touchstart',
                        'touchmove',
                        'touchcancel',
                        'touchend',
                      ],
                      properties: {
                        id14: {
                          key: 'id14',
                          'x-component': 'cloudbase_standard:icon',
                          'x-props': {
                            sourceKey: 'CLOUDBASE_STANDARD:Icon',
                            customDataForm: {},
                            staticResourceAttribute: [],
                          },
                          'x-index': 2,
                          emitEvents: [],
                        },
                      },
                    },
                  },
                },
              },
            },
            id24: {
              key: 'id24',
              'x-component': 'gsd-h5-react:modal',
              'x-props': {
                sourceKey: 'gsd-h5-react:Modal',
                customDataForm: {},
                staticResourceAttribute: [],
                listenerInstances: [
                  {
                    key: 'wa7anjvdlbn',
                    trigger: 'close',
                    instanceFunction: function ({ data, event, forItems }) {
                      event.detail.data = data;
                      this.props.emit('close', event.detail);
                    }.bind(this),
                    data: {
                      target: '',
                    },
                  },
                  {
                    key: 'waoo4cumg19g',
                    trigger: 'close',
                    instanceFunction: function ({ data, event, forItems }) {
                      event.detail.data = data;
                      this.props.emit('comfirm', event.detail);
                    }.bind(this),
                    data: {
                      target: '',
                    },
                  },
                ],
              },
              'x-index': 2,
              emitEvents: ['close', 'confirm'],
              properties: {
                customButton: {
                  key: 'customButton',
                  properties: {
                    id23: {
                      key: 'id23',
                      'x-component': 'gsd-h5-react:slot',
                      'x-props': {
                        sourceKey: 'gsd-h5-react:Slot',
                        customDataForm: {},
                        commonStyle: {
                          color: 'rgb(255, 255, 255)',
                          borderWidth: '0',
                          borderRadius: '0',
                          background: 'rgb(50, 129, 248)',
                          position: 'fixed',
                          left: '0',
                          right: '0',
                          bottom: '0',
                        },
                        staticResourceAttribute: [],
                      },
                      'x-index': 0,
                    },
                  },
                },
                customContent: {
                  key: 'customContent',
                  properties: {
                    id22: {
                      key: 'id22',
                      'x-component': 'gsd-h5-react:slot',
                      'x-props': {
                        sourceKey: 'gsd-h5-react:Slot',
                        customDataForm: {},
                        staticResourceAttribute: [],
                      },
                      'x-index': 0,
                    },
                  },
                },
              },
            },
          },
        },
      },
    };

    const defaultProps = {
      content: '',
      visible: true,
      isDefaultButton: true,
    };
    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 };
}
