Commit f93bb626 authored by beisir's avatar beisir

feat: 新增编辑表格组件

parent 38abbba2
import React from 'react'; import React, { useState } from 'react';
import { Table, Form, InputNumber, Input, Popconfirm } from 'antd'; import { Table, Form, InputNumber, Input, Popconfirm, Button, notification } from 'antd';
import { useEditProduct, dataInit } from './utils';
const data = []; const initData = {
// eslint-disable-next-line no-plusplus weight: null,
for (let i = 0; i < 5; i++) { productStockWarning: null,
data.push({ marketPrice: 'marketPrice',
firstSpecValue: '规格一级', // salePrice: '',
secondSpecValue: '规格二级', supplyPrice: 'supplyPrice',
key: i.toString(), // stock: '',
name: `Edrward ${i}`, productStock: 'productStock',
age: 32, thirdSkuNo: 'thirdSkuNo',
address: `London Park no. ${i}`, skuLink: 'skuLink',
imageList: [],
};
const createProductData = (
{ firstValues, secondValues, firstSpecId, secondSpecId },
productData,
) => {
const countRowSpan = {};
const dataSource = [];
firstValues.forEach((fisrtItem, index) => {
const specFirst = Object.assign({}, initData);
specFirst.firstSpecId = firstSpecId.key;
specFirst.firstSpecValue = fisrtItem;
if (secondValues.length) {
secondValues.forEach(secondItem => {
const specSecond = Object.assign({}, specFirst);
if (!countRowSpan[specFirst.firstSpecValue]) {
countRowSpan[specFirst.firstSpecValue] = true;
specSecond.rowSpanCount = secondValues.length;
}
specSecond.secondSpecId = secondSpecId.key;
specSecond.secondSpecValue = secondItem;
dataSource.push(specSecond);
});
return;
}
dataSource.push(specFirst);
}); });
} return dataSource;
};
const isRepeatProduct = (list, message) => {
const isRepeat = [...new Set(list)].length !== list.length;
if (isRepeat) {
notification.warning({ message });
}
return isRepeat;
};
const EditableContext = React.createContext(); const EditableContext = React.createContext();
...@@ -26,31 +64,39 @@ const EditableCell = tableProps => { ...@@ -26,31 +64,39 @@ const EditableCell = tableProps => {
const renderCell = form => { const renderCell = form => {
const { getFieldDecorator } = form; const { getFieldDecorator } = form;
const { const {
editing, editable,
dataIndex, dataIndex,
title, title,
inputType, inputType,
record, record,
index, index,
children, children,
rules,
required,
...restProps ...restProps
} = tableProps; } = tableProps;
console.log(tableProps);
return ( return (
<td {...restProps}> <td {...restProps}>
{editing ? ( {editable ? (
<Form.Item style={{ margin: 0 }}> <Form.Item style={{ margin: 0 }}>
{getFieldDecorator(`tableArray[${record.key}][${dataIndex}]`, { {getFieldDecorator(`tableArray[${index}][${dataIndex}]`, {
rules: [ rules: [
{ {
required: true, required,
message: `Please Input ${title}!`, message: `请输入 ${title}!`,
}, },
...rules,
], ],
initialValue: record[dataIndex], initialValue: record[dataIndex],
})(getInput())} })(getInput())}
</Form.Item> </Form.Item>
) : ( ) : (
children <Form.Item style={{ margin: 0 }}>
{getFieldDecorator(`tableArray[${index}][${dataIndex}]`, {
initialValue: record[dataIndex],
})(<span className="ant-form-text">{children}</span>)}
</Form.Item>
)} )}
</td> </td>
); );
...@@ -58,93 +104,127 @@ const EditableCell = tableProps => { ...@@ -58,93 +104,127 @@ const EditableCell = tableProps => {
return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>; return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>;
}; };
const isEditing = record => record.key === ''; const ProductInfoColumns = ({ firstSpecId, secondSpecId }, productData) => {
console.log(productData);
return productData.length
? [
{
title: firstSpecId?.label,
dataIndex: 'firstSpecValue',
key: 'firstSpecValue',
editable: false,
render: (val, row) => ({
children: val,
props: {
rowSpan: row.rowSpanCount ? row.rowSpanCount : 0,
},
}),
},
{
title: secondSpecId?.label,
dataIndex: 'secondSpecValue',
key: 'secondSpecValue',
editable: false,
},
{
title: '供货价',
key: 'supplyPrice',
dataIndex: 'supplyPrice',
editable: true,
inputType: 'number',
required: true,
rules: [],
},
{
title: '市场价',
key: 'marketPrice',
dataIndex: 'marketPrice',
editable: true,
required: true,
},
{
title: '库存',
dataIndex: 'productStock',
key: 'productStock',
editable: true,
inputType: 'number',
required: true,
},
{
title: '商品自编码',
dataIndex: 'thirdSkuNo',
key: 'thirdSkuNo',
editable: true,
inputType: 'number',
required: true,
},
{
title: '京东链接',
dataIndex: 'skuLink',
key: 'skuLink',
editable: true,
},
]
: [];
};
const ProductInfoColumns = () => [ const BatchSettings = () => {};
{
title: '一级规格',
dataIndex: 'firstSpecValue',
editable: false,
},
{
title: '二级规格',
dataIndex: 'secondSpecValue',
editable: false,
},
{
title: 'name',
dataIndex: 'name',
editable: true,
},
{
title: 'age',
dataIndex: 'age',
editable: true,
},
{
title: 'address',
dataIndex: 'address',
editable: true,
},
{
title: 'operation',
dataIndex: 'operation',
render: (text, record) => {
const editingKey = '';
const editable = isEditing(record);
return editable ? (
<span>
<EditableContext.Consumer>
{form => (
<a
// onClick={() => save(form, record.key)}
style={{ marginRight: 8 }}
>
Save
</a>
)}
</EditableContext.Consumer>
<Popconfirm title="Sure to cancel?">
<a>Cancel</a>
</Popconfirm>
</span>
) : (
<a disabled={editingKey !== ''}>Edit</a>
);
},
},
];
export const GenerateProductInfo = ({ form }) => { export const GenerateProductInfo = ({ form }) => {
const [productData, setProductData] = useState([]);
const components = { const components = {
body: { body: {
cell: EditableCell, cell: EditableCell,
}, },
}; };
const columns = ProductInfoColumns().map(col => { const columns = ProductInfoColumns(form.getFieldsValue(), productData).map(col => {
if (!col.editable) { console.log('============================================================');
return col;
}
return { return {
...col, ...col,
onCell: record => ({ onCell: (record, index) => {
record, console.log(index);
inputType: col.dataIndex === 'age' ? 'number' : 'text', return {
dataIndex: col.dataIndex, index,
title: col.title, record,
editing: true, editable: col.editable,
}), dataIndex: col.dataIndex,
title: col.title,
rules: col.rules,
required: col.required,
};
},
}; };
}); });
const handleAddProduct = () => {
const values = form.getFieldsValue();
const { firstValues = [], secondValues = [] } = values;
// 校验是否有重复的一级规格
const fisrtIsRepeat = isRepeatProduct(firstValues, '一级规格不可重复');
const secondIsRepeat = isRepeatProduct(secondValues, '二级规格不可重复');
if ([fisrtIsRepeat, secondIsRepeat].includes(true)) {
setProductData([]);
return;
}
const newData = createProductData(values, productData);
setProductData(newData);
};
return ( return (
<EditableContext.Provider value={form}> <EditableContext.Provider value={form}>
<div style={{ textAlign: 'center' }}>
<Button onClick={handleAddProduct} type="primary" style={{ marginBottom: 16 }}>
生成商品信息
</Button>
{/* <BatchSettings /> */}
</div>
<Table <Table
rowKey="id"
pagination={false} pagination={false}
components={components} components={components}
bordered bordered
dataSource={data} dataSource={productData}
columns={columns} columns={columns}
rowClassName="editable-row" rowClassName="editable-row"
/> />
......
...@@ -2,7 +2,15 @@ import React, { useState } from 'react'; ...@@ -2,7 +2,15 @@ import React, { useState } from 'react';
import { Form, notification, Col, Input, Icon, Row, Button, Select } from 'antd'; import { Form, notification, Col, Input, Icon, Row, Button, Select } from 'antd';
import { filterSpecId } from './utils'; import { filterSpecId } from './utils';
export const SelectSpecifications = ({ form, keys, formKey, labelName, specList, formValue }) => { export const SelectSpecifications = ({
form,
keys,
formKey,
labelName,
specList,
formValue,
labelKey,
}) => {
const { getFieldValue, getFieldDecorator, setFieldsValue } = form; const { getFieldValue, getFieldDecorator, setFieldsValue } = form;
const [countNumber, setCountNumber] = useState(0); // 添加计数器 const [countNumber, setCountNumber] = useState(0); // 添加计数器
...@@ -28,6 +36,12 @@ export const SelectSpecifications = ({ form, keys, formKey, labelName, specList, ...@@ -28,6 +36,12 @@ export const SelectSpecifications = ({ form, keys, formKey, labelName, specList,
}); });
}; };
const onChange = option => {
// setFieldsValue({
// [labelKey]: option.props.children,
// });
};
const formItemList = getFieldValue(keys); const formItemList = getFieldValue(keys);
const formItems = formItemList.map((k, index) => ( const formItems = formItemList.map((k, index) => (
<Col style={{ marginRight: 20 }} key={k}> <Col style={{ marginRight: 20 }} key={k}>
...@@ -45,7 +59,13 @@ export const SelectSpecifications = ({ form, keys, formKey, labelName, specList, ...@@ -45,7 +59,13 @@ export const SelectSpecifications = ({ form, keys, formKey, labelName, specList,
<> <>
<Form.Item label={labelName}> <Form.Item label={labelName}>
{getFieldDecorator(formKey)( {getFieldDecorator(formKey)(
<Select allowClear showSearch onChange={(val, option) => {}} filterOption={filterSpecId}> <Select
labelInValue
allowClear
showSearch
onChange={(_, option) => onChange(option)}
filterOption={filterSpecId}
>
{specList.map(item => ( {specList.map(item => (
<Select.Option key={item.specId} value={item.specId}> <Select.Option key={item.specId} value={item.specId}>
{item.specName} {item.specName}
......
...@@ -137,6 +137,7 @@ const OperationForm = props => { ...@@ -137,6 +137,7 @@ const OperationForm = props => {
keys="firstKeys" keys="firstKeys"
formKey="firstSpecId" formKey="firstSpecId"
formValue="firstValues" formValue="firstValues"
labelKey="firstSpecName"
labelName="一级规格" labelName="一级规格"
specList={specList} specList={specList}
/> />
...@@ -145,6 +146,7 @@ const OperationForm = props => { ...@@ -145,6 +146,7 @@ const OperationForm = props => {
keys="secondKeys" keys="secondKeys"
formKey="secondSpecId" formKey="secondSpecId"
formValue="secondValues" formValue="secondValues"
labelKey="secondSpecName"
labelName="二级规格" labelName="二级规格"
specList={specList} specList={specList}
/> />
......
...@@ -31,3 +31,25 @@ export const useSpecList = () => { ...@@ -31,3 +31,25 @@ export const useSpecList = () => {
export const filterSpecId = (input, option) => export const filterSpecId = (input, option) =>
option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0; option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
export const useEditProduct = () => [1];
export const dataInit = list => {
if (!list || !list.length) return;
const obj = {};
let finialList = [];
list.forEach(item => {
obj[item.firstSpecValue] = [];
});
list.forEach(item => obj[item.firstSpecValue].push(item));
const keys = Object.keys(obj);
keys.forEach(key => {
obj[key].forEach((i, index) => {
if (index === 0) {
i.length = obj[key].length;
}
});
finialList = finialList.concat(obj[key]);
return finialList;
});
};
...@@ -16,7 +16,7 @@ export default () => { ...@@ -16,7 +16,7 @@ export default () => {
*/ */
const [isEdit, setIsEdit] = useState(false); const [isEdit, setIsEdit] = useState(false);
const [categoryData, setCategoryData] = useState([]); const [categoryData, setCategoryData] = useState([]);
const [operationVisible, setOperationVisible] = useState(false); const [operationVisible, setOperationVisible] = useState(true);
const actionRef = useRef(); const actionRef = useRef();
const supplyPriceRef = useRef(); const supplyPriceRef = useRef();
const [supplyPrice, setSupplyPrice] = useState([]); const [supplyPrice, setSupplyPrice] = useState([]);
......
...@@ -69,6 +69,7 @@ export function createNewList(first, second, firstSpecId, secondSpecId) { ...@@ -69,6 +69,7 @@ export function createNewList(first, second, firstSpecId, secondSpecId) {
}); });
return; return;
} }
console.log(copy);
list.push(copy); list.push(copy);
}); });
} else if (second.length) { } else if (second.length) {
...@@ -83,7 +84,7 @@ export function createNewList(first, second, firstSpecId, secondSpecId) { ...@@ -83,7 +84,7 @@ export function createNewList(first, second, firstSpecId, secondSpecId) {
// 缺少一级和二级规格时生成的编辑表格 // 缺少一级和二级规格时生成的编辑表格
list.push(sku); list.push(sku);
} }
console.log(list);
return list; return list;
} }
...@@ -374,6 +375,7 @@ export function editColumns(methods, firstData, firstSpec, secondSpec, isJDGoods ...@@ -374,6 +375,7 @@ export function editColumns(methods, firstData, firstSpec, secondSpec, isJDGoods
align: 'center', align: 'center',
width: 100, width: 100,
render: (val, row) => { render: (val, row) => {
console.log(row);
const obj = { const obj = {
children: val, children: val,
props: {}, props: {},
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment