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

// 定义数据类型选项
const dataTypeOptions = [
  { label: 'STRING', value: 'STRING' },
  { label: 'INTEGER', value: 'INTEGER' },
  { label: 'BOOLEAN', value: 'BOOLEAN' },
  { label: 'ARRAY', value: 'ARRAY' },
  { label: 'OBJECT', value: 'OBJECT' },
  { label: 'JSON', value: 'JSON' },
  { label: 'DOUBLE', value: 'DOUBLE' }
];

// 定义数组类型选项
const arrayTypeOptions = [
  { label: 'STRING', value: 'STRING' },
  { label: 'INTEGER', value: 'INTEGER' },
  { label: 'DOUBLE', value: 'DOUBLE' },
  { label: 'BOOLEAN', value: 'BOOLEAN' },
  { label: 'JSON', value: 'JSON' },
  { label: 'OBJECT', value: 'OBJECT' }
];

function EditableCell({ value, onChange, columnType, record, dataIndex }) {
  // 对于数组类型字段的特殊处理
  if (dataIndex === 'generic') {
    // 仅当数据类型为 ARRAY 时才可编辑
    if (record.type === 'ARRAY') {
      return (
        <Select
          value={value}
          onChange={onChange}
          options={arrayTypeOptions}
          placeholder="请选择数组类型"
        />
      );
    }
    else {
      // 非 ARRAY 类型显示横杠
      return <span>-</span>;
    }
  }

  if (columnType === 'input') {
    return (
      <Input
        value={value}
        onChange={onChange}
        placeholder="请输入"
      />
    );
  }

  if (columnType === 'select') {
    return (
      <Select
        value={value}
        onChange={onChange}
        options={dataTypeOptions}
        placeholder="请选择数据类型"
      />
    );
  }

  return <span>{value}</span>;
}

function EditableTable({ onDataUpdate, initialData = [], visible }) {
  const [data, setData] = useState([]);

  // 当初始数据变化时，更新表格数据
  useEffect(() => {
    if (initialData && Array.isArray(initialData) && initialData.length > 0) {
      // 为每个数据项添加唯一的 key
      const dataWithKeys = initialData.map((item, index) => ({
        key: item.key || item.id || `key_${index}`,
        ...item
      }));
      setData(dataWithKeys);
    }
  }, [initialData]);

  useEffect(() => {
    if (!visible) setData([]);
  }, [visible]);

  const handleValueChange = (key, dataIndex, value) => {
    const newData = data.map(item => {
      if (item.key === key) {
        const updatedItem = { ...item, [dataIndex]: value };

        // 如果更改的是 type 字段且不是 ARRAY，则清空 generic 字段
        if (dataIndex === 'type' && value !== 'ARRAY') {
          updatedItem.generic = '';
        }

        return updatedItem;
      }
      return item;
    });

    setData(newData);
    onDataUpdate && onDataUpdate(newData);
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'ident',
      render: (_, record) => (
        <EditableCell
          value={record.ident}
          onChange={(value) => handleValueChange(record.key, 'ident', value)}
          columnType="input"
          record={record}
          dataIndex="ident"
        />
      )
    },
    {
      title: '数据类型',
      dataIndex: 'type',
      render: (_, record) => (
        <EditableCell
          value={record.type}
          onChange={(value) => handleValueChange(record.key, 'type', value)}
          columnType="select"
          record={record}
          dataIndex="type"
        />
      )
    },
    {
      title: '数组类型',
      dataIndex: 'generic',
      render: (_, record) => (
        <EditableCell
          value={record.generic}
          onChange={(value) => handleValueChange(record.key, 'generic', value)}
          columnType="select"
          record={record}
          dataIndex="generic"
        />
      )
    },
    {
      title: '参数描述',
      dataIndex: 'desc',
      render: (_, record) => (
        <EditableCell
          value={record.desc}
          onChange={(value) => handleValueChange(record.key, 'desc', value)}
          columnType="input"
          record={record}
          dataIndex="desc"
        />
      )
    },
    {
      title: '操作',
      dataIndex: 'op',
      render: (_, record) => (
        <Button
          onClick={() => removeRow(record.key)}
          type="text"
          status="danger"
        >
          删除
        </Button>
      )
    }
  ];

  const removeRow = (key) => {
    const newData = data.filter(item => item.key !== key);
    setData(newData);
    onDataUpdate && onDataUpdate(newData);
  };

  const addRow = () => {
    const newRow = {
      key: `${Date.now()}`,
      ident: '',
      type: '',
      generic: '',
      desc: ''
    };
    const newData = [...data, newRow];
    setData(newData);
    onDataUpdate && onDataUpdate(newData);
  };

  return (
    <>
      <Button
        style={{ marginBottom: 10 }}
        type="primary"
        onClick={addRow}
      >
        新增参数
      </Button>
      <Table
        data={data}
        pagination={false}
        columns={columns}
        className="table-demo-editable-cell"
      />
    </>
  );
}

export default EditableTable;