Commit d50542cd authored by 武广's avatar 武广

Merge branch 'feature/draft' into 'master'

Feature/draft

See merge request !73
parents d2761ac3 0d4ff3c5
import React, { useState, useEffect } from 'react';
import { Modal, Table, message } from 'antd';
import { columns } from './staticdata';
import { apiDraftList, apiDraftDetail, apiDeleteDraft } from '../service';
const DraftModal = props => {
const [pageInfo, setPageInfo] = useState({
current: 1,
pageSize: 4,
});
const [total, setTotal] = useState(0);
const [dataSource, setdataSource] = useState([]);
const onClose = () => props.onCancel();
const onEdit = async record => {
const res = await apiDraftDetail(record.id);
if (res && res.data) {
const data = JSON.parse(res.data.content);
data.id = record.id;
props.onToDetail(data);
onClose();
}
};
const getDraftList = async params => {
const res = await apiDraftList(params);
if (res && res.data && res.data.records) {
setdataSource(res.data.records);
setTotal(res.data.total);
}
};
const onRefresh = () => {
getDraftList({
pageSize: pageInfo.pageSize,
pageNo: pageInfo.current,
});
};
const onDel = record => {
Modal.confirm({
title: '确认提示',
content: '操作后不可更改,确认是否删除?',
onOk: async () => {
console.log('record :>> ', record);
await apiDeleteDraft(record.id);
message.success('删除成功!');
onRefresh();
},
});
};
const onChange = (current, pageSize) => {
const json = {
current,
pageSize,
};
setPageInfo(json);
json.pageNo = current;
getDraftList(json);
};
const pagination = {
...pageInfo,
total,
showTotal: t => `共 ${t} 项数据`,
onChange,
pageSizeOptions: [4, 20, 50, 100],
showSizeChanger: !0,
onShowSizeChange: onChange,
};
useEffect(() => {
if (props.visible) {
onRefresh();
}
}, [props.visible]);
const res = {
onDel,
onEdit,
};
return (
<Modal
visible={props.visible}
title="草稿箱"
onCancel={onClose}
maskClosable={false}
width="1000px"
footer={[]}
>
<Table
columns={columns(res)}
pagination={pagination}
rowKey={record => record.id}
dataSource={dataSource}
/>
</Modal>
);
};
export default DraftModal;
import React from 'react';
import { Button } from 'antd';
import styles from '../style.less';
const productType = {
1: '普通商品',
2: '虚拟商品',
3: '电子卡卷',
4: '服务商品',
};
export const columns = ({ onDel, onEdit }) => [
{
title: '草稿ID',
dataIndex: 'id',
width: 85,
align: 'center',
},
{
title: '商品名称',
dataIndex: 'productName',
align: 'center',
render(text) {
return <div className={styles.draftName}>{text}</div>;
},
},
{
title: '所属类目',
dataIndex: 'leimu',
width: 240,
align: 'center',
render(text, record) {
if (record.firstCategoryName) {
return `${record.firstCategoryName}>${record.secondCategoryName}>${record.thirdCategoryName}`;
}
return '-';
},
},
{
title: '商品类型',
dataIndex: 'productType',
width: 100,
align: 'center',
render(text) {
return productType[text];
},
},
{
title: '创建时间',
dataIndex: 'createdAt',
width: 120,
align: 'center',
},
{
title: '操作',
dataIndex: 'action',
width: 130,
align: 'center',
render: (text, record) => (
<>
<Button key="edit" type="link" size="small" onClick={() => onEdit(record)}>
修改
</Button>
<Button key="viewP" type="link" size="small" onClick={() => onDel(record)}>
删除
</Button>
</>
),
},
];
...@@ -25,6 +25,7 @@ import SearchForm from './SearchForm'; ...@@ -25,6 +25,7 @@ import SearchForm from './SearchForm';
import TempleatModal from './TempleatModal'; import TempleatModal from './TempleatModal';
import ServiceGoods from '../ServiceGoods'; import ServiceGoods from '../ServiceGoods';
import InfoAudit from './infoAudit'; import InfoAudit from './infoAudit';
import DraftModal from './DraftModal';
import { GOOD_MANAGE } from '@/../config/permission.config'; import { GOOD_MANAGE } from '@/../config/permission.config';
...@@ -56,6 +57,8 @@ class goodsManage extends Component { ...@@ -56,6 +57,8 @@ class goodsManage extends Component {
serviceData: {}, serviceData: {},
visibleAuditModal: false, visibleAuditModal: false,
auditRow: {}, // 查看审核信息使用 auditRow: {}, // 查看审核信息使用
isVisibleDraft: false, // 显示隐藏草稿箱
isEditDraft: false, // 是否编辑草稿
}; };
currentLog = null; currentLog = null;
...@@ -306,6 +309,7 @@ class goodsManage extends Component { ...@@ -306,6 +309,7 @@ class goodsManage extends Component {
serviceData: SourceData, serviceData: SourceData,
serviceVisble: true, serviceVisble: true,
createloading: false, createloading: false,
isEditDraft: false,
}); });
} else { } else {
this.setState({ this.setState({
...@@ -317,9 +321,20 @@ class goodsManage extends Component { ...@@ -317,9 +321,20 @@ class goodsManage extends Component {
} }
}; };
// 编辑草稿
editDraft = data => {
this.setState({
serviceData: data,
serviceVisble: true,
isEditDraft: true,
});
};
// 显示新增商品弹窗
serviceVisbleClose = (flag, refresh) => { serviceVisbleClose = (flag, refresh) => {
this.setState({ this.setState({
serviceVisble: flag, serviceVisble: flag,
isEditDraft: false,
serviceData: {}, serviceData: {},
}); });
if (refresh) { if (refresh) {
...@@ -327,6 +342,14 @@ class goodsManage extends Component { ...@@ -327,6 +342,14 @@ class goodsManage extends Component {
} }
}; };
// 打开草稿箱
openDraftModal = e => {
console.log('e :>> ', e);
this.setState({
isVisibleDraft: !!e,
});
};
onEdit = () => { onEdit = () => {
this.setState({ visibleAuditModal: false, auditRow: {} }); this.setState({ visibleAuditModal: false, auditRow: {} });
this.serviceVisbleChange(this.state.auditRow); this.serviceVisbleChange(this.state.auditRow);
...@@ -348,17 +371,26 @@ class goodsManage extends Component { ...@@ -348,17 +371,26 @@ class goodsManage extends Component {
this.canEditable = permissions[GOOD_MANAGE.EDITABLE]; this.canEditable = permissions[GOOD_MANAGE.EDITABLE];
return ( return (
<PageHeaderWrapper> <PageHeaderWrapper>
{canAddNormal || canAddService ? ( {canAddNormal || canAddService
? [
<Button <Button
type="primary" type="primary"
key="btnNew"
className={styles.button} className={styles.button}
onClick={() => this.serviceVisbleClose(true)} onClick={() => this.serviceVisbleClose(true)}
> >
新增商品 新增商品
</Button> </Button>,
) : ( <Button
'' type="link"
)} key="btnDraft"
className={styles.button}
onClick={this.openDraftModal}
>
草稿箱
</Button>,
]
: ''}
<Spin spinning={this.state.createloading}> <Spin spinning={this.state.createloading}>
<Card> <Card>
<SearchForm <SearchForm
...@@ -456,6 +488,7 @@ class goodsManage extends Component { ...@@ -456,6 +488,7 @@ class goodsManage extends Component {
virtualCategoryList={this.state.virtualTreeData} virtualCategoryList={this.state.virtualTreeData}
specListData={this.state.specListData} specListData={this.state.specListData}
permissions={permissions} permissions={permissions}
isDraft={this.state.isEditDraft}
/> />
)} )}
</Spin> </Spin>
...@@ -470,6 +503,13 @@ class goodsManage extends Component { ...@@ -470,6 +503,13 @@ class goodsManage extends Component {
onEdit={this.onEdit} onEdit={this.onEdit}
/> />
)} )}
{this.state.isVisibleDraft && (
<DraftModal
visible={this.state.isVisibleDraft}
onCancel={this.openDraftModal}
onToDetail={this.editDraft}
/>
)}
</PageHeaderWrapper> </PageHeaderWrapper>
); );
} }
......
...@@ -269,3 +269,23 @@ export const apiQueryLastAuditRecord = skuId => ...@@ -269,3 +269,23 @@ export const apiQueryLastAuditRecord = skuId =>
request.get(`/api/kdsp/sku/last/audit/record?skuId=${skuId}`, { request.get(`/api/kdsp/sku/last/audit/record?skuId=${skuId}`, {
prefix: goodsApi, prefix: goodsApi,
}); });
// 商品草稿详情
export const apiDraftDetail = draftId =>
request.get(`/api/merchants/drafts/detail?id=${draftId}`, {
prefix: goodsApi,
});
// 删除商品草稿
export const apiDeleteDraft = draftId =>
request.get(`/api/merchants/drafts/delete?id=${draftId}`, {
prefix: goodsApi,
});
// 商品草稿列表
export async function apiDraftList(data) {
return request.post('/api/merchants/drafts/list', {
prefix: goodsApi,
data,
});
}
...@@ -126,3 +126,7 @@ ...@@ -126,3 +126,7 @@
.attrboxMore { .attrboxMore {
max-height: max-content; max-height: max-content;
} }
.draftName {
text-align: left;
word-break: break-all;
}
...@@ -179,3 +179,10 @@ ...@@ -179,3 +179,10 @@
.btnMore { .btnMore {
text-align: center; text-align: center;
} }
.draftBox {
margin-bottom: 5px;
}
.conEdit {
color: #0e75fd;
cursor: pointer;
}
import React from 'react'; import React, { memo } from 'react';
import { Select, Form, InputNumber, Input, Button, Popover } from 'antd'; import { Select, Form, InputNumber, Input, Button, Popover } from 'antd';
import commonStyle from '../common.less'; import commonStyle from '../common.less';
...@@ -15,11 +15,11 @@ export const WrapperContainer = props => ( ...@@ -15,11 +15,11 @@ export const WrapperContainer = props => (
* @param props * @param props
*/ */
export const Title = props => ( export const Title = memo(props => (
<div className={commonStyle.title}> <div className={commonStyle.title}>
<h3>{props.title}</h3> <h3>{props.title}</h3>
</div> </div>
); ));
export const SelectTemplate = props => { export const SelectTemplate = props => {
const { const {
...@@ -87,7 +87,13 @@ export const CreateFormInput = props => { ...@@ -87,7 +87,13 @@ export const CreateFormInput = props => {
{...options} {...options}
style={{ width: '100%' }} style={{ width: '100%' }}
placeholder={`请输入${title}`} placeholder={`请输入${title}`}
onBlur={e => onBlurEvent(e.target.value, dataIndex, rowIndex)} onBlur={e => {
const inputTarget = e.target;
const timer = setTimeout(() => {
clearTimeout(timer);
onBlurEvent(inputTarget.value, dataIndex, rowIndex);
}, 10);
}}
/> />
); );
} }
...@@ -140,6 +146,7 @@ export const CreateFormInput = props => { ...@@ -140,6 +146,7 @@ export const CreateFormInput = props => {
const inputTarget = e.target; const inputTarget = e.target;
const timer = setTimeout(() => { const timer = setTimeout(() => {
clearTimeout(timer); clearTimeout(timer);
console.log('inputTarget.value :>> ', inputTarget.value);
onBlurEvent(inputTarget.value, dataIndex, rowIndex); onBlurEvent(inputTarget.value, dataIndex, rowIndex);
}, 10); }, 10);
}} }}
......
import { Input, Modal, Button, Form, Table, InputNumber } from 'antd'; import { Input, Modal, Button, Form, Table } from 'antd';
import React, { import React, {
useContext, useContext,
createContext, createContext,
...@@ -9,7 +9,7 @@ import React, { ...@@ -9,7 +9,7 @@ import React, {
} from 'react'; } from 'react';
import { ServiceContext } from '../context'; import { ServiceContext } from '../context';
import { CreateFormInput } from './CommonTemplate'; import { CreateFormInput } from './CommonTemplate';
import UUID from '../../../utils/uuid'; import { debounce } from '@/utils/utils';
const UpdateSkuName = ({ skuVisble, value, confirmEvent, cancelEvent }) => { const UpdateSkuName = ({ skuVisble, value, confirmEvent, cancelEvent }) => {
const [skuForm] = Form.useForm(); const [skuForm] = Form.useForm();
...@@ -62,39 +62,33 @@ const EditFormTable = forwardRef((props, ref) => { ...@@ -62,39 +62,33 @@ const EditFormTable = forwardRef((props, ref) => {
setDataSource([...initData]); setDataSource([...initData]);
}, [initData]); }, [initData]);
// const handleSave = row => { const getValues = () =>
// form.setFieldsValue({ [...dataSource].map(item => {
// tableList: [...row], const { rowSpanCount, option, ...childItem } = item;
// }); return childItem;
// const dataList = [...dataSource]; });
// dataList[rowIndex][dataIndex] = value;
// setDataSource([...dataList]);
// };
const handleSave = (value, dataIndex, rowIndex) => {
// form.setFieldsValue({
// [`tableList[${rowIndex}][${dataIndex}]`]: value,
// });
const dataList = [...dataSource];
dataList[rowIndex][dataIndex] = value;
setDataSource([...dataList]);
};
const onCheck = async () => { const onCheck = async () => {
try { try {
await form.validateFields(); await form.validateFields();
const newTableList = [...dataSource].map(item => { return getValues();
const { rowSpanCount, option, ...childItem } = item;
return childItem;
});
console.log('===============>newTableList', newTableList);
return newTableList;
} catch (errorInfo) { } catch (errorInfo) {
console.log(errorInfo); console.log(errorInfo);
return null; return null;
} }
}; };
const getFormValues = debounce(() => {
props.onValuesChange();
}, 400);
const handleSave = (value, dataIndex, rowIndex) => {
const dataList = [...dataSource];
dataList[rowIndex][dataIndex] = value;
setDataSource([...dataList]);
getFormValues();
};
const rowOnClickEvent = row => { const rowOnClickEvent = row => {
setSkuVisble(true); setSkuVisble(true);
setSkuNameItem({ setSkuNameItem({
...@@ -131,6 +125,7 @@ const EditFormTable = forwardRef((props, ref) => { ...@@ -131,6 +125,7 @@ const EditFormTable = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
form, form,
getValues,
})); }));
// 根据这里做判断渲染表格 // 根据这里做判断渲染表格
const columns = defaultColumns const columns = defaultColumns
...@@ -182,7 +177,7 @@ const EditFormTable = forwardRef((props, ref) => { ...@@ -182,7 +177,7 @@ const EditFormTable = forwardRef((props, ref) => {
return ( return (
<> <>
<Form form={form} scrollToFirstError component={false}> <Form form={form} scrollToFirstError component={false} onValuesChange={getFormValues}>
<EditableContext.Provider value={form}> <EditableContext.Provider value={form}>
<Table <Table
scroll={{ y: 320, x: 1000 }} scroll={{ y: 320, x: 1000 }}
...@@ -190,6 +185,7 @@ const EditFormTable = forwardRef((props, ref) => { ...@@ -190,6 +185,7 @@ const EditFormTable = forwardRef((props, ref) => {
pagination={false} pagination={false}
size="small" size="small"
bordered bordered
rowKey={(record, i) => i}
dataSource={dataSource} dataSource={dataSource}
columns={columns} columns={columns}
/> />
......
...@@ -6,6 +6,7 @@ import { UpOutlined, DownOutlined } from '@ant-design/icons'; ...@@ -6,6 +6,7 @@ import { UpOutlined, DownOutlined } from '@ant-design/icons';
import styles from '../common.less'; import styles from '../common.less';
import { apiGetAttribute } from '../service'; import { apiGetAttribute } from '../service';
import CustomSelect from '@/components/CustomSelect'; import CustomSelect from '@/components/CustomSelect';
import { debounce } from '@/utils/utils';
const FormAttr = forwardRef((props, ref) => { const FormAttr = forwardRef((props, ref) => {
const [form] = Form.useForm(); const [form] = Form.useForm();
...@@ -37,7 +38,10 @@ const FormAttr = forwardRef((props, ref) => { ...@@ -37,7 +38,10 @@ const FormAttr = forwardRef((props, ref) => {
skuAttr.forEach(item => { skuAttr.forEach(item => {
if (item[key].length) { if (item[key].length) {
let values = +item.optionType.code === 1 ? '' : []; let values = [];
if ((item.optionType && +item.optionType.code === 1) || typeof item[key] === 'string') {
values = '';
}
obj[item.productAttributeId] = []; obj[item.productAttributeId] = [];
item[key].forEach(attr => { item[key].forEach(attr => {
const { attributeValueId, attributeValueName } = attr; const { attributeValueId, attributeValueName } = attr;
...@@ -52,7 +56,11 @@ const FormAttr = forwardRef((props, ref) => { ...@@ -52,7 +56,11 @@ const FormAttr = forwardRef((props, ref) => {
obj[item.productAttributeId].push(json); obj[item.productAttributeId].push(json);
} }
// eslint-disable-next-line no-unused-expressions // eslint-disable-next-line no-unused-expressions
+item.optionType.code === 1 ? (values = v) : values.push(v); if ((item.optionType && +item.optionType.code === 1) || typeof item[key] === 'string') {
values = v;
} else {
values.push(v);
}
} }
}); });
obj.initValue[item.productAttributeId] = values; obj.initValue[item.productAttributeId] = values;
...@@ -63,6 +71,8 @@ const FormAttr = forwardRef((props, ref) => { ...@@ -63,6 +71,8 @@ const FormAttr = forwardRef((props, ref) => {
// 获取属性 // 获取属性
const getAttribute = async categoryId => { const getAttribute = async categoryId => {
console.log('categoryId :>> ', categoryId);
console.log('props.initData :>> ', props.initData);
const res = await apiGetAttribute(categoryId); const res = await apiGetAttribute(categoryId);
if (res && res.data && res.data.length) { if (res && res.data && res.data.length) {
let initValue = { let initValue = {
...@@ -128,6 +138,26 @@ const FormAttr = forwardRef((props, ref) => { ...@@ -128,6 +138,26 @@ const FormAttr = forwardRef((props, ref) => {
} }
}; };
const getFormValues = debounce(() => {
const values = form.getFieldsValue();
const arr = Object.keys(values).map(item => {
const obj = {
productAttributeId: item,
};
if (typeof values[item] === 'string') {
obj.productAttributeApplyValueList = JSON.parse(values[item]);
} else {
obj.productAttributeApplyValueList = values[item].map(v => JSON.parse(v));
}
return obj;
});
props.onValuesChange({
productAttributeApplyList: {
productAttributeApplyList: arr,
},
});
}, 400);
const onCheck = async () => { const onCheck = async () => {
try { try {
const values = await form.validateFields(); const values = await form.validateFields();
...@@ -181,7 +211,7 @@ const FormAttr = forwardRef((props, ref) => { ...@@ -181,7 +211,7 @@ const FormAttr = forwardRef((props, ref) => {
<> <>
<div className={styles.attrbox + (isMore ? styles.attrboxMore : '')}> <div className={styles.attrbox + (isMore ? styles.attrboxMore : '')}>
{categoryAttrs.length > 0 && ( {categoryAttrs.length > 0 && (
<Form form={form} initialValues={initAttrData}> <Form form={form} initialValues={initAttrData} onValuesChange={getFormValues}>
<Row> <Row>
{categoryAttrs.map(k => ( {categoryAttrs.map(k => (
<Col span={12} key={k.id}> <Col span={12} key={k.id}>
......
...@@ -2,6 +2,7 @@ import React, { useState, useContext, useEffect, forwardRef, useImperativeHandle ...@@ -2,6 +2,7 @@ import React, { useState, useContext, useEffect, forwardRef, useImperativeHandle
import { Cascader, Form, Input, Select, Popover, Button, Checkbox } from 'antd'; import { Cascader, Form, Input, Select, Popover, Button, Checkbox } from 'antd';
import { formItemLayout } from '../config'; import { formItemLayout } from '../config';
import { ServiceContext } from '../context'; import { ServiceContext } from '../context';
import { debounce } from '@/utils/utils';
const CreateSelectOption = optionList => const CreateSelectOption = optionList =>
optionList.map(brandItem => ( optionList.map(brandItem => (
...@@ -53,6 +54,11 @@ const FormInformationBasic = forwardRef((props, ref) => { ...@@ -53,6 +54,11 @@ const FormInformationBasic = forwardRef((props, ref) => {
} }
}; };
const getFormValues = debounce(() => {
const values = form.getFieldsValue();
props.onValuesChange({ infoMation: values });
}, 400);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
reset: form.resetFields, reset: form.resetFields,
...@@ -64,10 +70,8 @@ const FormInformationBasic = forwardRef((props, ref) => { ...@@ -64,10 +70,8 @@ const FormInformationBasic = forwardRef((props, ref) => {
}, [brandList]); }, [brandList]);
useEffect(() => { useEffect(() => {
if (customer.isEdit) {
if (!editData) return; if (!editData) return;
form.setFieldsValue(editData); form.setFieldsValue(editData);
}
}, [customer.isEdit, editData]); }, [customer.isEdit, editData]);
return ( return (
...@@ -82,6 +86,7 @@ const FormInformationBasic = forwardRef((props, ref) => { ...@@ -82,6 +86,7 @@ const FormInformationBasic = forwardRef((props, ref) => {
description: '', description: '',
}} }}
scrollToFirstError scrollToFirstError
onValuesChange={getFormValues}
> >
<Form.Item <Form.Item
name="categoryId" name="categoryId"
......
...@@ -4,6 +4,9 @@ import { PlusOutlined } from '@ant-design/icons'; ...@@ -4,6 +4,9 @@ import { PlusOutlined } from '@ant-design/icons';
import styles from '../common.less'; import styles from '../common.less';
import { isIntegerNotZero, isCheckPriceOneDecimal } from '@/utils/validator'; import { isIntegerNotZero, isCheckPriceOneDecimal } from '@/utils/validator';
import UUID from '@/utils/uuid'; import UUID from '@/utils/uuid';
import { debounce } from '@/utils/utils';
import localStorage from '@/utils/localStorage';
import { localAutoSaveKey } from '../utils';
const { Option } = Select; const { Option } = Select;
...@@ -158,11 +161,9 @@ const FormPackage = forwardRef((props, ref) => { ...@@ -158,11 +161,9 @@ const FormPackage = forwardRef((props, ref) => {
const { validateFields, getFieldsValue } = form; const { validateFields, getFieldsValue } = form;
const onCheck = async () => { const onCheck = async () => {
console.log('form :>> ', form);
try { try {
const values = await validateFields(); const values = await validateFields();
const arr = []; const arr = [];
console.log('package values :>> ', values);
if (values && values.lists) { if (values && values.lists) {
values.lists.forEach(item => { values.lists.forEach(item => {
arr.push({ arr.push({
...@@ -176,6 +177,13 @@ const FormPackage = forwardRef((props, ref) => { ...@@ -176,6 +177,13 @@ const FormPackage = forwardRef((props, ref) => {
} }
}; };
const getValues = () => form.getFieldsValue();
const getFormValues = debounce(() => {
// const values = form.getFieldsValue();{ setMealContent: values }
props.onValuesChange();
}, 400);
// 创建分组 // 创建分组
const onCreateGroup = () => { const onCreateGroup = () => {
const str = groupName && groupName.trim(); const str = groupName && groupName.trim();
...@@ -230,6 +238,7 @@ const FormPackage = forwardRef((props, ref) => { ...@@ -230,6 +238,7 @@ const FormPackage = forwardRef((props, ref) => {
} }
setList(arr); setList(arr);
form.setFieldsValue(arrList); form.setFieldsValue(arrList);
getFormValues();
}; };
useEffect(() => { useEffect(() => {
...@@ -266,11 +275,12 @@ const FormPackage = forwardRef((props, ref) => { ...@@ -266,11 +275,12 @@ const FormPackage = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
getValues,
})); }));
return ( return (
<div className={styles.formPackageBox}> <div className={styles.formPackageBox}>
<Form style={{ marginBottom: 10 }} form={form}> <Form style={{ marginBottom: 10 }} form={form} onValuesChange={getFormValues}>
<Form.List name="lists"> <Form.List name="lists">
{(fields, { add, remove }) => ( {(fields, { add, remove }) => (
<> <>
......
...@@ -7,7 +7,11 @@ import React, { ...@@ -7,7 +7,11 @@ import React, {
useRef, useRef,
useEffect, useEffect,
useContext, useContext,
useMemo,
useCallback,
memo,
} from 'react'; } from 'react';
// import { unstable_batchedUpdates } from 'react-dom';
import { formItemLayout, StaticColumns } from '../config'; import { formItemLayout, StaticColumns } from '../config';
import EditFormTable from './EditFormTable'; import EditFormTable from './EditFormTable';
import FormPackage from './FormPackage'; import FormPackage from './FormPackage';
...@@ -19,6 +23,7 @@ import { ...@@ -19,6 +23,7 @@ import {
fliterSkuListSortData, fliterSkuListSortData,
filterSkuNotIdList, filterSkuNotIdList,
} from '../utils'; } from '../utils';
import { debounce } from '@/utils/utils';
import { ServiceContext } from '../context'; import { ServiceContext } from '../context';
import { SelectTemplate, Title } from './CommonTemplate'; import { SelectTemplate, Title } from './CommonTemplate';
...@@ -172,7 +177,7 @@ const SpecificationTemplate = (props, _) => { ...@@ -172,7 +177,7 @@ const SpecificationTemplate = (props, _) => {
); );
}; };
const CreateBatchFormItems = ({ specInitValue, batchChange, editRef, defaultColumns }) => { const CreateBatchFormItems = ({ specInitValue, batchChange, defaultColumns }) => {
const customer = useContext(ServiceContext); const customer = useContext(ServiceContext);
const formItems = defaultColumns const formItems = defaultColumns
.filter(item => item.batchRole && item?.batchRole.includes(customer.productType)) .filter(item => item.batchRole && item?.batchRole.includes(customer.productType))
...@@ -195,7 +200,7 @@ const CreateBatchFormItems = ({ specInitValue, batchChange, editRef, defaultColu ...@@ -195,7 +200,7 @@ const CreateBatchFormItems = ({ specInitValue, batchChange, editRef, defaultColu
noSty noSty
formName="bacthFirst" formName="bacthFirst"
placeholder={specInitValue.firstSpec} placeholder={specInitValue.firstSpec}
dataList={specInitValue.firstSpecValue} dataList={specInitValue.firstSpecValue || []}
fieldNames={{ label: 'firstSpecValue', value: 'firstSpecValue' }} fieldNames={{ label: 'firstSpecValue', value: 'firstSpecValue' }}
/> />
<SelectTemplate <SelectTemplate
...@@ -203,7 +208,7 @@ const CreateBatchFormItems = ({ specInitValue, batchChange, editRef, defaultColu ...@@ -203,7 +208,7 @@ const CreateBatchFormItems = ({ specInitValue, batchChange, editRef, defaultColu
width={150} width={150}
formName="bacthSecon" formName="bacthSecon"
placeholder={specInitValue.secondSpec} placeholder={specInitValue.secondSpec}
dataList={specInitValue.secondSpecValue} dataList={specInitValue.secondSpecValue || []}
fieldNames={{ label: 'secondSpecValue', value: 'secondSpecValue' }} fieldNames={{ label: 'secondSpecValue', value: 'secondSpecValue' }}
/> />
{formItems.concat( {formItems.concat(
...@@ -296,7 +301,7 @@ const FormPriceOrStock = forwardRef((props, ref) => { ...@@ -296,7 +301,7 @@ const FormPriceOrStock = forwardRef((props, ref) => {
const CreateColumnsEvent = specData => { const CreateColumnsEvent = specData => {
const columsData = []; const columsData = [];
if (specData.firstSpec && specData.firstSpecValue.length) { if (specData.firstSpec && specData.firstSpecValue && specData.firstSpecValue.length) {
columsData.push({ columsData.push({
title: specData.firstSpec, title: specData.firstSpec,
dataIndex: 'firstSpecValue', dataIndex: 'firstSpecValue',
...@@ -304,7 +309,7 @@ const FormPriceOrStock = forwardRef((props, ref) => { ...@@ -304,7 +309,7 @@ const FormPriceOrStock = forwardRef((props, ref) => {
}); });
} }
if (specData.secondSpec && specData.secondSpecValue.length) { if (specData.secondSpec && specData.secondSpecValue && specData.secondSpecValue.length) {
columsData.push({ columsData.push({
title: specData.secondSpec, title: specData.secondSpec,
dataIndex: 'secondSpecValue', dataIndex: 'secondSpecValue',
...@@ -363,14 +368,13 @@ const FormPriceOrStock = forwardRef((props, ref) => { ...@@ -363,14 +368,13 @@ const FormPriceOrStock = forwardRef((props, ref) => {
const values = form.getFieldsValue(); const values = form.getFieldsValue();
const { batchItem, bacthFirst, bacthSecon } = values; const { batchItem, bacthFirst, bacthSecon } = values;
const resetObject = batchTableSourceData({ batchItem, tableData, bacthSecon, bacthFirst }); const resetObject = batchTableSourceData({ batchItem, tableData, bacthSecon, bacthFirst });
props.onValuesChange({ skuList: resetObject });
setTableData(resetObject); setTableData(resetObject);
}; };
const onSpecificationEvent = async () => { const onSpecificationEvent = async () => {
try { try {
const values = await form.validateFields(); const values = await form.validateFields();
console.log('values :>> ', values);
console.log('cleanArray(values.secondSpecValue) :>> ', cleanArray(values.secondSpecValue));
const cleanValues = { const cleanValues = {
firstSpec: values.firstSpec, firstSpec: values.firstSpec,
firstSpecId: values.firstSpecId, firstSpecId: values.firstSpecId,
...@@ -388,6 +392,24 @@ const FormPriceOrStock = forwardRef((props, ref) => { ...@@ -388,6 +392,24 @@ const FormPriceOrStock = forwardRef((props, ref) => {
return null; return null;
}; };
const getFormValues = debounce(async () => {
const cleanValues = await onSpecificationEvent();
props.onValuesChange({ infoSpecData: cleanValues });
}, 400);
const packageValueChange = () => {
const efvalues = editRef.current.getValues();
if (customer.isCard) {
const packageV = packageRef.current.getValues();
efvalues.forEach((item, i) => {
item.serviceItem = {
setMealContent: packageV.lists[i].children,
};
});
}
props.onValuesChange({ skuList: efvalues });
};
const firstOnChangeEvent = async () => { const firstOnChangeEvent = async () => {
const cleanValues = await onSpecificationEvent(); const cleanValues = await onSpecificationEvent();
if (cleanValues) { if (cleanValues) {
...@@ -406,6 +428,7 @@ const FormPriceOrStock = forwardRef((props, ref) => { ...@@ -406,6 +428,7 @@ const FormPriceOrStock = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
onFinish,
reset: () => { reset: () => {
form.resetFields(); form.resetFields();
setDefaultColumns([]); setDefaultColumns([]);
...@@ -416,20 +439,28 @@ const FormPriceOrStock = forwardRef((props, ref) => { ...@@ -416,20 +439,28 @@ const FormPriceOrStock = forwardRef((props, ref) => {
})); }));
useEffect(() => { useEffect(() => {
if (customer.isEdit) { if (customer.isEdit || customer.isUseCache) {
if (!editData) return; if (!editData) {
onFinish();
return;
}
form.setFieldsValue(editData); // 设置规格数据 form.setFieldsValue(editData); // 设置规格数据
firstOnChangeEvent(); // 触发成底部动态表格数据 firstOnChangeEvent(); // 触发成底部动态表格数据
setSpecInitValue(editData); // 缓存规格数据 setSpecInitValue(editData); // 缓存规格数据
CreateColumnsEvent(editData); CreateColumnsEvent(editData);
setMergeTable(Boolean(editData.secondSpecValue.length)); setMergeTable(Boolean(editData.secondSpecValue && editData.secondSpecValue.length));
setTableData(fliterSkuListSortData(skuList)); setTableData(fliterSkuListSortData(skuList) || []);
} }
}, [customer.isEdit, editData]); }, [customer.isEdit, customer.isUseCache, editData]);
return ( return (
<> <>
<Form form={form} autoComplete="off" initialValues={initSpecReced()}> <Form
form={form}
autoComplete="off"
initialValues={initSpecReced()}
onValuesChange={getFormValues}
>
<SpecificationTemplate <SpecificationTemplate
form={form} form={form}
label="一级规格" label="一级规格"
...@@ -469,11 +500,17 @@ const FormPriceOrStock = forwardRef((props, ref) => { ...@@ -469,11 +500,17 @@ const FormPriceOrStock = forwardRef((props, ref) => {
setTableData={setTableData} setTableData={setTableData}
defaultColumns={defaultColumns} defaultColumns={defaultColumns}
initData={tableData} initData={tableData}
onValuesChange={packageValueChange}
/> />
{customer.isCard && ( {customer.isCard && (
<> <>
<Title title="套餐内容" key="tctitle" /> <Title title="套餐内容" key="tctitle" />
<FormPackage ref={packageRef} initData={tableData} key="tc" /> <FormPackage
ref={packageRef}
initData={tableData}
key="tc"
onValuesChange={packageValueChange}
/>
</> </>
)} )}
</> </>
......
...@@ -3,7 +3,7 @@ import React, { useEffect, forwardRef, useImperativeHandle, useContext } from 'r ...@@ -3,7 +3,7 @@ import React, { useEffect, forwardRef, useImperativeHandle, useContext } from 'r
import moment from 'moment'; import moment from 'moment';
import { WeeksList, formItemLayout } from '../config'; import { WeeksList, formItemLayout } from '../config';
import { ServiceContext } from '../context'; import { ServiceContext } from '../context';
import { formatTime } from '../../../utils/utils'; import { debounce, formatTime } from '@/utils/utils';
const { Option } = Select; const { Option } = Select;
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
...@@ -34,7 +34,7 @@ const FormRuleSetting = forwardRef((props, ref) => { ...@@ -34,7 +34,7 @@ const FormRuleSetting = forwardRef((props, ref) => {
}; };
useEffect(() => { useEffect(() => {
if (customer.isEdit) { if (customer.isEdit || customer.isUseCache) {
if (!editData) return; if (!editData) return;
const goodInfo = Object.assign({}, editData); const goodInfo = Object.assign({}, editData);
if (goodInfo.shopIds) { if (goodInfo.shopIds) {
...@@ -43,7 +43,7 @@ const FormRuleSetting = forwardRef((props, ref) => { ...@@ -43,7 +43,7 @@ const FormRuleSetting = forwardRef((props, ref) => {
} }
form.setFieldsValue(goodInfo); form.setFieldsValue(goodInfo);
} }
}, [customer.isEdit, editData]); }, [customer.isEdit, customer.isUseCache, editData]);
const onCheck = async () => { const onCheck = async () => {
try { try {
...@@ -62,6 +62,11 @@ const FormRuleSetting = forwardRef((props, ref) => { ...@@ -62,6 +62,11 @@ const FormRuleSetting = forwardRef((props, ref) => {
} }
}; };
const getFormValues = debounce(() => {
const values = form.getFieldsValue();
props.onValuesChange({ serviceItem: values });
}, 400);
const nowDateTime = moment(moment().format('YYYY-MM-DD 00:00:00')); const nowDateTime = moment(moment().format('YYYY-MM-DD 00:00:00'));
const nowDateTimeEnd = moment(moment().format('YYYY-MM-DD 23:59:59')); const nowDateTimeEnd = moment(moment().format('YYYY-MM-DD 23:59:59'));
...@@ -89,6 +94,7 @@ const FormRuleSetting = forwardRef((props, ref) => { ...@@ -89,6 +94,7 @@ const FormRuleSetting = forwardRef((props, ref) => {
tips: '', // 温馨提示 tips: '', // 温馨提示
}} }}
scrollToFirstError scrollToFirstError
onValuesChange={getFormValues}
> >
<Form.Item name="purchaseTime" label="购买时间" {...rangeConfig}> <Form.Item name="purchaseTime" label="购买时间" {...rangeConfig}>
<RangePicker <RangePicker
......
...@@ -6,6 +6,7 @@ import { ServiceContext } from '../context'; ...@@ -6,6 +6,7 @@ import { ServiceContext } from '../context';
import { TaskList, formItemLayout } from '../config'; import { TaskList, formItemLayout } from '../config';
import UploadImage from './UploadImage'; import UploadImage from './UploadImage';
import commonStyle from '../common.less'; import commonStyle from '../common.less';
import { debounce } from '@/utils/utils';
const FormRuleVPictures = forwardRef((props, ref) => { const FormRuleVPictures = forwardRef((props, ref) => {
const { editData, specKeyItem } = props; const { editData, specKeyItem } = props;
...@@ -21,12 +22,12 @@ const FormRuleVPictures = forwardRef((props, ref) => { ...@@ -21,12 +22,12 @@ const FormRuleVPictures = forwardRef((props, ref) => {
const [{ imgConfig }] = typeConfig.filter(item => item.type === customer.productType); const [{ imgConfig }] = typeConfig.filter(item => item.type === customer.productType);
useEffect(() => { useEffect(() => {
if (customer.isEdit) { if (customer.isEdit || customer.isUseCache) {
if (editData) { if (editData) {
setImageList(editData.imageList); setImageList(editData.imageList || {});
setCardImageList(editData.cardImageList); setCardImageList(editData.cardImageList || []);
setCommonImageList(editData.commonImageList); // 编辑状态下设置公共图 setCommonImageList(editData.commonImageList || []); // 编辑状态下设置公共图
setDetailImageList(editData.detailImageList); // 编辑状态下设置详情图 setDetailImageList(editData.detailImageList || []); // 编辑状态下设置详情图
const editParams = { const editParams = {
commonImageList: editData.commonImageList, commonImageList: editData.commonImageList,
detailImageList: editData.detailImageList, detailImageList: editData.detailImageList,
...@@ -42,7 +43,7 @@ const FormRuleVPictures = forwardRef((props, ref) => { ...@@ -42,7 +43,7 @@ const FormRuleVPictures = forwardRef((props, ref) => {
}); });
} }
} }
}, [customer.isEdit, editData]); }, [customer.isEdit, customer.isUseCache, editData]);
useEffect(() => { useEffect(() => {
if (customer.isCard) return; if (customer.isCard) return;
...@@ -67,6 +68,12 @@ const FormRuleVPictures = forwardRef((props, ref) => { ...@@ -67,6 +68,12 @@ const FormRuleVPictures = forwardRef((props, ref) => {
} }
}; };
const getFormValues = debounce(() => {
const values = form.getFieldsValue();
props.onValuesChange({ infoImageData: values });
// props.onValuesChange(values);
}, 400);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
setFieldsValue: obj => { setFieldsValue: obj => {
...@@ -139,6 +146,7 @@ const FormRuleVPictures = forwardRef((props, ref) => { ...@@ -139,6 +146,7 @@ const FormRuleVPictures = forwardRef((props, ref) => {
imageList: {}, imageList: {},
detailImageList: [], detailImageList: [],
}} }}
onValuesChange={getFormValues}
> >
<Form.Item <Form.Item
name="commonImageList" name="commonImageList"
......
...@@ -3,6 +3,7 @@ import { Form, Input, Select, Checkbox, Radio, Space, InputNumber } from 'antd'; ...@@ -3,6 +3,7 @@ import { Form, Input, Select, Checkbox, Radio, Space, InputNumber } from 'antd';
import { Title } from './CommonTemplate'; import { Title } from './CommonTemplate';
import { formItemLayout } from '../config'; import { formItemLayout } from '../config';
import { ServiceContext } from '../context'; import { ServiceContext } from '../context';
import { debounce } from '@/utils/utils';
const createInitValues = () => ({ const createInitValues = () => ({
settlementMethod: 1, settlementMethod: 1,
...@@ -35,13 +36,18 @@ const FormSettlementOthers = forwardRef((props, ref) => { ...@@ -35,13 +36,18 @@ const FormSettlementOthers = forwardRef((props, ref) => {
} }
}; };
const getFormValues = debounce(() => {
const values = form.getFieldsValue();
props.onValuesChange({ settlementItem: values });
}, 400);
useEffect(() => { useEffect(() => {
if (customer.isEdit) { if (customer.isEdit || customer.isUseCache) {
if (!editData) return; if (!editData) return;
form.setFieldsValue(editData); form.setFieldsValue(editData);
setInitValue({ ...editData }); setInitValue({ ...editData });
} }
}, [customer.isEdit, editData]); }, [customer.isEdit, customer.isUseCache, editData]);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
onCheck, onCheck,
...@@ -120,6 +126,7 @@ const FormSettlementOthers = forwardRef((props, ref) => { ...@@ -120,6 +126,7 @@ const FormSettlementOthers = forwardRef((props, ref) => {
name="register" name="register"
initialValues={initValue} initialValues={initValue}
scrollToFirstError scrollToFirstError
onValuesChange={getFormValues}
> >
<Form.Item <Form.Item
name="appointment" name="appointment"
......
import React, { useState, useRef, useEffect, useCallback } from 'react'; import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { Spin, Button, Modal, message, notification } from 'antd'; import { Spin, Button, Modal, message, notification } from 'antd';
import moment from 'moment';
import { Title, WrapperContainer } from './components/CommonTemplate'; import { Title, WrapperContainer } from './components/CommonTemplate';
import { TaskTypeSelect } from './components/TaskTypeSelect'; import { TaskTypeSelect } from './components/TaskTypeSelect';
import FormInformationBasic from './components/FormInformationBasic'; import FormInformationBasic from './components/FormInformationBasic';
...@@ -8,6 +9,7 @@ import FormRuleSetting from './components/FormRuleSetting'; ...@@ -8,6 +9,7 @@ import FormRuleSetting from './components/FormRuleSetting';
import FormRuleVPictures from './components/FormRuleVPictures'; import FormRuleVPictures from './components/FormRuleVPictures';
import FormSettlementOthers from './components/FormSettlementOthers'; import FormSettlementOthers from './components/FormSettlementOthers';
import FormAttr from './components/FormAttr'; import FormAttr from './components/FormAttr';
import localStorage from '@/utils/localStorage';
import { import {
merchantBrandList, merchantBrandList,
merchantSpecList, merchantSpecList,
...@@ -17,10 +19,13 @@ import { ...@@ -17,10 +19,13 @@ import {
merchantProductAdd, merchantProductAdd,
merchantProductEdit, merchantProductEdit,
getByProductType, getByProductType,
apiCreateDraft,
apiEditDraft,
} from './service'; } from './service';
import { isUrl, filterSendData, clearCurrent } from './utils'; import { isUrl, filterSendData, clearCurrent, onAutoSaveValue, localAutoSaveKey } from './utils';
import { ServiceContext } from './context'; import { ServiceContext } from './context';
import { GOOD_MANAGE } from '@/../config/permission.config'; import { GOOD_MANAGE } from '@/../config/permission.config';
import styles from './common.less';
/** /**
* 服务商品改造-商品模块 * 服务商品改造-商品模块
...@@ -42,6 +47,7 @@ const ServiceGoods = options => { ...@@ -42,6 +47,7 @@ const ServiceGoods = options => {
const [pageId, setPageId] = useState(null); const [pageId, setPageId] = useState(null);
const [categoryIds, setCategoryIds] = useState([]); // 商品品类ID const [categoryIds, setCategoryIds] = useState([]); // 商品品类ID
const [isEdit, setIsEdit] = useState(false); // 是否是编辑状态 const [isEdit, setIsEdit] = useState(false); // 是否是编辑状态
const [isUseCache, setIsUseCache] = useState(false); // 是否使用缓存
const [productType, setProductType] = useState(canAddNormal ? 1 : 4); // 商品状态 const [productType, setProductType] = useState(canAddNormal ? 1 : 4); // 商品状态
const [pageLoading, setPageLoading] = useState(false); // 页面加载状态 const [pageLoading, setPageLoading] = useState(false); // 页面加载状态
const [afterAddressList, setAfterAddressList] = useState([]); // 售后地址 const [afterAddressList, setAfterAddressList] = useState([]); // 售后地址
...@@ -51,6 +57,7 @@ const ServiceGoods = options => { ...@@ -51,6 +57,7 @@ const ServiceGoods = options => {
const [specList, setSpecList] = useState([]); // 规格列表 const [specList, setSpecList] = useState([]); // 规格列表
const [editData, setEditData] = useState({}); // 编辑保存数据 const [editData, setEditData] = useState({}); // 编辑保存数据
const [newCategoryList, setNewCategoryList] = useState({}); const [newCategoryList, setNewCategoryList] = useState({});
const [visibleCacheEdit, setVisibleCacheEdit] = useState(false); // 显示有缓存未保存提示
const [checkFormList] = useState([ const [checkFormList] = useState([
basicRef, basicRef,
attrRef, attrRef,
...@@ -64,25 +71,66 @@ const ServiceGoods = options => { ...@@ -64,25 +71,66 @@ const ServiceGoods = options => {
const resetForm = () => clearCurrent(checkFormList).forEach(({ current }) => current.reset()); const resetForm = () => clearCurrent(checkFormList).forEach(({ current }) => current.reset());
const onValuesChange = e => {
if (!isEdit) {
if (visibleCacheEdit) {
setVisibleCacheEdit(false);
localStorage.remove(localAutoSaveKey);
onAutoSaveValue(
{
type: productType,
},
!0,
);
}
onAutoSaveValue(e);
}
};
const productChange = task => { const productChange = task => {
setProductType(task.type); setProductType(task.type);
setPageLoading(true);
setCategoryIds([]); setCategoryIds([]);
setVisibleCacheEdit(false);
const timer = setTimeout(() => { const timer = setTimeout(() => {
setPageLoading(false);
resetForm(); resetForm();
clearTimeout(timer); clearTimeout(timer);
onAutoSaveValue(
{
type: task.type,
},
!0,
);
stockRef.current.onFinish();
}, 1000); }, 1000);
}; };
const handleCancel = refresh => { const onResetData = refresh => {
setPageId(null); setPageId(null);
setIsEdit(false); setIsEdit(false);
setProductType(4); // 默认写死服务类商品 setProductType(canAddNormal ? 1 : 4);
setEditData({}); setEditData({});
setSpecKeyList([]); setSpecKeyList([]);
resetForm(); resetForm();
options.onChange(false, refresh); options.onChange(false, refresh);
}; };
const handleCancel = refresh => {
const info = localStorage.get(localAutoSaveKey);
if (info && Object.keys(info).length > 1) {
Modal.confirm({
title: '确认提示',
content: '商品信息还未保存,确认关闭弹窗?',
onOk() {
onResetData(refresh);
},
});
} else {
onResetData(refresh);
}
};
// 获取商品牌数据 // 获取商品牌数据
const getMerchantBrandList = async () => { const getMerchantBrandList = async () => {
if (!brandList.length) { if (!brandList.length) {
...@@ -112,6 +160,7 @@ const ServiceGoods = options => { ...@@ -112,6 +160,7 @@ const ServiceGoods = options => {
const addResponse = await sendAsyncHttpRequest(sendData); const addResponse = await sendAsyncHttpRequest(sendData);
if (addResponse.data) { if (addResponse.data) {
message.success(`${isEdit ? '修改' : '添加'}成功!`); message.success(`${isEdit ? '修改' : '添加'}成功!`);
localStorage.remove(localAutoSaveKey);
handleCancel(true); handleCancel(true);
} }
setPageLoading(false); setPageLoading(false);
...@@ -131,6 +180,7 @@ const ServiceGoods = options => { ...@@ -131,6 +180,7 @@ const ServiceGoods = options => {
const shopGetByProductType = async type => { const shopGetByProductType = async type => {
if (!newCategoryList[type]?.length) { if (!newCategoryList[type]?.length) {
const result = await getByProductType(type); const result = await getByProductType(type);
console.log('result :>> ', result);
setNewCategoryList({ setNewCategoryList({
...newCategoryList, ...newCategoryList,
[type]: result.data || [], [type]: result.data || [],
...@@ -138,6 +188,7 @@ const ServiceGoods = options => { ...@@ -138,6 +188,7 @@ const ServiceGoods = options => {
} }
}; };
// 保存商品
const submitEvent = async () => { const submitEvent = async () => {
const checkPromiseList = clearCurrent(checkFormList).map(({ current }) => current.onCheck()); const checkPromiseList = clearCurrent(checkFormList).map(({ current }) => current.onCheck());
const resuslt = await Promise.all(checkPromiseList); const resuslt = await Promise.all(checkPromiseList);
...@@ -152,6 +203,9 @@ const ServiceGoods = options => { ...@@ -152,6 +203,9 @@ const ServiceGoods = options => {
if (isEdit) { if (isEdit) {
sendData.id = pageId; sendData.id = pageId;
} }
if (options.isDraft) {
sendData.productDraftId = SourceData.id;
}
console.log('sendData :>> ', sendData); console.log('sendData :>> ', sendData);
sendMerchantProductHttpRequest(sendData); sendMerchantProductHttpRequest(sendData);
} }
...@@ -173,6 +227,36 @@ const ServiceGoods = options => { ...@@ -173,6 +227,36 @@ const ServiceGoods = options => {
} }
}; };
const onSetData = info => {
if (info.serviceItem) {
const ptime = info.serviceItem.purchaseTime;
const utime = info.serviceItem.useTime;
if (ptime && ptime.length === 2) {
ptime[0] = moment(ptime[0]);
ptime[1] = moment(ptime[1]);
}
if (utime && utime.length === 2) {
utime[0] = moment(utime[0]);
utime[1] = moment(utime[1]);
}
}
setProductType(info.type);
setEditData(info);
if (info.infoMation && info.infoMation.categoryId && info.infoMation.categoryId.length) {
setCategoryIds(info.infoMation.categoryId);
}
};
// 继续编辑(使用缓存数据)
const onContinueEdit = () => {
setVisibleCacheEdit(false);
setIsUseCache(true);
const info = localStorage.get(localAutoSaveKey);
if (info) {
onSetData(info);
}
};
useEffect(() => { useEffect(() => {
(async () => { (async () => {
if (!options.visible) { if (!options.visible) {
...@@ -184,12 +268,24 @@ const ServiceGoods = options => { ...@@ -184,12 +268,24 @@ const ServiceGoods = options => {
await getAfterSalesAddrsPage(); await getAfterSalesAddrsPage();
await getMerchantSpecList(); await getMerchantSpecList();
if (Object.keys(SourceData).length) { if (Object.keys(SourceData).length) {
console.log('SourceData :>> ', SourceData);
// 从编辑草稿进入 执行以下代码
if (options.isDraft) {
setIsUseCache(true);
setVisibleCacheEdit(false);
onSetData(SourceData);
onValuesChange(SourceData, !0);
} else {
setEditData(SourceData); setEditData(SourceData);
setPageId(SourceData.id); setPageId(SourceData.id);
setProductType(SourceData.productType); setProductType(SourceData.productType);
setCategoryIds(SourceData.infoMation.categoryId || []); setCategoryIds(SourceData.infoMation.categoryId || []);
setIsEdit(true); setIsEdit(true);
} }
} else {
// 默认生成一条规格数据
stockRef.current.onFinish();
}
setPageLoading(false); setPageLoading(false);
})(); })();
}, [SourceData]); }, [SourceData]);
...@@ -200,6 +296,17 @@ const ServiceGoods = options => { ...@@ -200,6 +296,17 @@ const ServiceGoods = options => {
} }
}, [productType, options.visible]); }, [productType, options.visible]);
useEffect(() => {
if (options.visible && !isEdit) {
const info = localStorage.get(localAutoSaveKey);
if (info) {
setVisibleCacheEdit(true);
return;
}
}
setVisibleCacheEdit(false);
}, [isEdit, options.visible]);
useEffect(() => { useEffect(() => {
setProductType(canAddNormal ? 1 : 4); setProductType(canAddNormal ? 1 : 4);
}, [canAddNormal]); }, [canAddNormal]);
...@@ -230,10 +337,65 @@ const ServiceGoods = options => { ...@@ -230,10 +337,65 @@ const ServiceGoods = options => {
}); });
} }
}; };
// 切换类目
const onCategoryChange = e => { const onCategoryChange = e => {
setCategoryIds(e); setCategoryIds(e);
}; };
// 保存草稿
const onSaveDraft = async () => {
console.log('newCategoryList :>> ', newCategoryList);
const info = localStorage.get(localAutoSaveKey);
if (
!info ||
!info.infoMation ||
!info.infoMation.name ||
!info.infoMation.categoryId ||
info.infoMation.categoryId.length !== 3
) {
message.warning('请添加商品类目和名称');
return;
}
Modal.confirm({
title: '确认提示',
content: '确定将商品信息保存至草稿箱?',
onOk: async () => {
info.type = productType;
let arr = newCategoryList[info.type];
const first = arr.find(item => item.id === info.infoMation.categoryId[0]);
arr = first.children;
const second = arr.find(item => item.id === info.infoMation.categoryId[1]);
arr = second.children;
const third = arr.find(item => item.id === info.infoMation.categoryId[2]);
const params = {
productName: info.infoMation.name,
productType: info.type,
firstCategoryId: info.infoMation.categoryId[0],
firstCategoryName: first.name,
secondCategoryId: info.infoMation.categoryId[1],
secondCategoryName: second.name,
thirdCategoryId: info.infoMation.categoryId[2],
thirdCategoryName: third.name,
content: JSON.stringify(info),
};
console.log('params :>> ', params);
setPageLoading(true);
let api = apiCreateDraft;
if (options.isDraft) {
params.id = SourceData.id;
api = apiEditDraft;
}
await api(params);
localStorage.remove(localAutoSaveKey);
setPageLoading(false);
message.success('草稿保存成功!');
handleCancel(true);
},
});
};
const providerValue = { const providerValue = {
pageId, pageId,
isEdit, isEdit,
...@@ -246,6 +408,7 @@ const ServiceGoods = options => { ...@@ -246,6 +408,7 @@ const ServiceGoods = options => {
// 当商品进行编辑 & 类型不为电子卡券 & 商品状态不为驳回 禁用当前功能 // 当商品进行编辑 & 类型不为电子卡券 & 商品状态不为驳回 禁用当前功能
isDisabled: isEdit && productType !== 4 && SourceData.state && SourceData.state !== 4, isDisabled: isEdit && productType !== 4 && SourceData.state && SourceData.state !== 4,
isJDGoods: isEdit && SourceData.pageProductType && +SourceData.pageProductType !== 1, isJDGoods: isEdit && SourceData.pageProductType && +SourceData.pageProductType !== 1,
isUseCache, // 是否使用缓存数据
onEventBus, onEventBus,
}; };
...@@ -259,6 +422,9 @@ const ServiceGoods = options => { ...@@ -259,6 +422,9 @@ const ServiceGoods = options => {
maskClosable={false} maskClosable={false}
keyboard={false} keyboard={false}
footer={[ footer={[
<Button key="draft" type="primary" ghost loading={pageLoading} onClick={onSaveDraft}>
保存草稿
</Button>,
<Button key="submit" type="primary" loading={pageLoading} onClick={submitEvent}> <Button key="submit" type="primary" loading={pageLoading} onClick={submitEvent}>
提交 提交
</Button>, </Button>,
...@@ -269,6 +435,14 @@ const ServiceGoods = options => { ...@@ -269,6 +435,14 @@ const ServiceGoods = options => {
> >
<Spin tip="正在加载..." spinning={pageLoading} delay={100}> <Spin tip="正在加载..." spinning={pageLoading} delay={100}>
<WrapperContainer> <WrapperContainer>
{visibleCacheEdit && (
<div className={styles.draftBox}>
有未保存内容。是否
<span className={styles.conEdit} onClick={onContinueEdit}>
继续编辑
</span>
</div>
)}
<ServiceContext.Provider value={providerValue}> <ServiceContext.Provider value={providerValue}>
<Title title="商品类型" /> <Title title="商品类型" />
<TaskTypeSelect productType={productType} onChange={productChange} /> <TaskTypeSelect productType={productType} onChange={productChange} />
...@@ -284,11 +458,18 @@ const ServiceGoods = options => { ...@@ -284,11 +458,18 @@ const ServiceGoods = options => {
afterAddressList={afterAddressList} afterAddressList={afterAddressList}
specListData={specListData} specListData={specListData}
onCategoryChange={onCategoryChange} onCategoryChange={onCategoryChange}
onValuesChange={onValuesChange}
/> />
{[1, 2].includes(productType) && [ {[1, 2].includes(productType) && [
<Title title="商品属性" key="attrtitle" />, <Title title="商品属性" key="attrtitle" />,
<FormAttr key="attr" ref={attrRef} categoryIds={categoryIds} initData={editData} />, <FormAttr
key="attr"
ref={attrRef}
categoryIds={categoryIds}
initData={editData}
onValuesChange={onValuesChange}
/>,
]} ]}
<Title title="价格与库存" /> <Title title="价格与库存" />
...@@ -298,14 +479,15 @@ const ServiceGoods = options => { ...@@ -298,14 +479,15 @@ const ServiceGoods = options => {
onSpecChange={onSpecCommonImgEvent} onSpecChange={onSpecCommonImgEvent}
editData={editData.infoSpecData} editData={editData.infoSpecData}
skuList={editData.skuList} skuList={editData.skuList}
onValuesChange={onValuesChange}
/> />
<Title title="规则设置" /> <Title title="规则设置" />
{productType === 4 && ( {productType === 4 && (
<FormRuleSetting <FormRuleSetting
ref={settingRef} ref={settingRef}
editData={editData.serviceItem} editData={editData.serviceItem}
supplierIdList={supplierIdList} supplierIdList={supplierIdList}
onValuesChange={onValuesChange}
/> />
)} )}
...@@ -313,9 +495,14 @@ const ServiceGoods = options => { ...@@ -313,9 +495,14 @@ const ServiceGoods = options => {
ref={picturesRef} ref={picturesRef}
specKeyItem={specKeyList} specKeyItem={specKeyList}
editData={editData.infoImageData} editData={editData.infoImageData}
onValuesChange={onValuesChange}
/> />
{productType === 4 && ( {productType === 4 && (
<FormSettlementOthers ref={settleOtrRef} editData={editData.settlementItem} /> <FormSettlementOthers
ref={settleOtrRef}
editData={editData.settlementItem}
onValuesChange={onValuesChange}
/>
)} )}
</ServiceContext.Provider> </ServiceContext.Provider>
</WrapperContainer> </WrapperContainer>
......
...@@ -103,3 +103,17 @@ export const apiGetAttribute = categoryId => ...@@ -103,3 +103,17 @@ export const apiGetAttribute = categoryId =>
request.get(`/api/kdsp/category/template/ref/attribute/detail?categoryId=${categoryId}`, { request.get(`/api/kdsp/category/template/ref/attribute/detail?categoryId=${categoryId}`, {
prefix: goodsApi, prefix: goodsApi,
}); });
// 新建草稿
export const apiCreateDraft = data =>
request.post('/api/merchants/drafts/add', {
prefix: goodsApi,
data,
});
// 编辑草稿
export const apiEditDraft = data =>
request.post('/api/merchants/drafts/edit', {
prefix: goodsApi,
data,
});
import { message } from 'antd';
import { sortBy } from 'lodash'; import { sortBy } from 'lodash';
import UUID from '../../utils/uuid'; import UUID from '../../utils/uuid';
import localStorage from '@/utils/localStorage';
import { debounce, getObjectType, isClass } from '@/utils/utils';
export const clearCurrent = currentList => currentList.filter(item => item.current); export const clearCurrent = currentList => currentList.filter(item => item.current);
...@@ -106,7 +109,6 @@ const filterItems = (type, props) => { ...@@ -106,7 +109,6 @@ const filterItems = (type, props) => {
}; };
export const filterSendData = (type, params) => { export const filterSendData = (type, params) => {
console.log('===============>生成数据', params);
const { infoMation, infoImageData, attributeApplyList } = params; const { infoMation, infoImageData, attributeApplyList } = params;
const items = filterItems(type, params); const items = filterItems(type, params);
const commonImageList = type === 4 ? [] : infoImageData.commonImageList; const commonImageList = type === 4 ? [] : infoImageData.commonImageList;
...@@ -248,7 +250,28 @@ export const createProductData = (props, isEdit, skuList) => { ...@@ -248,7 +250,28 @@ export const createProductData = (props, isEdit, skuList) => {
const newSecondList = secndInIdList.concat(secndNoIdList || []); const newSecondList = secndInIdList.concat(secndNoIdList || []);
list = createSkuListData(newFirstList, newSecondList, firstSpecId, secondSpecId, skuList); list = createSkuListData(newFirstList, newSecondList, firstSpecId, secondSpecId, skuList);
} else { } else {
list = createSkuListData(fisrtNoIdList, secndNoIdList, firstSpecId, secondSpecId); list = createSkuListData(fisrtNoIdList, secndNoIdList, firstSpecId, secondSpecId, skuList);
} }
return list; return list;
}; };
export const localAutoSaveKey = 'good-info-auto-save';
export const onAutoSaveValue = (e, isClear) => {
const keys = Object.keys(e);
if (
e &&
isClass(e) === 'Object' &&
keys.length === 1 &&
isClass(e[keys[0]]) === 'Object' &&
Object.keys(e[keys[0]]) < 1
) {
return;
}
if (isClear) {
localStorage.set(localAutoSaveKey, Object.assign({}, e));
} else {
const info = localStorage.get(localAutoSaveKey) || {};
localStorage.set(localAutoSaveKey, Object.assign({ type: 1 }, info, e));
}
};
...@@ -4,7 +4,7 @@ import { Form } from '@ant-design/compatible'; ...@@ -4,7 +4,7 @@ import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css'; import '@ant-design/compatible/assets/index.css';
import { Modal, Select, Input, Card, notification } from 'antd'; import { Modal, Select, Input, Card, notification } from 'antd';
import style from '../index.less'; import style from '../index.less';
import { updateExpress } from '../service'; import { apiDeliveriesAdd } from '../service';
const FormItem = Form.Item; const FormItem = Form.Item;
const { Option } = Select; const { Option } = Select;
...@@ -53,7 +53,7 @@ const LogisticsForm = props => { ...@@ -53,7 +53,7 @@ const LogisticsForm = props => {
notification.error({ message: '该订单下的所有商品必须设置物流信息!' }); notification.error({ message: '该订单下的所有商品必须设置物流信息!' });
return; return;
} }
await updateExpress(resultData); await apiDeliveriesAdd(resultData);
onSubmit(); onSubmit();
}; };
......
...@@ -40,13 +40,6 @@ export async function queryExpress() { ...@@ -40,13 +40,6 @@ export async function queryExpress() {
} }
} }
export async function updateExpress(params) {
return request.post('/api/merchants/orders/deliveries/add', {
prefix: config.kdspApi,
data: params,
});
}
export async function getGoods(orderId) { export async function getGoods(orderId) {
const { data } = await request.get(`/api/merchants/orders/skus/list?orderId=${orderId}`, { const { data } = await request.get(`/api/merchants/orders/skus/list?orderId=${orderId}`, {
prefix: config.kdspApi, prefix: config.kdspApi,
......
...@@ -42,14 +42,6 @@ export async function queryToSend(params) { ...@@ -42,14 +42,6 @@ export async function queryToSend(params) {
} }
} }
// 发货/更新物流
export async function updateExpress(params) {
return request.post('/api/merchants/orders/deliveries/add', {
prefix: config.kdspApi,
data: params,
});
}
// 快递公司 // 快递公司
export async function queryExpress() { export async function queryExpress() {
try { try {
......
...@@ -125,3 +125,5 @@ export const getClientInfo = () => { ...@@ -125,3 +125,5 @@ export const getClientInfo = () => {
height: document.body.clientHeight, height: document.body.clientHeight,
}; };
}; };
export const getObjectType = v => Object.prototype.toString.call(v).replace(/\[object |]/g, '');
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