Commit 8869885b authored by beisir's avatar beisir

fix: TS

parent f10cff00
import { Form } from '@ant-design/compatible'; import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css'; import '@ant-design/compatible/assets/index.css';
import { Card, Pagination, Table, notification, Drawer, Spin } from 'antd'; import { Card, Pagination, Table, notification, Drawer, Spin, Button } from 'antd';
import React, { Component } from 'react'; import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout'; import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva'; import { connect } from 'dva';
...@@ -24,6 +24,7 @@ import CreateModal from './createModal'; ...@@ -24,6 +24,7 @@ import CreateModal from './createModal';
import { column, JDSHOPID } from './staticdata'; import { column, JDSHOPID } from './staticdata';
import SearchForm from './SearchForm'; import SearchForm from './SearchForm';
import TempleatModal from './TempleatModal'; import TempleatModal from './TempleatModal';
import ServiceGoods from '../ServiceGoods';
@connect(({ goodsManage }) => ({ @connect(({ goodsManage }) => ({
goodsManage, goodsManage,
...@@ -48,6 +49,7 @@ class goodsManage extends Component { ...@@ -48,6 +49,7 @@ class goodsManage extends Component {
isAll: 0, isAll: 0,
templateList: [], templateList: [],
isType: '', isType: '',
serviceVisble: true,
}; };
currentLog = null; currentLog = null;
...@@ -115,7 +117,7 @@ class goodsManage extends Component { ...@@ -115,7 +117,7 @@ class goodsManage extends Component {
this.setState({ this.setState({
createloading: true, createloading: true,
}); });
const { data, msg } = await spuDetail({ id: spuId }); const { data, msg } = await spuDetail({ id: 894048258062 }); // spuId
if (data) { if (data) {
data.state = state; data.state = state;
data.pageProductType = productType; data.pageProductType = productType;
...@@ -290,6 +292,12 @@ class goodsManage extends Component { ...@@ -290,6 +292,12 @@ class goodsManage extends Component {
}); });
}; };
serviceVisbleChange = visble => {
this.setState({
serviceVisble: visble,
})
}
render() { render() {
const { const {
goodsManage: { tableData = {} }, goodsManage: { tableData = {} },
...@@ -303,6 +311,7 @@ class goodsManage extends Component { ...@@ -303,6 +311,7 @@ class goodsManage extends Component {
<PageHeaderWrapper> <PageHeaderWrapper>
<Spin spinning={this.state.createloading}> <Spin spinning={this.state.createloading}>
<Card> <Card>
<Button type="primary" onClick={() => this.serviceVisbleChange(true)}>new 新增商品</Button>
<SearchForm <SearchForm
handleSearch={this.handleSearch} handleSearch={this.handleSearch}
onReset={this.onReset} onReset={this.onReset}
...@@ -398,6 +407,8 @@ class goodsManage extends Component { ...@@ -398,6 +407,8 @@ class goodsManage extends Component {
isType={this.state.isType} isType={this.state.isType}
templateList={this.state.templateList} templateList={this.state.templateList}
/> />
{/* '894048258062' */}
<ServiceGoods visible={this.state.serviceVisble} onChange={this.serviceVisbleChange} id={894048258062} />
</Spin> </Spin>
</PageHeaderWrapper> </PageHeaderWrapper>
); );
......
import React from 'react'; import React from 'react';
import commonStyle from '../common.less'; import commonStyle from '../common.less';
export const WrapperContainer = props => ( export const WrapperContainer = props => (
<div className={commonStyle.container}>{props.children}</div> <div className={commonStyle.container}>{props.children}</div>
); );
......
import { InputNumber, InputRef } from 'antd'; import { InputNumber, Button, Form, Table } from 'antd';
import { Button, Form, Input, Popconfirm, Table } from 'antd'; import React, { useContext, createContext, useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import type { FormInstance } from 'antd/es/form'; import { ServiceContext } from '../context';
import React, { useContext, useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react';
const EditableContext = createContext(null);
const EditableContext = React.createContext<FormInstance<any> | null>(null);
const EditableRow= ({ index, ...props }) => {
interface DataType {
rowSpanCount?: number;
supplyPrice: number;
commissionRate: number;
marketPrice: number;
salePrice: number;
stock: number;
productStockWarning: number;
}
interface PropType {
initData: any[];
defaultColumns: any[];
setTableData: (item: DataType[]) => {};
};
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;
}
type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
// console.log('==========> index', props); // console.log('==========> index', props);
// const [form] = Form.useForm(); // const [form] = Form.useForm();
// console.log('==========>props', props) // console.log('==========>props', props)
...@@ -55,7 +18,7 @@ const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => { ...@@ -55,7 +18,7 @@ const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
}; };
const EditableCell: React.FC<EditableCellProps> = (props) => { const EditableCell = (props) => {
const { const {
rowIndex, rowIndex,
title, title,
...@@ -66,6 +29,7 @@ const EditableCell: React.FC<EditableCellProps> = (props) => { ...@@ -66,6 +29,7 @@ const EditableCell: React.FC<EditableCellProps> = (props) => {
handleSave, handleSave,
...restProps ...restProps
} = props; } = props;
const form = useContext(EditableContext)!; const form = useContext(EditableContext)!;
const save = async () => { const save = async () => {
try { try {
...@@ -77,15 +41,12 @@ const EditableCell: React.FC<EditableCellProps> = (props) => { ...@@ -77,15 +41,12 @@ const EditableCell: React.FC<EditableCellProps> = (props) => {
}; };
let childNode = children; let childNode = children;
// if (editable) {
childNode = <Form.Item childNode = <Form.Item
style={{ margin: 0 }} style={{ margin: 0 }}
name={['tableList', rowIndex, dataIndex]} name={['tableList', rowIndex, dataIndex]}
// initialValue={record[dataIndex]}
rules={[{ required: true, message: `${title} is required.` }]}> rules={[{ required: true, message: `${title} is required.` }]}>
{editable ?<InputNumber onBlur={save} /> : children[1]} {editable ? <InputNumber onBlur={save} /> : children[1]}
</Form.Item> </Form.Item>
// }
return <td {...restProps}>{childNode}</td>; return <td {...restProps}>{childNode}</td>;
}; };
...@@ -93,17 +54,14 @@ const EditableCell: React.FC<EditableCellProps> = (props) => { ...@@ -93,17 +54,14 @@ const EditableCell: React.FC<EditableCellProps> = (props) => {
const EditFormTable = forwardRef((props: PropType, ref) => { const EditFormTable = forwardRef((props, ref) => {
const { initData, defaultColumns, setTableData } = props; const { initData, defaultColumns, setTableData, mergeTable } = props;
// console.log(initData); const customer = useContext(ServiceContext);
const [dataSource, setDataSource] = useState<DataType[]>([]); const [dataSource, setDataSource] = useState([]);
const [form] = Form.useForm(); const [form] = Form.useForm();
useEffect(() => { useEffect(() => {
console.log('==============>坚听initData', initData); console.log('==============>坚听initData', initData);
form.setFieldsValue({ form.setFieldsValue({
tableList: initData, tableList: initData,
}); });
...@@ -119,15 +77,7 @@ const EditFormTable = forwardRef((props: PropType, ref) => { ...@@ -119,15 +77,7 @@ const EditFormTable = forwardRef((props: PropType, ref) => {
} }
}; };
const handleSave = (row: DataType[]) => { const handleSave = (row) => {
// console.log('============>row', row);
// const newData = [...dataSource];
// const index = newData.findIndex(item => row.key === item.key);
// const item = newData[index];
// newData.splice(index, 1, {
// ...item,
// ...row,
// });
setTableData([...row]); setTableData([...row]);
}; };
...@@ -148,19 +98,18 @@ const EditFormTable = forwardRef((props: PropType, ref) => { ...@@ -148,19 +98,18 @@ const EditFormTable = forwardRef((props: PropType, ref) => {
// 根据这里做判断渲染表格 // 根据这里做判断渲染表格
const columns = defaultColumns.map((col, colIndex) => { const columns = defaultColumns
// if (!col.editable) { .filter(item => {
// return col; // console.log('===============>column', item);
// } return !item.role || item.role.includes(customer.productType);
})
.map((col, colIndex) => {
return { return {
...col, ...col,
onCell: (record: DataType, rowIndex: number) => { onCell: (record, rowIndex) => {
let rowSpan = null; let rowSpan = null;
if (col.dataIndex === 'firstSpecValue') { if (col.dataIndex === 'firstSpecValue' && mergeTable) {
// console.log(record, rowSpan); rowSpan = record.rowSpanCount || 0;
rowSpan = record.rowSpanCount ? record.rowSpanCount : 0;
} }
return ({ return ({
...@@ -192,7 +141,7 @@ const EditFormTable = forwardRef((props: PropType, ref) => { ...@@ -192,7 +141,7 @@ const EditFormTable = forwardRef((props: PropType, ref) => {
bordered bordered
dataSource={dataSource} dataSource={dataSource}
rowKey={(row, rowInd) => rowInd} rowKey={(row, rowInd) => rowInd}
columns={columns as ColumnTypes} columns={columns}
/> />
</EditableContext.Provider> </EditableContext.Provider>
<Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>Add a row</Button> <Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>Add a row</Button>
......
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react'; import React, { useContext, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Cascader, Form, Input, Select } from 'antd'; import { Cascader, Form, Input, Select } from 'antd';
import { useParams } from 'react-router-dom'; import { formItemLayout } from '../config';
import { DefaultOptionType } from 'antd/lib/select'; import { ServiceContext } from '../context';
interface CategoryItem { const CreateSelectOption = optionList =>
id: number; optionList.map(brandItem => (
level: number;
name: string;
parentId: number;
children?: CategoryItem[];
}
interface BrandItem {
id: number;
name: string;
chineseName?: string;
chinesePinyin?: string;
englishName?: string;
firstLetter?: string;
horizontalLogo?: string;
logo?: string;
priority?: string;
}
interface PropsType {
editData: any;
categoryList: Array<CategoryItem>;
brandList: BrandItem[];
}
const categoryIdArrayList = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const formItemLayout = {
labelCol: {
sm: { span: 3 },
},
wrapperCol: {
sm: { span: 16 },
},
};
const CreateSelectOption = (optionList: BrandItem[]) =>
optionList.map((brandItem: BrandItem) => (
<Select.Option key={brandItem.id} value={brandItem.id}> <Select.Option key={brandItem.id} value={brandItem.id}>
{brandItem.name} {brandItem.name}
</Select.Option> </Select.Option>
)); ));
const fileterBrandOptions = ( const fileterBrandOptions = (
input: string, input,
options: { key: string; value: number; children: string }, options,
) => options.children.includes(input); ) => options.children.includes(input);
const filterCategoryOptions = (inputValue: string, path: DefaultOptionType[]) => const filterCategoryOptions = (inputValue, path) =>
path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1); path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
const FormInformationBasic = forwardRef((props: PropsType, ref) => { const FormInformationBasic = forwardRef((props, ref) => {
const { editData, categoryList, brandList } = props; const { editData, categoryList, brandList } = props;
const [form] = Form.useForm(); const [form] = Form.useForm();
...@@ -102,23 +33,28 @@ const FormInformationBasic = forwardRef((props: PropsType, ref) => { ...@@ -102,23 +33,28 @@ const FormInformationBasic = forwardRef((props: PropsType, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
reset: form.resetFields,
})); }));
const { id } = useParams<any>(); const customer = useContext(ServiceContext);
useEffect(() => { useEffect(() => {
if (+id !== 0) { if (customer.isEdit) {
if (!Object.keys(editData).length) return; if (!Object.keys(editData).length) return;
const { serviceItem } = editData.skuList[0]; const initValues = {
form.setFieldsValue({
brandId: editData.brandId, brandId: editData.brandId,
supplierId: editData.supplierId, supplierId: editData.supplierId,
name: editData.name, name: editData.name,
categoryId: [editData.firstCategoryId, editData.secondCategoryId, editData.thirdCategoryId], categoryId: [editData.firstCategoryId, editData.secondCategoryId, editData.thirdCategoryId],
description: serviceItem.description, description: null,
}); };
if (customer.isCard) {
const { serviceItem } = editData.skuList[0];
initValues.description = (serviceItem || {}).description || null;
}
form.setFieldsValue(initValues);
} }
}, [id, editData]); }, [customer.isEdit, editData]);
const onFinish = (values: any) => { const onFinish = values => {
console.log('Received values of form: ', values); console.log('Received values of form: ', values);
}; };
...@@ -166,13 +102,13 @@ const FormInformationBasic = forwardRef((props: PropsType, ref) => { ...@@ -166,13 +102,13 @@ const FormInformationBasic = forwardRef((props: PropsType, ref) => {
/> />
</Form.Item> </Form.Item>
<Form.Item {customer.isCard ? <Form.Item
name="description" name="description"
label="描述" label="描述"
rules={[{ required: true, message: '请输入描述!' }]} rules={[{ required: true, message: '请输入描述!' }]}
> >
<Input.TextArea showCount maxLength={100} placeholder="请输入描述!" /> <Input.TextArea showCount maxLength={100} placeholder="请输入描述!" />
</Form.Item> </Form.Item> : null}
</Form> </Form>
); );
}); });
......
import { ConsoleSqlOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; import { ConsoleSqlOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, Select, Space, Modal, InputNumber, notification } from 'antd'; import { Button, Form, Input, Select, Space, Modal, InputNumber, notification } from 'antd';
import React, { useState, forwardRef, useImperativeHandle, useRef, useEffect, useContext } from 'react'; import React, { useState, forwardRef, useImperativeHandle, useRef, useEffect, useContext } from 'react';
import { useParams } from 'react-router-dom';
import { formItemLayout, StaticColumns } from '../config'; import { formItemLayout, StaticColumns } from '../config';
import EditFormTable from './EditFormTable'; import EditFormTable from './EditFormTable';
import { createProductData, cleanArray } from '../utils'; import { createProductData, cleanArray } from '../utils';
import { ServiceContext } from '../context'; import { ServiceContext } from '../context';
import { ColumnTypes } from '../type';
const { Option } = Select;
interface SpecItem {
specId: number;
specName: string;
}
interface PropsType {
editData: any;
specList: Array<SpecItem>;
}
const validatorSpecValue = (value, list, index, specName) => { const validatorSpecValue = (value, list, index, specName) => {
const checkList = list.filter((item, ind) => { const checkList = list.filter((item, ind) => {
if (ind === index) { if (ind === index) {
...@@ -49,11 +35,14 @@ const SpecificationTemplate = (props, _) => { ...@@ -49,11 +35,14 @@ const SpecificationTemplate = (props, _) => {
// onChange(); // onChange();
}; };
const inputOnblurEvent = () => { const inputOnblurEvent = event => {
// onChange(); console.log(event.target.value);
if (event.target.value) {
onChange();
}
} }
const bundlePlusAddSpecEvent = (addCallback: () => void) => { const bundlePlusAddSpecEvent = addCallback => {
console.log(name); console.log(name);
const specId = form.getFieldValue(name); const specId = form.getFieldValue(name);
if (!specId) { if (!specId) {
...@@ -64,12 +53,12 @@ const SpecificationTemplate = (props, _) => { ...@@ -64,12 +53,12 @@ const SpecificationTemplate = (props, _) => {
return; return;
} }
addCallback(); addCallback();
// inputOnblurEvent(); onChange();
}; };
const bundlePlusRemoveSpecEvent = (removeCallback, fieldName) => { const bundlePlusRemoveSpecEvent = (removeCallback, fieldName) => {
removeCallback(fieldName) removeCallback(fieldName)
// inputOnblurEvent(); onChange();
} }
return ( return (
...@@ -153,7 +142,7 @@ const originItems = { ...@@ -153,7 +142,7 @@ const originItems = {
// 编辑回显示时只获取用到的数据 // 编辑回显示时只获取用到的数据
const filterItem = skuItem => { const filterItem = skuItem => {
const { imageList, serviceItem, ...argsItem } = skuItem; const { serviceItem, ...argsItem } = skuItem;
argsItem.disabled = true; argsItem.disabled = true;
return argsItem; return argsItem;
}; };
...@@ -186,27 +175,16 @@ const CreateBatchFormItems = ({ batchChange, editRef, defaultColumns }) => { ...@@ -186,27 +175,16 @@ const CreateBatchFormItems = ({ batchChange, editRef, defaultColumns }) => {
<InputNumber placeholder={item.title} /> <InputNumber placeholder={item.title} />
</Form.Item> </Form.Item>
)); ));
console.log(formItems.length);
// const batchEvent = () => {
// const batchItem = form.getFieldValue('batchItem');
// console.log(batchItem);
// // editRef.current.form.setFieldsValue({
// // });
// }
return <> return <>
{formItems.length && <Space style={{ marginBottom: 20 }}> {formItems.length ? <Space style={{ marginBottom: 20 }}>
{formItems.concat(<Button key="batch" type="primary" onClick={batchChange}>批量设置</Button>)} {formItems.concat(<Button key="batch" type="primary" onClick={batchChange}>批量设置</Button>)}
</Space>} </Space> : null }
</>; </>;
}; };
const FormPriceOrStock = forwardRef((props: PropsType, ref) => { const FormPriceOrStock = forwardRef((props, ref) => {
const { specList, editData } = props; const { specList, editData, onSpecChange } = props;
const editRef = useRef(null); const editRef = useRef(null);
const customer = useContext(ServiceContext); const customer = useContext(ServiceContext);
const [form] = Form.useForm(); const [form] = Form.useForm();
...@@ -221,6 +199,7 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -221,6 +199,7 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
const [defaultColumns, setDefaultColumns] = useState([]); const [defaultColumns, setDefaultColumns] = useState([]);
const [tableData, setTableData] = useState([]); const [tableData, setTableData] = useState([]);
const [mergeTable, setMergeTable] = useState(false);
const onCheck = async () => { const onCheck = async () => {
try { try {
...@@ -237,7 +216,6 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -237,7 +216,6 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
columsData.push({ columsData.push({
title: specData.firstSpec, title: specData.firstSpec,
dataIndex: 'firstSpecValue', dataIndex: 'firstSpecValue',
role: [],
}); });
} }
...@@ -245,15 +223,10 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -245,15 +223,10 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
columsData.push({ columsData.push({
title: specData.secondSpec, title: specData.secondSpec,
dataIndex: 'secondSpecValue', dataIndex: 'secondSpecValue',
role: [],
}); });
} }
if (!columsData.length) { const dynamicColumns = [
return;
}
const dynamicColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
...columsData, ...columsData,
...StaticColumns, ...StaticColumns,
]; ];
...@@ -264,7 +237,6 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -264,7 +237,6 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
try { try {
const values = await form.validateFields(); const values = await form.validateFields();
CreateColumnsEvent(values); CreateColumnsEvent(values);
const cleanValues = { const cleanValues = {
firstValues: cleanArray(values.firstSpecValue), firstValues: cleanArray(values.firstSpecValue),
secondValues: cleanArray(values.secondSpecValue), secondValues: cleanArray(values.secondSpecValue),
...@@ -272,12 +244,20 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -272,12 +244,20 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
secondSpecId: values.secondSpecId, secondSpecId: values.secondSpecId,
}; };
const newData = createProductData(cleanValues); const newData = createProductData(cleanValues);
setMergeTable(Boolean(cleanValues.secondValues.length));
setTableData(newData); setTableData(newData);
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }
}; };
const firstOnChangeEvent = () => {
const firstSpecValue = form.getFieldValue('firstSpecValue');
const firstSpecValueList = cleanArray(firstSpecValue).map(item => item.firstSpecValue);
onSpecChange(firstSpecValueList);
}
const batchChange = () => { const batchChange = () => {
const batchItem = form.getFieldValue('batchItem') const batchItem = form.getFieldValue('batchItem')
const batchItemKey = Object.keys(batchItem); const batchItemKey = Object.keys(batchItem);
...@@ -298,8 +278,9 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -298,8 +278,9 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
reset: form.resetFields,
})); }));
const { id } = useParams<any>();
useEffect(() => { useEffect(() => {
if (customer.isEdit) { if (customer.isEdit) {
if (!Object.keys(editData).length) return; if (!Object.keys(editData).length) return;
...@@ -317,6 +298,7 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -317,6 +298,7 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
}; };
form.setFieldsValue(specData); // 设置规格数据 form.setFieldsValue(specData); // 设置规格数据
setSpecInitValue(specData); // 缓存规格数据 setSpecInitValue(specData); // 缓存规格数据
firstOnChangeEvent(); // 触发成底部动态表格数据
onFinish(); // 触发生成表格 onFinish(); // 触发生成表格
} }
}, [customer.isEdit, editData]); }, [customer.isEdit, editData]);
...@@ -332,9 +314,9 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -332,9 +314,9 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
> >
<SpecificationTemplate <SpecificationTemplate
form={form} form={form}
onChange={onFinish}
label="一级规格" label="一级规格"
name="firstSpecId" name="firstSpecId"
onChange={firstOnChangeEvent}
selectName="firstSpec" selectName="firstSpec"
specName="firstSpecValue" specName="firstSpecValue"
specList={specList} specList={specList}
...@@ -342,7 +324,6 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -342,7 +324,6 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
/> />
<SpecificationTemplate <SpecificationTemplate
form={form} form={form}
onChange={onFinish}
label="二级规格" label="二级规格"
name="secondSpecId" name="secondSpecId"
selectName="secondSpec" selectName="secondSpec"
...@@ -355,8 +336,18 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => { ...@@ -355,8 +336,18 @@ const FormPriceOrStock = forwardRef((props: PropsType, ref) => {
生成商品信息 生成商品信息
</Button> </Button>
</div> </div>
<CreateBatchFormItems batchChange={batchChange} editRef={editRef} defaultColumns={defaultColumns} /> <CreateBatchFormItems
<EditFormTable ref={editRef} defaultColumns={defaultColumns} setTableData={setTableData} initData={tableData} /> batchChange={batchChange}
editRef={editRef}
defaultColumns={defaultColumns}
/>
<EditFormTable
ref={editRef}
mergeTable={mergeTable}
setTableData={setTableData}
defaultColumns={defaultColumns}
initData={tableData}
/>
</Form> </Form>
); );
}); });
......
import { Form, Input, Select, Checkbox, DatePicker, Radio, InputNumber } from 'antd'; import { Form, Input, Select, Checkbox, DatePicker } from 'antd';
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react'; import React, { useState, useEffect, forwardRef, useImperativeHandle, useContext } from 'react';
import moment from 'moment'; import moment from 'moment';
import { useParams } from 'react-router-dom'; import { WeeksList, formItemLayout } from '../config';
import UploadImage from './UploadImage'; import { ServiceContext } from '../context';
import { WeeksList } from '../config';
const { Option } = Select; const { Option } = Select;
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
const formItemLayout = {
labelCol: {
sm: { span: 3 },
},
wrapperCol: {
sm: { span: 16 },
},
};
const WeekCheckBox = () => const WeekCheckBox = () =>
WeeksList.map(item => ( WeeksList.map(item => (
...@@ -31,19 +22,15 @@ const rangeConfig = { ...@@ -31,19 +22,15 @@ const rangeConfig = {
rules: [{ type: 'array', required: true, message: 'Please select time!' }], rules: [{ type: 'array', required: true, message: 'Please select time!' }],
}; };
const FormRuleSetting = forwardRef((props: { editData: any }, ref) => { const FormRuleSetting = forwardRef((props, ref) => {
const [form] = Form.useForm();
const { editData } = props; const { editData } = props;
const [form] = Form.useForm();
const url = 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'; const customer = useContext(ServiceContext);
const { id } = useParams<any>();
const [imageList, setImageList] = useState([]); const [imageList, setImageList] = useState([]);
const [commonImageList, setCommonImageList] = useState([]); const [commonImageList, setCommonImageList] = useState([]);
const [detailImageList, setDetailImageList] = useState([]); const [detailImageList, setDetailImageList] = useState([]);
useEffect(() => { useEffect(() => {
if (+id !== 0) { if (customer.isEdit) {
console.log();
if (!Object.keys(editData).length) return; if (!Object.keys(editData).length) return;
setImageList(editData.commonImageList); setImageList(editData.commonImageList);
setCommonImageList(editData.commonImageList); setCommonImageList(editData.commonImageList);
...@@ -62,15 +49,9 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => { ...@@ -62,15 +49,9 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => {
ruleDescription: serviceItem.ruleDescription, // 规则说明 ruleDescription: serviceItem.ruleDescription, // 规则说明
applyScope: serviceItem.applyScope, // 适用范围 applyScope: serviceItem.applyScope, // 适用范围
tips: serviceItem.tips, // 温馨提示 tips: serviceItem.tips, // 温馨提示
imageList: editData.commonImageList,
commonImageList: editData.commonImageList,
detailImageList: editData.detailImageList,
appointment: serviceItem.appointment, // 预约
receptionVolume: serviceItem.receptionVolume, // 接待数量
}); });
} }
}, [id, editData]); }, [customer.isEdit, editData]);
const onCheck = async () => { const onCheck = async () => {
try { try {
...@@ -90,9 +71,10 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => { ...@@ -90,9 +71,10 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
reset: form.resetFields,
})); }));
const onFinish = (values: any) => { const onFinish = values => {
console.log('Received values of form: ', values); console.log('Received values of form: ', values);
}; };
return ( return (
...@@ -119,8 +101,6 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => { ...@@ -119,8 +101,6 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => {
commonImageList, commonImageList,
detailImageList, detailImageList,
appointment: null, // 预约
receptionVolume: null,
}} }}
scrollToFirstError scrollToFirstError
> >
...@@ -196,65 +176,6 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => { ...@@ -196,65 +176,6 @@ const FormRuleSetting = forwardRef((props: { editData: any }, ref) => {
placeholder="请输入温馨提示,200字以内 例如:全场通用例如:\n不兑零" placeholder="请输入温馨提示,200字以内 例如:全场通用例如:\n不兑零"
/> />
</Form.Item> </Form.Item>
<Form.Item
label="封面图片"
name="commonImageList"
extra={`建议尺寸: ##宽##高 (${commonImageList.length} / 1) `}
rules={[
{ required: true, type: 'array', message: '请输入温馨提示', validateTrigger: 'submit' },
]}
>
<UploadImage
name="commonImageList"
limit={1}
pictures={commonImageList}
setPictureList={setCommonImageList}
/>
</Form.Item>
<Form.Item
label="商品图片"
name="imageList"
extra={`建议尺寸: ##宽##高 (${imageList.length} / 11) `}
rules={[
{ required: true, type: 'array', message: '请输入温馨提示', validateTrigger: 'submit' },
]}
>
<UploadImage
name="imageList"
limit={11}
pictures={imageList}
setPictureList={setImageList}
/>
</Form.Item>
<Form.Item
label="商品详情图"
name="detailImageList"
extra={`最多上传30张,${detailImageList.length} / 30`}
rules={[
{ required: true, type: 'array', message: '请输入温馨提示', validateTrigger: 'submit' },
]}
>
<UploadImage
name="detailImageList"
limit={4}
pictures={detailImageList}
setPictureList={setDetailImageList}
/>
</Form.Item>
<Form.Item name="appointment" label="预约">
<Radio.Group>
<Radio value={1}></Radio>
<Radio value={0}></Radio>
</Radio.Group>
</Form.Item>
<Form.Item
name="receptionVolume"
label="每日最低接待量"
rules={[{ required: true, message: '每日最低接待量' }]}
>
<InputNumber min={0} style={{ width: 200 }} placeholder="请输入每日最低接待量" />
</Form.Item>
</Form> </Form>
</> </>
); );
......
import React, { useState, useEffect, useContext, forwardRef, useImperativeHandle } from 'react';
import { Form } from 'antd';
import { ServiceContext } from '../context';
import UploadImage from './UploadImage';
import { formItemLayout } from '../config';
const FormRuleVPictures = forwardRef((props, ref) => {
const { editData, specKeyItem } = props;
const [form] = Form.useForm();
const [imageList, setImageList] = useState({});
const [commonImageList, setCommonImageList] = useState([]);
const [detailImageList, setDetailImageList] = useState([]);
const customer = useContext(ServiceContext);
useEffect(() => {
if (customer.isEdit) {
console.log('==============>图片', editData)
if (!Object.keys(editData).length) return;
setCommonImageList(editData.commonImageList); // 编辑状态下设置公共图
setDetailImageList(editData.detailImageList); // 编辑状态下设置详情图
const commImg = editData.skuList.reduce((orgin, item) => {
const keyString = `${item.firstSpecValue}`; // _${item.firstSpecId}
if (!Object.keys(orgin).includes(keyString)) {
orgin[keyString] = item.imageList;
}
return orgin;
}, {});
setImageList(commImg);
form.setFieldsValue({
imageList: commImg,
commonImageList: editData.commonImageList,
detailImageList: editData.detailImageList,
});
}
}, [customer.isEdit, editData]);
useEffect(() => {
const newImageList = specKeyItem.reduce((origin, item) => {
const showItem = imageList[item] || [];
origin[item] = showItem;
return origin;
}, {});
setImageList(newImageList);
}, [specKeyItem])
const onCheck = async () => {
try {
const values = await form.validateFields();
console.log(values)
return values;
} catch (errorInfo) {
return null;
}
};
useImperativeHandle(ref, () => ({
onCheck,
reset: form.resetFields,
}));
const onFinish = values => {
console.log('Received values of form: ', values);
};
const onPictureSuccessEvent = (imgList, key) => {
setImageList({
...imageList,
[key]: imgList,
});
}
return (
<>
<Form
{...formItemLayout}
form={form}
name="register"
onFinish={onFinish}
initialValues={{
imageList,
commonImageList,
detailImageList,
}}
scrollToFirstError
>
<Form.Item
label="封面图片"
name="commonImageList"
extra={`建议尺寸: ##宽##高 (${commonImageList.length} / 1) `}
rules={[
{ required: true, type: 'array', message: '请输入温馨提示', validateTrigger: 'submit' },
]}
>
<UploadImage
name="commonImageList"
limit={1}
pictures={commonImageList}
setPictureList={setCommonImageList}
/>
</Form.Item>
{Object.keys(imageList).map(key =>
<Form.Item
key={key}
label={`商品图片(${key})`}
name={['imageList', key]}
extra={`建议尺寸: ##宽##高 (${imageList[key].length} / 11) `}
rules={[
{ required: true, type: 'array', message: '请输入温馨提示', validateTrigger: 'submit' },
]}
>
<UploadImage
name={key}
limit={11}
pictures={imageList[key]}
setPictureList={list => onPictureSuccessEvent(list, key)}
/>
</Form.Item>)}
<Form.Item
label="商品详情图"
name="detailImageList"
extra={`最多上传30张,${detailImageList.length} / 30`}
rules={[
{ required: true, type: 'array', message: '请输入温馨提示', validateTrigger: 'submit' },
]}
>
<UploadImage
name="detailImageList"
limit={4}
pictures={detailImageList}
setPictureList={setDetailImageList}
/>
</Form.Item>
</Form>
</>
);
});
export default FormRuleVPictures;
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react'; import React, { useContext, useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select, Checkbox, Radio, Space, InputNumber, Switch } from 'antd'; import { Form, Input, Select, Checkbox, Radio, Space, InputNumber } from 'antd';
import { useParams } from 'react-router-dom';
import { Title } from './CommonTemplate'; import { Title } from './CommonTemplate';
import { formItemLayout } from '../config'; import { formItemLayout } from '../config';
import { ServiceContext } from '../context';
interface PropsType { const FormSettlementOthers = forwardRef((props, ref) => {
editData: any;
}
const FormSettlementOthers = forwardRef((props: PropsType, ref) => {
const { editData } = props; const { editData } = props;
const [form] = Form.useForm(); const [form] = Form.useForm();
...@@ -26,8 +22,9 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => { ...@@ -26,8 +22,9 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
reset: form.resetFields,
})); }));
const { id } = useParams<any>(); const customer = useContext(ServiceContext);
const [initValue, setInitValue] = useState({ const [initValue, setInitValue] = useState({
settlementMethod: 1, settlementMethod: 1,
limitPurchase: null, // 是否限购1:限购/0:不限购 limitPurchase: null, // 是否限购1:限购/0:不限购
...@@ -35,10 +32,13 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => { ...@@ -35,10 +32,13 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => {
limitPurchaseCycle: null, // 限购周期1:每天/7:7天/30:30天 limitPurchaseCycle: null, // 限购周期1:每天/7:7天/30:30天
limitPurchaseQuantity: null, // 限购数量 limitPurchaseQuantity: null, // 限购数量
packageContent: '', packageContent: '',
appointment: null, // 预约
receptionVolume: null,
}); });
useEffect(() => { useEffect(() => {
if (+id !== 0) { if (customer.isEdit) {
if (!Object.keys(editData).length) return; if (!Object.keys(editData).length) return;
const { serviceItem } = editData.skuList[0]; const { serviceItem } = editData.skuList[0];
...@@ -49,20 +49,22 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => { ...@@ -49,20 +49,22 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => {
limitPurchaseCycle: serviceItem.limitPurchaseCycle, // 限购周期1:每天/7:7天/30:30天 limitPurchaseCycle: serviceItem.limitPurchaseCycle, // 限购周期1:每天/7:7天/30:30天
limitPurchaseQuantity: serviceItem.limitPurchaseQuantity, // 限购数量 limitPurchaseQuantity: serviceItem.limitPurchaseQuantity, // 限购数量
packageContent: serviceItem.packageContent, packageContent: serviceItem.packageContent,
appointment: serviceItem.appointment, // 预约
receptionVolume: serviceItem.receptionVolume, // 接待数量
}; };
form.setFieldsValue(data); form.setFieldsValue(data);
setInitValue({ ...data }); setInitValue({ ...data });
} }
}, [id, editData]); }, [customer.isEdit, editData]);
useEffect(() => {}, [form]); useEffect(() => {}, [form]);
const onFinish = (values: any) => { const onFinish = values => {
console.log('Received values of form: ', values); console.log('Received values of form: ', values);
}; };
const radioChangeEvent = (key: string) => { const radioChangeEvent = key => {
const value = form.getFieldValue(key); const value = form.getFieldValue(key);
setInitValue({ setInitValue({
...initValue, ...initValue,
...@@ -71,7 +73,7 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => { ...@@ -71,7 +73,7 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => {
}; };
const AuditLimitPurchaseType = () => { const AuditLimitPurchaseType = () => {
const limitPurchaseType: number = form.getFieldValue('limitPurchaseType'); const limitPurchaseType = form.getFieldValue('limitPurchaseType');
if (limitPurchaseType === 1) { if (limitPurchaseType === 1) {
return null; return null;
} }
...@@ -133,6 +135,19 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => { ...@@ -133,6 +135,19 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => {
initialValues={initValue} initialValues={initValue}
scrollToFirstError scrollToFirstError
> >
<Form.Item name="appointment" label="预约">
<Radio.Group>
<Radio value={1}></Radio>
<Radio value={0}></Radio>
</Radio.Group>
</Form.Item>
<Form.Item
name="receptionVolume"
label="每日最低接待量"
rules={[{ required: true, message: '每日最低接待量' }]}
>
<InputNumber min={0} style={{ width: 200 }} placeholder="请输入每日最低接待量" />
</Form.Item>
<Title title="结算信息" /> <Title title="结算信息" />
<Form.Item <Form.Item
name="packageContent" name="packageContent"
...@@ -155,7 +170,6 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => { ...@@ -155,7 +170,6 @@ const FormSettlementOthers = forwardRef((props: PropsType, ref) => {
<Checkbox onChange={() => radioChangeEvent('limitPurchase')}> <Checkbox onChange={() => radioChangeEvent('limitPurchase')}>
<b style={{ marginLeft: 10 }}>启用限购</b> <b style={{ marginLeft: 10 }}>启用限购</b>
<span style={{ marginLeft: 10 }} className="ant-form-text"> <span style={{ marginLeft: 10 }} className="ant-form-text">
{' '}
限制每人可购买数量 限制每人可购买数量
</span> </span>
</Checkbox> </Checkbox>
......
import React, { useContext } from 'react';
import { TaskList } from '../config';
import { ServiceContext } from '../context';
import commonStyle from '../common.less';
export const TaskTypeSelect = props => {
const customer = useContext(ServiceContext);
const selectTabs = task => {
if (!customer.isEdit) {
props.onChange(task);
}
}
return (
<div className={commonStyle.prodcutContent}>
{TaskList.map(task => {
const activeClassName = props.productType === task.type ? commonStyle.activeCard : '';
return (
<dl
key={task.type}
onClick={() => selectTabs(task)}
className={`${commonStyle.productCard} ${activeClassName}`}
>
<dd className="prodcut-name">{task.name}</dd>
<dd className="prodcut-desc">({task.desc})</dd>
</dl>
);
})}
</div>
);
}
import React from 'react';
import { TaskList } from '../config';
import { Task } from '../type';
import commonStyle from '../common.less';
export const TaskTypeSelect = (props: { productType: number; onChange: (task: Task) => void }) => (
<div className={commonStyle.prodcutContent}>
{TaskList.map((task: Task) => {
const activeClassName: string = props.productType === task.type ? commonStyle.activeCard : '';
return (
<dl
key={task.type}
onClick={() => props.onChange(task)}
className={`${commonStyle.productCard} ${activeClassName}`}
>
<dd className="prodcut-name">{task.name}</dd>
<dd className="prodcut-desc">({task.desc})</dd>
</dl>
);
})}
</div>
);
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from '@ant-design/icons';
import { Modal, Upload, notification, Spin } from 'antd'; import { Modal, Upload, notification, Spin } from 'antd';
import type { UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import lodash from 'lodash'; import lodash from 'lodash';
import { merchantUpload } from '../service'; import { merchantUpload } from '../service';
type PicturesType = {
name?: string;
limit?: number;
uploadParams?: UploadProps;
pictures?: Array<string>;
onChange?: (path: string[]) => void;
setPictureList?: (item: string[]) => void
};
const MAX_FILE_SIZE = 5; const MAX_FILE_SIZE = 5;
const UNIT = 1024 * 1024; const UNIT = 1024 * 1024;
...@@ -33,7 +22,7 @@ const uploadButton = ( ...@@ -33,7 +22,7 @@ const uploadButton = (
</div> </div>
); );
const UploadImage: React.FC<PicturesType> = props => { const UploadImage = props => {
const { const {
name = `${Date.now()}`, name = `${Date.now()}`,
limit = 1, limit = 1,
...@@ -46,11 +35,11 @@ const UploadImage: React.FC<PicturesType> = props => { ...@@ -46,11 +35,11 @@ const UploadImage: React.FC<PicturesType> = props => {
const [previewVisible, setPreviewVisible] = useState(false); const [previewVisible, setPreviewVisible] = useState(false);
const [previewImage, setPreviewImage] = useState(''); const [previewImage, setPreviewImage] = useState('');
const [previewTitle, setPreviewTitle] = useState(''); const [previewTitle, setPreviewTitle] = useState('');
const [fileList, setFileList] = useState<UploadFile[]>([]); const [fileList, setFileList] = useState([]);
const fileListRef = useRef([]); const fileListRef = useRef([]);
useEffect(() => { useEffect(() => {
const newPictures = pictures.map((url: string, ind: number) => ({ const newPictures = pictures.map((url, ind) => ({
url, url,
name: url, name: url,
uid: `${ind}`, uid: `${ind}`,
...@@ -61,7 +50,7 @@ const UploadImage: React.FC<PicturesType> = props => { ...@@ -61,7 +50,7 @@ const UploadImage: React.FC<PicturesType> = props => {
const handleCancel = () => setPreviewVisible(false); const handleCancel = () => setPreviewVisible(false);
const handlePreview = async (file: UploadFile) => { const handlePreview = async file => {
setPreviewImage(file.url); setPreviewImage(file.url);
setPreviewVisible(true); setPreviewVisible(true);
setPreviewTitle(file.name || (file.url).substring(file.url.lastIndexOf('/') + 1)); setPreviewTitle(file.name || (file.url).substring(file.url.lastIndexOf('/') + 1));
...@@ -116,9 +105,7 @@ const UploadImage: React.FC<PicturesType> = props => { ...@@ -116,9 +105,7 @@ const UploadImage: React.FC<PicturesType> = props => {
// } // }
// }; // };
const checkFile = file => { const checkFile = file => new Promise(resolve => {
console.log(file);
return new Promise(resolve => {
const curType = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase(); const curType = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
const fileType = ['jpg', 'jpeg', 'png']; const fileType = ['jpg', 'jpeg', 'png'];
if (!fileType.includes(curType)) { if (!fileType.includes(curType)) {
...@@ -136,8 +123,7 @@ const UploadImage: React.FC<PicturesType> = props => { ...@@ -136,8 +123,7 @@ const UploadImage: React.FC<PicturesType> = props => {
return resolve(null); return resolve(null);
} }
return resolve(file); return resolve(file);
}); })
}
const imageLoading = (file, ret) => new Promise(resolve => { const imageLoading = (file, ret) => new Promise(resolve => {
const reader = new FileReader(); const reader = new FileReader();
......
...@@ -75,7 +75,7 @@ export const StaticColumns = [ ...@@ -75,7 +75,7 @@ export const StaticColumns = [
title: '佣金费率', title: '佣金费率',
dataIndex: 'commissionRate', dataIndex: 'commissionRate',
editable: true, editable: true,
role: [], role: [3],
}, },
{ {
title: '市场价', title: '市场价',
...@@ -91,6 +91,13 @@ export const StaticColumns = [ ...@@ -91,6 +91,13 @@ export const StaticColumns = [
title: '库存', title: '库存',
dataIndex: 'stock', dataIndex: 'stock',
editable: true, editable: true,
role: [3],
},
{
title: '库存',
dataIndex: 'productStock',
editable: true,
role: [1, 2],
}, },
{ {
title: '库存预警阈值', title: '库存预警阈值',
...@@ -98,4 +105,18 @@ export const StaticColumns = [ ...@@ -98,4 +105,18 @@ export const StaticColumns = [
editable: true, editable: true,
role: [], role: [],
}, },
{
title: '商品自编码',
dataIndex: 'thirdSkuNo',
editable: true,
role: [1, 2],
inputType: 'text',
},
{
title: '京东链接',
dataIndex: 'skuLink',
editable: true,
role: [1, 2],
inputType: 'text',
},
]; ];
import React, { useState, useRef, useEffect } from 'react'; import React, { useState, useRef, useEffect, useCallback } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout'; import { Spin, Button, Modal } from 'antd';
import { Spin, Button } from 'antd';
import { Title, WrapperContainer } from './components/CommonTemplate'; import { Title, WrapperContainer } from './components/CommonTemplate';
import { TaskTypeSelect } from './components/TaskTypeSelect'; import { TaskTypeSelect } from './components/TaskTypeSelect';
import { Task } from './type';
import FormInformationBasic from './components/FormInformationBasic'; import FormInformationBasic from './components/FormInformationBasic';
import FormPriceOrStock from './components/FormPriceOrStock'; import FormPriceOrStock from './components/FormPriceOrStock';
import FormRuleSetting from './components/FormRuleSetting'; import FormRuleSetting from './components/FormRuleSetting';
import FormRuleVPictures from './components/FormRuleVPictures';
import FormSettlementOthers from './components/FormSettlementOthers'; import FormSettlementOthers from './components/FormSettlementOthers';
import commonStyle from './common.less';
import { import {
getProductDetail, getProductDetail,
merchantCategoryGetAll, merchantCategoryGetAll,
...@@ -23,13 +21,13 @@ import { ServiceContext } from './context'; ...@@ -23,13 +21,13 @@ import { ServiceContext } from './context';
* @returns ReactDOM * @returns ReactDOM
*/ */
const ServiceGoods = options => { const ServiceGoods = options => {
const pageId = +options.match.params.id; // pageId: 0-新增,1-修改,2-查看
const basicRef = useRef(null); const basicRef = useRef(null);
const stockRef = useRef(null); const stockRef = useRef(null);
const settingRef = useRef(null); const settingRef = useRef(null);
const picturesRef = useRef(null);
const settleOtrRef = useRef(null); const settleOtrRef = useRef(null);
const [pageId, setPageId] = useState(null);
const [isEdit, setIsEdit] = useState(false); // 是否是编辑状态 const [isEdit, setIsEdit] = useState(false); // 是否是编辑状态
const [productType, setProductType] = useState(1); // 商品状态 const [productType, setProductType] = useState(1); // 商品状态
const [pageLoading, setPageLoading] = useState(false); // 页面加载状态 const [pageLoading, setPageLoading] = useState(false); // 页面加载状态
...@@ -37,25 +35,44 @@ const ServiceGoods = options => { ...@@ -37,25 +35,44 @@ const ServiceGoods = options => {
const [brandList, setBrandList] = useState([]); // 获取商品牌 const [brandList, setBrandList] = useState([]); // 获取商品牌
const [specList, setSpecList] = useState([]); // 规格列表 const [specList, setSpecList] = useState([]); // 规格列表
const [editData, setEditData] = useState({}); // 编辑保存数据 const [editData, setEditData] = useState({}); // 编辑保存数据
const baseCheckList = [basicRef, stockRef, picturesRef];
const [checkFormList, setCheckFormList] = useState(baseCheckList);
const [specKeyList, setSpecKeyList] = useState([]); // 记录一级规格key字段
const changeCheckList = proType => {
const newBaseCheckList = proType === 3 ? [
...baseCheckList,
settingRef,
settleOtrRef,
] : baseCheckList;
setCheckFormList(newBaseCheckList);
}
useEffect(() => {
const timer = setTimeout(() => {
checkFormList.forEach(({ current }) => {
current.reset()
});
clearTimeout(timer);
});
}, [checkFormList])
const productChange = (task: Task): void => { const productChange = task => {
setProductType(task.type); setProductType(task.type);
changeCheckList(task.type);
}; };
const submitEvent = async () => { const submitEvent = async () => {
const resuslt = await Promise.all([ const checkPromiseList = checkFormList.map(({ current }) => current.onCheck());
basicRef.current.onCheck(), const resuslt = await Promise.all(checkPromiseList);
stockRef.current.onCheck(),
settingRef.current.onCheck(),
settleOtrRef.current.onCheck(),
]);
console.log(resuslt); console.log(resuslt);
}; };
// 编辑回显详情数据 // 编辑回显详情数据
const getProductDetailResponse = async () => { const getProductDetailResponse = async id => {
try { try {
const res = await getProductDetail(pageId); const res = await getProductDetail(id);
if (res && res.data) { if (res && res.data) {
setProductType(res.data.type); setProductType(res.data.type);
setEditData(res.data); setEditData(res.data);
...@@ -83,23 +100,41 @@ const ServiceGoods = options => { ...@@ -83,23 +100,41 @@ const ServiceGoods = options => {
useEffect(() => { useEffect(() => {
(async () => { (async () => {
if (!options.visible) {
return;
}
setPageId(options.id);
setPageLoading(true); setPageLoading(true);
// await getMerchantCategory(); await getMerchantCategory();
// await getMerchantBrandList(); await getMerchantBrandList();
await getMerchantSpecList(); await getMerchantSpecList();
if (pageId !== 0) { if (options.id) {
setIsEdit(true); setIsEdit(true);
await getProductDetailResponse(); await getProductDetailResponse(options.id);
changeCheckList(productType);
} }
setPageLoading(false); setPageLoading(false);
})(); })();
}, [pageId]); }, [options.visible, options.id]);
const handleOk = () => {
}
const handleCancel = () => {
options.onChange(false);
}
const onSpecCommonImgEvent = useCallback(keys => {
setSpecKeyList(keys);
}, [specKeyList])
return ( return (
<Spin tip="正在加载..." spinning={pageLoading} delay={100}> <Modal visible={options.visible} onOk={handleOk} onCancel={handleCancel} width={1366}>
<PageHeaderWrapper className={commonStyle.header}> <Spin tip="正在加载..." spinning={pageLoading} delay={100}>
<WrapperContainer> <WrapperContainer>
<ServiceContext.Provider value={{ pageId, isEdit, productType }}> <ServiceContext.Provider value={{ pageId, isEdit, productType, isCard: productType === 3 }}>
<Title title="商品类型" /> <Title title="商品类型" />
<TaskTypeSelect productType={productType} onChange={productChange} /> <TaskTypeSelect productType={productType} onChange={productChange} />
...@@ -112,19 +147,20 @@ const ServiceGoods = options => { ...@@ -112,19 +147,20 @@ const ServiceGoods = options => {
/> />
<Title title="价格与库存" /> <Title title="价格与库存" />
<FormPriceOrStock ref={stockRef} specList={specList} editData={editData} /> <FormPriceOrStock ref={stockRef} specList={specList} onSpecChange={onSpecCommonImgEvent} editData={editData} />
<Title title="规则设置" /> <Title title="规则设置" />
<FormRuleSetting ref={settingRef} editData={editData} /> {productType === 3 && <FormRuleSetting ref={settingRef} editData={editData} />}
<FormSettlementOthers ref={settleOtrRef} editData={editData} /> <FormRuleVPictures ref={picturesRef} specKeyItem={specKeyList} editData={editData} />
{productType === 3 && <FormSettlementOthers ref={settleOtrRef} editData={editData} />}
<Button type="primary" onClick={submitEvent}> <Button type="primary" onClick={submitEvent}>
Register Register
</Button> </Button>
</ServiceContext.Provider> </ServiceContext.Provider>
</WrapperContainer> </WrapperContainer>
</PageHeaderWrapper> </Spin>
</Spin> </Modal>
); );
}; };
......
...@@ -4,6 +4,9 @@ import { stringify } from 'qs'; ...@@ -4,6 +4,9 @@ import { stringify } from 'qs';
import _ from 'lodash'; import _ from 'lodash';
const { goodsApi, kdspApi } = config; const { goodsApi, kdspApi } = config;
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
export const merchantUpload = async files => { export const merchantUpload = async files => {
const params = new FormData(); const params = new FormData();
...@@ -16,9 +19,10 @@ export const merchantUpload = async files => { ...@@ -16,9 +19,10 @@ export const merchantUpload = async files => {
}; };
export const getProductDetail = id => export const getProductDetail = id =>
request.post('/mock/389/product/detail', { request.post('/product/api/merchant/detail', {
prefix: 'http://yapi.quantgroups.com', prefix: goodsApi,
data: { id }, params: { id },
headers,
}); });
export const merchantCategoryGetAll = () => export const merchantCategoryGetAll = () =>
......
...@@ -57,7 +57,7 @@ const createSecondProduct = (secondSpecList, initItem, secondSpec, dataSource, c ...@@ -57,7 +57,7 @@ const createSecondProduct = (secondSpecList, initItem, secondSpec, dataSource, c
}; };
export const createProductData = ({ firstValues, secondValues, firstSpecId, secondSpecId }) => { export const createProductData = ({ firstValues, secondValues, firstSpecId, secondSpecId }) => {
console.log(firstValues, secondValues); console.log('=============>firstValues, secondValues', firstValues, secondValues);
const countRowSpan = {}; const countRowSpan = {};
const dataSource = []; const dataSource = [];
if (firstValues.length) { if (firstValues.length) {
...@@ -82,5 +82,6 @@ export const createProductData = ({ firstValues, secondValues, firstSpecId, seco ...@@ -82,5 +82,6 @@ export const createProductData = ({ firstValues, secondValues, firstSpecId, seco
const specFirst = createInitProduct(); const specFirst = createInitProduct();
dataSource.push(specFirst); dataSource.push(specFirst);
} }
console.log('dataSource===========>', dataSource);
return dataSource; 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