import React, { useMemo, useState, useEffect } from 'react';
import { Button } from 'antd';
import DDComponents from '../index';
import style from './index.less';

function TableField(props) {
  const { item, onChange } = props;
  const [value, setValue] = useState([]);

  const getEmptyValue = () => {
    let data = item.children.map(children => ({
      name: children.props.id,
      value: '',
    }));
    data.id = Math.random();
    return data;
  };
  const getChildren = (item, data) => {
    let cur = data.find(d => d.name == item.props.id);
    const childrenChange = value => {
      cur.value = value;
      onChange(JSON.stringify(value));
    };
    return DDComponents({ item, onChange: childrenChange, value: cur.value });
  };

  // const localValue = useMemo(() => {
  //   let v = [];
  //   try {
  //     v = JSON.parse(value);
  //   } catch (error) {}
  //   if (v.length == 0) {
  //     let data = getEmptyValue();
  //     v.push(data);
  //   }
  //   return v;
  // }, [value]);

  const addRow = () => {
    let newValue = [...value, getEmptyValue()];
    setValue(newValue);
    onChange(JSON.stringify(newValue));
  };

  const removeRow = index => {
    let newValue = [...value];
    newValue.splice(index, 1);

    setValue(newValue);
    onChange(JSON.stringify(newValue));
  };
  useEffect(() => {
    setValue([getEmptyValue()]);
  }, []);

  return (
    <div>
      <table className={style.table}>
        <thead>
          <tr>
            <th></th>
            {item.children.map(item => (
              <th>{item.props.label}</th>
            ))}
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {value.map((curItem, index) => (
            <tr key={curItem.id}>
              <td>{index + 1}</td>
              {item.children.map(item => (
                <td>{getChildren(item, curItem)}</td>
              ))}
              <td>
                {value.length > 1 && <a onClick={() => removeRow(index)}>删除</a>}
                {/* <a>复制</a> */}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <Button style={{ marginTop: 20 }} onClick={addRow}>
        {item.props.actionName}
      </Button>
    </div>
  );
}

export default TableField;
