import React, { useState, useEffect } from 'react';
import { Input, Select, Table, Button } from '@arco-design/web-react';
import { IconDelete } from '@arco-design/web-react/icon';

interface TableDataItem {
  key: number | string;
  id: string;
  dataType: string;
  arrayType: string;
  desc: string;
  defaultValue: string;

  [key: string]: any; // 允许其他自定义字段
}

interface ParamsTableProps {
  initialData: TableDataItem[] | any;
  onChange: (data) => void;
}

const ParamsTable: React.FC<ParamsTableProps> = ({
                                                   initialData,
                                                   onChange
                                                 }) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    // 为现有数据添加key属性（如果不存在）
    const dataWithKeys = initialData?.map((item, index) => ({
      ...item,
      key: item.key ?? index
    })) || [];
    setData(dataWithKeys);
  }, [initialData]);


  const columns = [
    {
      title: 'key',
      dataIndex: 'paramsKey',
      render: (_: any, record: TableDataItem) => (
        <Input
          value={record.paramsKey}
          onChange={(value) => handleSave({ ...record, paramsKey: value })}
        />
      )
    },
    {
      title: 'value',
      dataIndex: 'paramsValue',
      render: (_: any, record: TableDataItem) => (
        <Input
          value={record.paramsValue}
          onChange={(value) => handleSave({ ...record, paramsValue: value })}
        />
      )
    },
    {
      title: '操作',
      dataIndex: 'op',
      render: (_: any, record: TableDataItem) => (
        record.id !== 'maxTime' && <Button onClick={() => removeRow(record.key)} type="text" status="danger">
          <IconDelete />
        </Button>
      )
    }
  ];

  const handleSave = (row: TableDataItem) => {
    const newData = [...data];
    const index = newData.findIndex((item) => row.key === item.key);
    if (index >= 0) {
      newData.splice(index, 1, { ...newData[index], ...row });
    }
    else {
      newData.push(row);
    }
    setData(newData);
    onChange(newData);
  };

  const removeRow = (key: number | string) => {
    const newData = data.filter((item) => item.key !== key);
    setData(newData);
    onChange(newData);
  };

  const addRow = () => {
    const newKey = Date.now();
    const newRow = {
      key: newKey,
      paramsKey: '',
      paramsValue: ''
    };
    const newData = [...data, newRow];
    setData(newData);
    onChange(newData);
  };

  return (
    <>
      <Table columns={columns} data={data} pagination={false} />
      <Button
        style={{ height: 45 }}
        long
        type="outline"
        onClick={addRow}
      >
        + 添加
      </Button>
    </>
  );
};

export default ParamsTable;