import React, { useState } from 'react'
import { Button, Table, Input, Message } from '@alifd/next';

export default function DesignPic() {
  // 添加状态管理表格数据
  const [tableData, setTableData] = useState(() => {
    const result = [];
    for (let i = 0; i < 5; i++) {
      result.push({
        title: { name: `Quotation for 1PCS Nano ${3 + i}.0 controller compatible` },
        id: 100306660940 + i,
        time: 2e3 + i,
        // 添加名称和标签字段
        picName: '1235',
        picLabel: ''
      });
    }
    return result;
  });

  const pic_render = (value: any, index: any, record: any) => {
    return (
      <img className='size-20' src={record.url} alt={record.title} />
    );
  }

  // 修改图片名称渲染函数
  const name_render = (value: any, index: number, record: any) => {
    return <>
      <Input.TextArea
        value={record.picName}
        onChange={(value) => handleNameChange(value, index)}
        composition
        placeholder={'请输入图片名称'}
      />
    </>
  };

  // 修改图片标签渲染函数
  const label_render = (value: any, index: number, record: any) => {
    return <>
      <Input.TextArea
        value={record.picLabel}
        onChange={(value) => handleLabelChange(value, index)}
        composition
        placeholder={'请输入图片标签'}
      />
    </>
  };

  // 添加名称变化处理函数
  const handleNameChange = (value: string, index: number) => {
    const newData = [...tableData];
    newData[index].picName = value;
    setTableData(newData);
  };

  // 添加标签变化处理函数
  const handleLabelChange = (value: string, index: number) => {
    const newData = [...tableData];
    newData[index].picLabel = value;
    setTableData(newData);
  };

  // 完善删除功能
  const handleDelete = (index: number, record: any) => {
    // 方案1: 直接删除
    const newData = [...tableData];
    newData.splice(index, 1);
    setTableData(newData);
    
    // 方案2: 带确认的删除 (可选)
    // if (window.confirm(`确定要删除 "${record.title.name}" 吗?`)) {
    //   const newData = [...tableData];
    //   newData.splice(index, 1);
    //   setTableData(newData);
    //   Message.success('删除成功');
    // }
  };

  // 删除操作渲染函数
  const option_render = (value: any, index: number, record: any) => {
    return (
      <a 
        className='text-red-600 cursor-pointer'
        onClick={() => handleDelete(index, record)}
      >
        删除
      </a>
    );
  };

  // 添加行索引以确保正确删除
  const dataSourceWithIndex = tableData.map((item, index) => ({
    ...item,
    index
  }));

  return (
    <div className='w-3xl h-fit'>
      <Button>按钮</Button>
      <Table dataSource={dataSourceWithIndex}>
        <Table.Column title="图片" cell={pic_render} />
        <Table.Column title="图片名称" cell={name_render} />
        <Table.Column title="图片标签" cell={label_render} />
        <Table.Column title="操作" cell={option_render} />
      </Table>
    </div>
  )
}