import React, { useState, useEffect } from 'react';
import FormContent from './FormContent';
import ComponentLibrary from './ComponentLibrary';
import ItemAttribute from './ItemAttribute';
import { uuidv4 } from '@antv/xflow';
import { Button } from 'antd';

function AuditForm(props) {
  const { value, onChange } = props;
  const [formList, setFormList] = useState([]);
  const [select, setSelect] = useState(-1);
  const [visible, setVisible] = useState(false);

  const handleAddItem = item => {
    const formItem = generateItem(item);
    handleChangeList([...formList, formItem]);
    setVisible(false);
  };

  const generateItem = item => {
    let newItem = {
      ...item,
      props: { ...item.props, id: `${item.componentName}_${uuidv4()}` },
    };
    delete newItem.icon;
    return newItem;
  };

  const onChangeAttribute = newItem => {
    let oldValue = formList[select].props;
    formList[select].props = { ...oldValue, ...newItem };
    handleChangeList([...formList]);
  };

  const handleChangeList = list => {
    setFormList(list);
    onChange?.(list);
  };

  useEffect(() => {
    if (value instanceof Array) {
      setFormList([...value]);
      onChange?.([...value]);
    }
  }, [value]);

  return (
    <div>
      <Button onClick={() => setVisible(true)}>增加控件</Button>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'flex-start',
          width: 800,
          marginTop: 20,
        }}
      >
        <FormContent onSelect={setSelect} onChange={handleChangeList} list={formList}></FormContent>
        <ItemAttribute item={formList[select]} onChange={onChangeAttribute}></ItemAttribute>
      </div>
      <ComponentLibrary
        onOk={handleAddItem}
        visible={visible}
        onCancel={() => setVisible(false)}
      ></ComponentLibrary>
    </div>
  );
}

export default AuditForm;
