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