import React, { useState, useEffect } from 'react';
import { Form, Input, Button } from 'antd';
import { CHI_AZ_NUM_COMMON } from 'common/constants';
import FormFooter from 'common/form-footer';
import { errorModal } from 'common/helper';
import ProtocolCode from './ProtocolCode';
import GoodsList from './GoodsList';
import { createCodeApi, updateCodeApi, agreementDetailApi } from '../service';
const Item = Form.Item;
const formItemLayout = {
labelCol: { xs: { span: 24 }, sm: { span: 3 } },
wrapperCol: { xs: { span: 24 }, sm: { span: 10 } },
};
const ProtocolAdd = props => {
const { history, form, match } = props;
const { getFieldDecorator, validateFieldsAndScroll } = form || {};
const { params = {} } = match;
const [deleteList, setDeleteList] = useState([]);
const [state, setState] = useState({
name: '',
code: '',
list: [],
});
const [test, setCount] = useState(0);
const [tableData, setTableData] = useState([]);
const { name, code, list } = state;
useEffect(() => {
(async () => {
if (params.id) {
const res = await agreementDetailApi({ agreementId: params.id });
const { name, agreementCode, skuDetailList = [] } = res || {};
setState({
name,
code: agreementCode,
list: skuDetailList.map(i => ({ ...i, name: i.itemName, id: i.skuId, saleStatus: i.status })),
});
}
})();
}, []);
const validatorList = (_, value, callback) => {
if (!value || !value?.length) {
callback('至少选择一个商品的SKU');
} else {
callback();
}
};
const handleDelete = ids => {
setDeleteList([...new Set([...deleteList, ...ids])]);
};
const handleSubmit = () => {
validateFieldsAndScroll(async (err, value) => {
if (!err) {
const { skuIds = [], ...other } = value || {};
if (skuIds.length > 400) {
errorModal('最多可添加400个商品SKU');
return;
}
const id = params.id;
const payload = {
...other,
skuIds: skuIds?.reduce((result, item) => {
result[item.id] = item.saleStatus;
return result;
}, {}),
};
if (id) {
payload.id = id;
payload.deleteSkuIds = deleteList.reduce((result, item) => {
result[item.id] = item.saleStatus;
return result;
}, {});
}
const res = await (id ? updateCodeApi(payload) : createCodeApi(payload));
if (res) {
history.push('/protocol/list');
}
}
});
};
// 上移行
const handleMoveUp = index => {
if (index <= 0) return;
const newData = [...tableData];
[newData[index], newData[index - 1]] = [newData[index - 1], newData[index]];
setTableData([...newData]); // 修改:返回一个全新数组
};
// 下移行
const handleMoveDown = index => {
if (index >= tableData.length - 1) return;
const newData = [...tableData];
[newData[index], newData[index + 1]] = [newData[index + 1], newData[index]];
setTableData([...newData]); // 修改:返回一个全新数组
};
// 删除行
const handleDeleteRow = index => {
const newData = tableData.filter((_, i) => i !== index);
setTableData([...newData]); // 修改:返回一个全新数组
};
// 新增行
const handleAddRow = () => {
setCount(test + 1);
const newEntry = { id: test, name: '', code: '' };
setTableData([...tableData, newEntry]);
};
// 更新表格数据
const handleInputChange = (index, field, value) => {
const updatedTableData = [...tableData];
updatedTableData[index][field] = value;
setTableData(updatedTableData); // 修复:直接传入更新后的数组
};
// 新增 handleProtocolCodeChange 方法
const handleProtocolCodeChange = (index, value) => {
const updatedTableData = [...tableData];
updatedTableData[index].code = value;
setTableData(updatedTableData); // 修复:直接传入更新后的数组
};
return (
<Form {...formItemLayout} autoComplete="off">
<h2 className="box-title">配置信息</h2>
<Item label="配置名称">
{getFieldDecorator('mock1', {
initialValue: name,
rules: [
{ required: true, message: '请输入数字、汉字、英文、特殊字符,不超过20个字符' },
{ pattern: CHI_AZ_NUM_COMMON, message: '请输入数字、汉字、英文、特殊字符,不超过20个字符' },
],
})(<Input placeholder="请输入配置名称" maxLength={20} />)}
</Item>
<h2 className="box-title">协议信息</h2>
<Item label="协议名称">
{getFieldDecorator('name', {
initialValue: name,
rules: [
{ required: true, message: '请输入数字、汉字、英文、特殊字符,不超过20个字符' },
{ pattern: CHI_AZ_NUM_COMMON, message: '请输入数字、汉字、英文、特殊字符,不超过20个字符' },
],
})(<Input placeholder="请输入协议名称" maxLength={20} />)}
</Item>
<Item label="协议code">
{getFieldDecorator('agreementCode', {
initialValue: code,
rules: [{ required: true, message: '请选择协议code' }],
})(<ProtocolCode />)}
</Item>
<h2 className="box-title">协议信息1</h2>
<pre>{JSON.stringify(tableData, null, 2)}</pre>
<div className="xieyi" key={`table-${tableData.length}-${Date.now()}`}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr>
<th style={{ border: '1px solid #ddd', padding: '8px' }}>协议名称</th>
<th style={{ border: '1px solid #ddd', padding: '8px' }}>协议code</th>
<th style={{ border: '1px solid #ddd', padding: '8px' }}>操作栏</th>
</tr>
</thead>
<tbody>
{tableData?.map((row, index) => (
<tr key={index}>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>
{getFieldDecorator(`tableData[${index}].name`, {
initialValue: row.name,
rules: [
{ required: true, message: '请输入数字、汉字、英文、特殊字符,不超过20个字符' },
{ pattern: CHI_AZ_NUM_COMMON, message: '请输入数字、汉字、英文、特殊字符,不超过20个字符' },
],
})(
<Input
placeholder="请输入协议名称"
onChange={e => handleInputChange(index, 'name', e.target.value)}
maxLength={20}
/>
)}
</td>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>
{getFieldDecorator(`tableData[${index}].code`, {
initialValue: row.code,
rules: [{ required: true, message: '请选择协议code' }],
})(<ProtocolCode onChange={value => handleProtocolCodeChange(index, value)} />)}
</td>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>
<Button
type="primary"
onClick={() => handleDeleteRow(index)}
style={{ display: index === 0 ? 'none' : 'inline-block' }}
>
删除
</Button>
<Button
type="primary"
onClick={() => handleMoveUp(index)}
disabled={index === 0}
style={{ display: index === 0 ? 'none' : 'inline-block' }}
>
上移
</Button>
<Button
type="primary"
onClick={() => handleMoveDown(index)}
style={{ display: index === tableData.length - 1 ? 'none' : 'inline-block' }}
disabled={index === tableData.length - 1}
>
下移
</Button>
</td>
</tr>
))}
</tbody>
</table>
<Button
type="primary"
onClick={handleAddRow}
style={{ display: tableData.length >= 5 ? 'none' : 'inline-block' }}
>
添加
</Button>
</div>
<h2 className="box-title">商品信息</h2>
<Item wrapperCol={{ xs: { span: 24 }, sm: { span: 24 } }}>
{getFieldDecorator('skuIds', {
initialValue: list,
rules: [{ validator: validatorList }],
})(
<GoodsList
tips="最多可添加400个商品SKU"
rowKey="id"
onDelete={handleDelete}
agreementId={params.id}
deleteList={deleteList}
/>
)}
</Item>
<FormFooter handleCancel={history.goBack} handleSubmit={handleSubmit} autoSubmit={false} />
</Form>
);
};
export default Form.create()(ProtocolAdd);
帮我分析一下,当前代码,为什么,对 tabledata表格进行,删除,上移,下移等操作,数据变了,但是试图没有变化