import { Form } from 'antd';
import React, { useState } from 'react';
import { ArrowUpOutlined, ArrowDownOutlined, DeleteOutlined } from '@ant-design/icons';

function FormContent(props) {
  const { list, onChange, onSelect } = props;
  const [currentItem, setCurrentItem] = useState(null);
  const handleDelete = index => {
    let _list = [...list];
    _list.splice(index, 1);
    onChange(_list);
  };
  const handleUp = index => {
    let _list = [...list];
    // 跟上一位置换位置
    const temp = _list[index - 1];
    _list[index - 1] = _list[index];
    _list[index] = temp;
    onChange(_list);
  };
  const handleDown = index => {
    let _list = [...list];
    const temp = _list[index + 1];
    _list[index + 1] = _list[index];
    _list[index] = temp;
    onChange(_list);
  };
  const handleSelect = index => {
    setCurrentItem(index);
    onSelect(index);
  };
  return (
    <div style={{ width: 300 }}>
      {list.map((item, index) => {
        const btns = (
          <>
            {index != 0 && (
              <ArrowUpOutlined
                style={{ marginLeft: 5, cursor: 'pointer' }}
                onClick={() => handleUp(index)}
              />
            )}
            {index != list.length - 1 && (
              <ArrowDownOutlined
                style={{ marginLeft: 5, cursor: 'pointer' }}
                onClick={() => handleDown(index)}
              />
            )}
            <DeleteOutlined
              style={{ marginLeft: 5, cursor: 'pointer' }}
              onClick={() => handleDelete(index)}
            />
          </>
        );
        return (
          <FormItem
            key={item.props?.id}
            active={index == currentItem}
            onClick={() => handleSelect(index)}
            item={item}
            btns={btns}
          />
        );
      })}
    </div>
  );
}

function FormItem(props) {
  const { item, btns, active, onClick } = props;
  const { label, placeholder, required } = item.props;
  return (
    <div
      style={{
        marginBottom: 20,
        padding: '4px 12px',
        border: '1px solid #666',
        borderLeft: active ? '10px solid #1890FF' : '1px solid #666',
      }}
      onClick={onClick}
    >
      <div style={{ fontSzie: 24, color: '#000', fontWeight: 'bold', position: 'relative' }}>
        {required && <i style={{ color: 'red' }}>*</i>}
        {label}
        <div style={{ position: 'absolute', right: 0, top: 0, padding: '5px 10px' }}>{btns}</div>
      </div>
      <div style={{ color: '#999', fontSize: 16 }}>{placeholder}</div>
    </div>
  );
}

export default FormContent;
