import React, { useEffect, useState } from 'react';
// import { EDITORROOT, SysModel } from '../utils/system';
import { Drawer } from 'antd-mobile';
import { mergeObject, guid, pluginCore } from '../utils';
import { PREFIX_CLS } from '../config';
import { plugin } from './jscss';
import Icon from '../icon';
import Button from '../button';
import './style/index';
import { SysModel } from '../utils/system';

const prefixCls = `${PREFIX_CLS}-popbutton-mobile`;

export default ({
  terminal,
  model = SysModel.DEV,
  data,
  dispatch,
  children,
}) => {
  const { style, props } = mergeObject(plugin, data);
  const { popicon = {} } = props;
  const [visible, setVisible] = useState(false);
  const popIconData = {
    style: {
      iconfont: {
        ...popicon,
      },
    },
  };
  const onLoad = () => {
    const values = {
      type: 'VerLayout',
      id: guid(),
      style: {
        width: '100%',
        height: '100%',
      },
      props: {},
      pid: data.id,
      children: [],
    };
    if (data.children.length === 0) {
      dispatch({
        type: 'tree/updateByKey',
        payload: {
          key: 'children',
          value: [values],
          id: data.id,
          createHistory: false,
        },
      });
      const editorPlugin = pluginCore.get({ terminal, type: data.type });
      if (editorPlugin) {
        dispatch({
          type: 'tree/select',
          payload: {
            data: { ...editorPlugin.data, children: [values] },
          },
        });
      }
    }
  };
  const closeClick = e => {
    e.stopPropagation();
    setVisible(false);
  };
  useEffect(() => {
    if (model === SysModel.DEV) {
      onLoad();
    }
  }, []);
  return (
    <>
      <Button
        data={{ style, props }}
        onClick={() => {
          setVisible(true);
        }}
      />
      <Drawer
        open={visible}
        className={`${prefixCls}-drawer`}
        position="bottom"
        enableDragHandle
        transitions
        sidebar={
          <>
            <div>
              {children}
              {popicon.type && (
                <div
                  className={`${prefixCls}__closebutton`}
                  onClick={closeClick}
                >
                  <Icon data={popIconData} />
                </div>
              )}
            </div>
          </>
        }
      />
    </>
  );
};
