Commit 8a5a0130 authored by beisir's avatar beisir

fix: 生成表格校验

parent 03acb249
......@@ -2,16 +2,16 @@ const isProduction = process.env.NODE_ENV === 'production';
const isPre = process.env.PRE_ENV === 'pre';
const envAPi = {
api: '//backstms-yxm.liangkebang.net',
kdspOpApi: 'https://kdsp-operation-yxm.liangkebang.net',
kdspApi: 'https://sc-op-api-yxm.liangkebang.net',
goodsApi: 'https://sc-op-api-yxm.liangkebang.net',
querysApi: 'https://sc-settlement-api-yxm.liangkebang.net',
api: 'https://backstms-xyqb.liangkebang.net',
kdspOpApi: 'https://kdsp-operation-xyqb.liangkebang.net',
kdspApi: 'https://sc-op-api-xyqb.liangkebang.net',
goodsApi: 'https://sc-op-api-xyqb.liangkebang.net',
querysApi: 'https://sc-settlement-api-xyqb.liangkebang.net',
// goodsApi: '//192.168.188.111:7000',
prologueDomain: 'https://mall-yxm.liangkebang.net',
prologueDomain: 'https://mall-xyqb.liangkebang.net',
// qiniuHost: 'https://appsync.lkbang.net',
qiniuHost: 'https://kdspstatic.q-gp.com/',
opapiHost: 'https://opapi-yxm.liangkebang.net',
opapiHost: 'https://opapi-xyqb.liangkebang.net',
};
const prodApi = {
......
......@@ -5,16 +5,38 @@ import React, { useContext, useEffect, useRef, useState } from 'react';
const EditableContext = React.createContext<FormInstance<any> | null>(null);
interface PropType {
initData: any[];
};
interface Item {
key: string;
name: string;
age: string;
address: string;
}
interface EditableCellProps {
rowIndex: number;
title: React.ReactNode;
editable: boolean;
children: React.ReactNode;
dataIndex: keyof Item;
record: Item;
handleSave: (record: Item) => void;
}
interface EditableRowProps {
index: number;
}
interface DataType {
rowSpanCount?: number;
supplyPrice: number;
commissionRate: number;
marketPrice: number;
salePrice: number;
stock: number;
productStockWarning: number;
}
type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
// console.log('==========> index', props);
......@@ -29,15 +51,6 @@ const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
);
};
interface EditableCellProps {
rowIndex: number;
title: React.ReactNode;
editable: boolean;
children: React.ReactNode;
dataIndex: keyof Item;
record: Item;
handleSave: (record: Item) => void;
}
const EditableCell: React.FC<EditableCellProps> = (props) => {
const {
......@@ -50,73 +63,61 @@ const EditableCell: React.FC<EditableCellProps> = (props) => {
handleSave,
...restProps
} = props;
// console.log(props);
const form = useContext(EditableContext)!;
const save = async () => {
try {
console.log(rowIndex);
const { tableList } = await form.validateFields();
const tableList = form.getFieldValue('tableList');
handleSave(tableList);
} catch (errInfo) {
console.log('Save failed:', errInfo);
}
};
const childNode = <Form.Item
style={{ margin: 0 }}
name={['tableList', rowIndex, dataIndex]}
initialValue={record[dataIndex]}
rules={[ { required: true, message: `${title} is required.` }]}>
<InputNumber onBlur={save} />
</Form.Item>
let childNode = children;
if (editable) {
childNode = <Form.Item
style={{ margin: 0 }}
name={['tableList', rowIndex, dataIndex]}
// initialValue={record[dataIndex]}
rules={[{ required: true, message: `${title} is required.` }]}>
<InputNumber onBlur={save} />
</Form.Item>
}
return <td {...restProps}>{childNode}</td>;
};
type EditableTableProps = Parameters<typeof Table>[0];
interface DataType {
supplyPrice: number;
commissionRate: number;
marketPrice: number;
salePrice: number;
stock: number;
productStockWarning: number;
}
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
const EditFormTable: React.FC = () => {
const [dataSource, setDataSource] = useState<DataType[]>([
{
supplyPrice: 100,
commissionRate: 20,
marketPrice: 32,
salePrice: 100,
stock: 100,
productStockWarning: 100,
},
{
supplyPrice: 100,
commissionRate: 20,
marketPrice: 32,
salePrice: 100,
stock: 100,
productStockWarning: 100,
}
]);
// const form = useContext(EditableContext)!;
const EditFormTable = (props: PropType) => {
const { initData } = props;
// console.log(initData);
const [dataSource, setDataSource] = useState<DataType[]>([]);
const [form] = Form.useForm();
const [count, setCount] = useState(2);
useEffect(() => {
console.log('==============>坚听initData', initData);
form.setFieldsValue({
tableList: initData,
});
setDataSource(initData);
}, [initData])
const handleDelete = (key: React.Key) => {
const newData = dataSource.filter(item => item.key !== key);
setDataSource(newData);
};
const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
{
title: '一级规格',
dataIndex: 'firstSpecValue',
},
{
title: '二级规格',
dataIndex: 'secondSpecValue',
},
{
title: '供货价',
dataIndex: 'supplyPrice',
......@@ -149,23 +150,17 @@ const EditFormTable: React.FC = () => {
},
];
const handleAdd = () => {
console.log(form.getFieldsValue());
// const newData: DataType = {
// key: count,
// supplyPrice: 200,
// commissionRate: 20,
// marketPrice: 32,
// salePrice: 100,
// stock: 100,
// productStockWarning: 100,
// };
// setDataSource([...dataSource, newData]);
// setCount(count + 1);
const handleAdd = async () => {
try {
const { tableList } = await form.validateFields();
console.log(tableList);
} catch (errInfo) {
console.log('Save failed:', errInfo);
}
};
const handleSave = (row: DataType[]) => {
console.log('============>row', row);
// console.log('============>row', row);
// const newData = [...dataSource];
// const index = newData.findIndex(item => row.key === item.key);
// const item = newData[index];
......@@ -175,28 +170,32 @@ const EditFormTable: React.FC = () => {
// });
setDataSource([...row]);
};
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
// 根据这里做判断渲染表格
const columns = defaultColumns.map((col, colIndex) => {
if (!col.editable) {
return col;
}
// if (!col.editable) {
// return col;
// }
return {
...col,
onCell: (record: DataType, rowIndex: number) => ({
record,
rowIndex,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
}),
onCell: (record: DataType, rowIndex: number) => {
let rowSpan = null;
if (col.dataIndex === 'firstSpecValue') {
// console.log(record, rowSpan);
rowSpan = record.rowSpanCount ? record.rowSpanCount : 0;
}
return ({
rowSpan,
record,
rowIndex,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
});
}
};
});
......@@ -205,12 +204,17 @@ const EditFormTable: React.FC = () => {
<Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>
Add a row
</Button>
<Form form={form} component={false}>
<Form form={form} scrollToFirstError component={false}>
<EditableContext.Provider value={form}>
<Table
pagination={false}
size="small"
components={components}
components={{
body: {
row: EditableRow,
cell: EditableCell,
},
}}
bordered
dataSource={dataSource}
rowKey={(row, rowInd) => rowInd}
......
......@@ -42,7 +42,6 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => {
const [commonImageList, setCommonImageList] = useState([]);
const [detailImageList, setDetailImageList] = useState([]);
useEffect(() => {
console.log(id);
if (+id !== 0) {
console.log();
if (!Object.keys(editData).length) return;
......
import React from 'react';
export const ServiceContext = React.createContext(null);
......@@ -12,7 +12,13 @@ import FormPriceOrStock from './components/FormPriceOrStock';
import FormRuleSetting from './components/FormRuleSetting';
import FormSettlementOthers from './components/FormSettlementOthers';
import commonStyle from './common.less';
import { getProductDetail, merchantCategoryGetAll, merchantBrandList, merchantSpecList } from './service';
import {
getProductDetail,
merchantCategoryGetAll,
merchantBrandList,
merchantSpecList,
} from './service';
import { ServiceContext } from './context';
/**
* 服务商品改造-商品模块
......@@ -28,9 +34,9 @@ const ServiceGoods = options => {
const settingRef = useRef(null);
const settleOtrRef = useRef(null);
const [isEdit, setIsEdit] = useState(false);
const [productType, setProductType] = useState(1);
const [pageLoading, setPageLoading] = useState(false);
const [categoryList, setCategoryList] = useState([]); // 获取三级类目
const [brandList, setBrandList] = useState([]); // 获取商品牌
const [specList, setSpecList] = useState([]); // 规格列表
......@@ -91,10 +97,11 @@ const ServiceGoods = options => {
useEffect(() => {
(async () => {
setPageLoading(true);
await getMerchantCategory();
await getMerchantBrandList();
// await getMerchantCategory();
// await getMerchantBrandList();
await getMerchantSpecList();
if (pageId !== 0) {
setIsEdit(true);
await getProductDetailResponse();
}
setPageLoading(false);
......@@ -105,27 +112,29 @@ const ServiceGoods = options => {
<Spin tip="正在加载..." spinning={pageLoading} delay={100}>
<PageHeaderWrapper className={commonStyle.header}>
<WrapperContainer>
<Title title="商品类型" />
<TaskTypeSelect productType={productType} onChange={productChange} />
<Title title="商品基本信息编辑" />
<FormInformationBasic
ref={basicRef}
editData={editData}
categoryList={categoryList}
brandList={brandList}
/>
<Title title="价格与库存" />
<FormPriceOrStock ref={stockRef} specList={specList} editData={editData} />
<Title title="规则设置" />
<FormRuleSetting ref={settingRef} editData={editData} />
<FormSettlementOthers ref={settleOtrRef} editData={editData} />
<Button type="primary" onClick={submitEvent}>
Register
</Button>
<ServiceContext.Provider value={{ pageId, isEdit }}>
<Title title="商品类型" />
<TaskTypeSelect productType={productType} onChange={productChange} />
<Title title="商品基本信息编辑" />
<FormInformationBasic
ref={basicRef}
editData={editData}
categoryList={categoryList}
brandList={brandList}
/>
<Title title="价格与库存" />
<FormPriceOrStock ref={stockRef} specList={specList} editData={editData} />
<Title title="规则设置" />
<FormRuleSetting ref={settingRef} editData={editData} />
<FormSettlementOthers ref={settleOtrRef} editData={editData} />
<Button type="primary" onClick={submitEvent}>
Register
</Button>
</ServiceContext.Provider>
</WrapperContainer>
</PageHeaderWrapper>
</Spin>
......
import { ConsoleSqlOutlined } from '@ant-design/icons';
export const cleanArray = actual => {
const newArray = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
};
const createInitProduct = (skuItem, isCreate) => {
if (isCreate && Object.keys(skuItem).length > 5) {
return skuItem;
}
return {
// firstSpecValue: '',
// secondSpecValue: '',
weight: null,
productStockWarning: null,
marketPrice: null,
supplyPrice: null,
stock: null,
thirdSkuNo: null,
skuLink: null,
};
};
const initData = {
// firstSpecValue: '',
// secondSpecValue: '',
weight: null,
productStockWarning: null,
marketPrice: null,
supplyPrice: null,
stock: null,
thirdSkuNo: null,
skuLink: null,
};
const createSecondProduct = (secondSpecList, initItem, secondSpec, dataSource, callback) => {
secondSpecList.forEach(secondItem => {
console.log('============>', Object.keys(secondItem));
const specSecond =
Object.keys(secondItem).length < 2
? {
firstSpecId: initItem.firstSpecId,
firstSpecValue: initItem.firstSpecValue,
...initData,
}
: Object.assign({}, initItem); // 继承fist参数
if (callback) {
callback(specSecond);
}
specSecond.secondSpecId = secondSpec;
specSecond.secondSpecValue = secondItem.secondSpecValue;
dataSource.push(specSecond);
});
};
export const createProductData = ({ firstValues, secondValues, firstSpecId, secondSpecId }) => {
console.log(firstValues, secondValues);
const countRowSpan = {};
const dataSource = [];
if (firstValues.length) {
firstValues.forEach((fisrtItem, index) => {
const specFirst = createInitProduct(fisrtItem, true);
specFirst.firstSpecId = firstSpecId;
specFirst.firstSpecValue = fisrtItem.firstSpecValue;
if (secondValues.length) {
createSecondProduct(secondValues, specFirst, secondSpecId, dataSource, specSecond => {
if (!countRowSpan[specFirst.firstSpecValue]) {
countRowSpan[specFirst.firstSpecValue] = true;
specSecond.rowSpanCount = secondValues.length;
}
});
return;
}
dataSource.push(specFirst);
});
} else if (secondValues.length) {
// const childData = createInitProduct();
createSecondProduct(secondValues, initData, secondSpecId, dataSource);
} else {
const specFirst = createInitProduct();
dataSource.push(specFirst);
}
return dataSource;
};
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