Files
gao-customer-h5/src/pages/customer/CustomerEdit.vue
T
2026-09-19 13:08:44 +08:00

864 lines
23 KiB
Vue

<template>
<div v-can="savePermissionCode" class="customer-edit">
<t-form class="form" label-align="left" label-width="5rem" :disabled="isCustomerBound" v-entrance-transition>
<t-form-item label="客户编码">
<t-input
v-model.trim="formData.code"
placeholder="客户编码"
borderless
:disabled="false"
@blur="handleCodeBlur"
>
<template #suffix-icon>
<t-button
theme="primary"
size="extra-small"
:disabled="false"
@click="toggleScanner"
>
<span v-text="scannerVisible ? '关闭扫码' : '扫码'" />
</t-button>
</template>
</t-input>
</t-form-item>
<div v-if="scannerVisible" class="code-scanner-wrapper">
<code-scanner
visible
:status-text="scanStatus"
active-text="正在识别客户编码"
@decode="handleDecodedText"
@status-change="handleScanStatusChange"
/>
</div>
<div v-if="isCustomerBound" class="bound-customer">
<customer-profile-card :customer="boundCodeCustomer" />
<div class="tips red">
<t-icon name="error-circle" />
<span v-text="isCreateMode ? '该编码已绑定客户,不可新录入' : '该编码已绑定其他客户,请使用新的编码'" />
</div>
<t-button
block
theme="primary"
variant="outline"
:disabled="false"
@click="toBoundCustomerEdit"
>编辑该客户</t-button>
</div>
<t-form-item label="姓名" required-mark>
<t-input
v-model.trim="formData.name"
placeholder="姓名"
borderless
:disabled="isCustomerBound"
/>
</t-form-item>
<t-form-item label="出生日期">
<birthdate-picker
v-model="formData.birthdate"
v-model:calendar="formData.birthdateCalendar"
:disabled="isCustomerBound"
/>
</t-form-item>
<t-form-item label="年龄">
<t-input
v-model.trim="formData.age"
type="number"
:readonly="!!formData.birthdate"
:placeholder="formData.birthdate ? '根据出生日期自动计算' : '年龄'"
borderless
:disabled="isCustomerBound"
/>
</t-form-item>
<t-form-item label-width="0">
<div class="photo">
<media-selector
v-model="photoList"
v-model:photo-items="photoItemList"
:edit-mode="true"
:show-add="!isCustomerBound"
:show-remove="!isCustomerBound"
:show-viewer-actions="!isCustomerBound"
:add-actions="photoAddActions"
:loading="isPhotoUploading"
@add="openPhotoPicker('OTHER')"
@action="handlePhotoAction"
@capture-photo="capturePhoto"
@capture-video="captureVideo"
/>
<div class="tips orange" v-if="!hasCustomerDeletePermission">当前账户权限编辑客户需要上传照片和积分卡</div>
</div>
</t-form-item>
<t-form-item label="性别">
<t-radio-group class="sex" v-model="formData.gender" variant="default-filled" :disabled="isCustomerBound">
<t-radio :block="false" borderless value="MALE">男</t-radio>
<t-radio :block="false" borderless value="FEMALE">女</t-radio>
<t-radio :block="false" borderless value="">未知</t-radio>
</t-radio-group>
</t-form-item>
<t-form-item label="手机号">
<t-input v-model.trim="formData.telephone" type="tel" placeholder="手机号" borderless :disabled="isCustomerBound" />
</t-form-item>
<t-form-item label="介绍人">
<div class="selector">
<t-input
:value="formData.introducerCustomer?.name"
readonly
placeholder="选择介绍人"
borderless
:disabled="isCustomerBound"
/>
<div class="actions">
<t-button
v-if="introducerCustomerId"
variant="text"
theme="danger"
size="extra-small"
:disabled="isCustomerBound"
@click="clearIntroducer"
>清除</t-button>
<t-button
theme="primary"
variant="outline"
size="extra-small"
:disabled="isCustomerBound"
@click="selectorVisible = true"
>选择客户</t-button>
</div>
</div>
</t-form-item>
<t-form-item v-if="formData.introducerCustomer" label-width="0">
<customer-profile-card
class="introducer-profile"
:customer="formData.introducerCustomer"
/>
</t-form-item>
<t-form-item label="调理部位" :arrow="!isCustomerBound" @click="openBodyAreaPicker">
<div class="picker-text" v-text="selectedAreaText" />
</t-form-item>
</t-form>
<customer-tag-card
v-if="canReadTag"
class="tag-card"
:editable="canEditTag && !isCustomerBound"
:tag-list="customerTagList"
v-entrance-transition="70"
@edit="openTagSelector"
/>
<t-form class="form" label-align="left" label-width="3rem" :disabled="isCustomerBound" v-entrance-transition="140">
<t-form-item label="住址">
<t-textarea
class="textarea"
v-model.trim="formData.address"
:autosize="{ minRows: 3, maxRows: 5 }"
placeholder="住址"
:disabled="isCustomerBound"
/>
</t-form-item>
<t-form-item label="病症">
<t-textarea
class="textarea"
v-model.trim="formData.disease"
:autosize="{ minRows: 3, maxRows: 5 }"
placeholder="病症"
:disabled="isCustomerBound"
/>
</t-form-item>
<t-form-item label="备注">
<t-textarea
class="textarea"
v-model.trim="formData.remark"
:autosize="{ minRows: 3, maxRows: 5 }"
placeholder="客户备注"
:disabled="isCustomerBound"
/>
</t-form-item>
</t-form>
<input
ref="photoInputRef"
class="file-input"
type="file"
accept="*/*"
@change="handlePhotoSelected"
>
<input
ref="photoCameraInputRef"
class="file-input"
type="file"
accept="image/*"
capture="environment"
@change="handlePhotoSelected"
>
<input
ref="videoInputRef"
class="file-input"
type="file"
accept="video/*"
capture="environment"
@change="handlePhotoSelected"
>
<customer-selector
v-if="!isCustomerBound"
v-model="introducerCustomerId"
v-model:visible="selectorVisible"
@change="handleIntroducerChange"
/>
<tag-selector
v-if="canEditTag && !isCustomerBound"
v-model="selectedTagIdList"
v-model:visible="tagSelectorVisible"
@change="handleTagSelected"
/>
</div>
<bottom-popup
v-model="bodyAreaPickerVisible"
title="选择调理部位"
height="32rem"
@left-button-click="cancelBodyAreaPicker"
@right-button-click="confirmBodyAreaPicker"
>
<body-area-selector v-model="bodyAreaDraft" :readonly="isCustomerBound" />
</bottom-popup>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import { type Attachment, AttachmentAPI, useUserStore } from "timi-web-api";
import { Message } from "@/utils/message";
import CustomerAPI from "@/api/CustomerAPI";
import TagAPI from "@/api/TagAPI";
import BodyAreaSelector from "@/components/BodyAreaSelector.vue";
import CodeScanner from "@/components/CodeScanner.vue";
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
import CustomerSelector from "@/components/CustomerSelector.vue";
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
import type { MediaSelectorAddAction } from "@/components/mediaSelector/types";
import TagSelector from "@/components/TagSelector.vue";
import CustomerTagCard from "@/pages/customer/component/CustomerTagCard.vue";
import { useCurrentStoreStore } from "@/store/currentStoreStore";
import { useNavBarStore } from "@/store/navBarStore";
import { useSettingStore } from "@/store/settingStore";
import type { BodyAreaValue, Customer, CustomerAttachmentType, EditableCustomerPhoto } from "@/types/Customer";
import type { Tag } from "@/types/Tag";
import { bodyAreaLabelMap } from "@/utils/bodyArea";
import { getAttachmentReadURL } from "@/utils/attachment";
import { normalizeBodyAreaValue } from "@/utils/customer";
import { corePermissionCodes, gaoRoleCodes, permissionCodes } from "@/utils/permission";
import { compressUploadImage } from "@/utils/imageCompression";
defineOptions({
name: "CustomerEdit"
});
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const settingStore = useSettingStore();
const currentStoreStore = useCurrentStoreStore();
const navBarStore = useNavBarStore();
const isCreateMode = computed(() => route.name === "CustomerCreate");
const savePermissionCode = computed(() => isCreateMode.value ? permissionCodes.customer.create : permissionCodes.customer.update);
const hasCustomerDeletePermission = computed(() => userStore.hasPermissions(permissionCodes.customer.delete));
const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalManager));
let latestDecodedText = "";
// ---------- 扫码 ----------
const scannerVisible = ref(false);
const scanStatus = ref("点击扫码开始识别");
const introducerCustomerId = ref("");
const boundCodeCustomer = ref<Customer>();
const checkedCode = ref("");
let codeCheckToken = 0;
let pendingCodeCheck: Promise<void> | undefined;
let pendingCode = "";
const isCustomerBound = computed(() => {
const boundCustomerId = boundCodeCustomer.value?.id;
return !!boundCustomerId && boundCustomerId !== formData.id;
});
async function toggleScanner(): Promise<void> {
if (scannerVisible.value) {
scannerVisible.value = false;
return;
}
scannerVisible.value = true;
latestDecodedText = "";
}
async function handleDecodedText(rawText: string): Promise<void> {
const normalizedText = rawText.trim();
if (!normalizedText || normalizedText === latestDecodedText) {
return;
}
latestDecodedText = normalizedText;
await settingStore.playScanSuccessSound();
formData.code = normalizedText;
scannerVisible.value = false;
await checkBoundCustomerCode();
scanStatus.value = `已识别客户编码 ${normalizedText}`;
}
function handleScanStatusChange(value: string): void {
scanStatus.value = value;
}
async function handleCodeBlur(): Promise<void> {
await checkBoundCustomerCode();
}
async function checkBoundCustomerCode(): Promise<void> {
const normalizedCode = formData.code?.trim() || "";
if (!normalizedCode) {
codeCheckToken++;
checkedCode.value = "";
boundCodeCustomer.value = undefined;
pendingCodeCheck = undefined;
pendingCode = "";
return;
}
if (checkedCode.value === normalizedCode) {
return;
}
if (pendingCodeCheck && pendingCode === normalizedCode) {
await pendingCodeCheck;
return;
}
const requestToken = ++codeCheckToken;
boundCodeCustomer.value = undefined;
pendingCode = normalizedCode;
pendingCodeCheck = (async () => {
const matched = await CustomerAPI.findByCode(normalizedCode);
if (requestToken !== codeCheckToken || normalizedCode !== (formData.code?.trim() || "")) {
return;
}
checkedCode.value = normalizedCode;
boundCodeCustomer.value = matched?.id ? matched : undefined;
})();
try {
await pendingCodeCheck;
} finally {
if (pendingCode === normalizedCode) {
pendingCodeCheck = undefined;
pendingCode = "";
}
}
}
// ---------- 介绍人 ----------
const selectorVisible = ref(false);
async function handleIntroducerChange(id: string): Promise<void> {
const customer = id ? await CustomerAPI.findById(id) : undefined;
introducerCustomerId.value = customer?.id || "";
formData.introducerCustomerId = customer?.id || "";
formData.introducerCustomer = customer;
}
function clearIntroducer(): void {
if (isCustomerBound.value) {
return;
}
introducerCustomerId.value = "";
formData.introducerCustomerId = "";
formData.introducerCustomer = undefined;
}
// ---------- 表单 ----------
const formData = reactive<Customer>({
});
watch(() => formData.code, (value) => {
const normalizedCode = value?.trim() || "";
if (normalizedCode !== checkedCode.value && normalizedCode !== pendingCode) {
codeCheckToken++;
checkedCode.value = "";
boundCodeCustomer.value = undefined;
}
});
// ---------- 标签 ----------
const canReadTag = computed(() => userStore.hasPermissions(corePermissionCodes.tag.read));
const canApplyTag = computed(() => userStore.hasPermissions(corePermissionCodes.tag.apply));
const canEditTag = computed(() => canReadTag.value && canApplyTag.value);
const customerTagList = ref<Tag[]>([]);
const selectedTagIdList = ref<string[]>([]);
const tagSelectorVisible = ref(false);
async function loadCustomerTags(customerId: string): Promise<void> {
if (!customerId || !canReadTag.value) {
customerTagList.value = [];
selectedTagIdList.value = [];
return;
}
customerTagList.value = await TagAPI.listByBizType("GAO_CUSTOMER", customerId);
selectedTagIdList.value = customerTagList.value.map(item => item.id || "").filter(Boolean);
}
function openTagSelector(): void {
if (!canEditTag.value || isCustomerBound.value) {
return;
}
selectedTagIdList.value = customerTagList.value.map(item => item.id || "").filter(Boolean);
tagSelectorVisible.value = true;
}
function handleTagSelected(tagList: Tag[]): void {
customerTagList.value = tagList;
selectedTagIdList.value = tagList.map(item => item.id || "").filter(Boolean);
}
// ---------- 调理部位 ----------
const selectedAreas = ref<BodyAreaValue>({
selectedCodeList: []
});
const bodyAreaPickerVisible = ref(false);
const bodyAreaDraft = ref<BodyAreaValue>({
selectedCodeList: []
});
const selectedAreaText = computed(() => {
const selectedLabelList = selectedAreas.value.selectedCodeList.map(item => bodyAreaLabelMap.get(item) || item);
return selectedLabelList.length ? `${selectedLabelList.join("、")}` : "选择调理部位";
});
function openBodyAreaPicker(): void {
if (isCustomerBound.value) {
return;
}
bodyAreaDraft.value = {
selectedCodeList: [...selectedAreas.value.selectedCodeList]
};
bodyAreaPickerVisible.value = true;
}
function cancelBodyAreaPicker(): void {
bodyAreaPickerVisible.value = false;
}
function confirmBodyAreaPicker(): void {
if (isCustomerBound.value) {
bodyAreaPickerVisible.value = false;
return;
}
selectedAreas.value = {
selectedCodeList: [...bodyAreaDraft.value.selectedCodeList]
};
bodyAreaPickerVisible.value = false;
}
function openPhotoPicker(target: CustomerAttachmentType): void {
if (isCustomerBound.value) {
return;
}
photoPickerTarget.value = target;
photoInputRef.value?.click();
}
function capturePhoto(): void {
if (isCustomerBound.value) {
return;
}
photoPickerTarget.value = "PHOTO";
photoCameraInputRef.value?.click();
}
function capturePointCard(): void {
if (isCustomerBound.value) {
return;
}
photoPickerTarget.value = "POINT_CARD";
photoCameraInputRef.value?.click();
}
function captureVideo(): void {
if (isCustomerBound.value) {
return;
}
photoPickerTarget.value = "OTHER";
videoInputRef.value?.click();
}
function handlePhotoAction(action: MediaSelectorAddAction): void {
if (action.emit === "add-point-card") {
capturePointCard();
return;
}
if (action.emit === "add-other") {
openPhotoPicker("OTHER");
}
}
watch(isCustomerBound, (value) => {
navBarStore.setRightDisabled(value);
if (!value) {
return;
}
scannerVisible.value = false;
selectorVisible.value = false;
tagSelectorVisible.value = false;
bodyAreaPickerVisible.value = false;
});
const canSubmit = computed(() => formData.name?.trim() && currentStoreStore.currentStoreId);
async function prepareStoreScope(): Promise<void> {
if (isGlobalManager.value) {
await currentStoreStore.loadStoreList();
formData.storeId = currentStoreStore.currentStoreId;
return;
}
await currentStoreStore.loadLoginStore();
formData.storeId = currentStoreStore.currentStoreId;
}
async function loadDetail() {
await prepareStoreScope();
const id = String(route.params.id || "");
if (!id) {
customerTagList.value = [];
selectedTagIdList.value = [];
return;
}
try {
const customer = await CustomerAPI.detail(id);
Object.assign(formData, customer);
formData.storeId = currentStoreStore.currentStoreId;
await checkBoundCustomerCode();
await loadCustomerTags(id);
photoItemList.value = (customer.attachmentList || [])
.filter(item => !!item.id)
.map(item => ({
attachment: item,
attachType: normalizeAttachmentType(item.attachType),
mimeType: item.mimeType,
previewUrl: getAttachmentReadURL(item.id || ""),
url: getAttachmentReadURL(item.id || "", 90)
}));
selectedAreas.value = normalizeBodyAreaValue(customer.conditioningPart);
introducerCustomerId.value = customer.introducerCustomerId || customer.introducerCustomer?.id || "";
} catch (err) {
console.warn("客户详情加载失败", err);
Message.error("客户详情加载失败");
}
}
onMounted(loadDetail);
onMounted(() => {
navBarStore.clearRight();
if (userStore.hasPermissions(savePermissionCode.value)) {
navBarStore.setRightText("保存", "var(--td-brand-color)", doSubmit);
navBarStore.setRightDisabled(isCustomerBound.value);
}
});
watch(() => route.fullPath, loadDetail);
// ---------- 年龄 ----------
watch(() => formData.birthdate, (value) => {
if (value) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (match) {
const birthYear = Number(match[1]);
const birthMonth = Number(match[2]);
const birthDay = Number(match[3]);
const today = new Date();
let age = today.getFullYear() - birthYear;
if (today.getMonth() + 1 < birthMonth || (today.getMonth() + 1 === birthMonth && today.getDate() < birthDay)) {
age--;
}
formData.age = Math.max(age, 0);
} else {
formData.age = undefined;
}
}
});
// ---------- 照片 ----------
const photoInputRef = ref<HTMLInputElement>();
const photoCameraInputRef = ref<HTMLInputElement>();
const videoInputRef = ref<HTMLInputElement>();
const photoAddActions = [
{
icon: "cardmembership",
text: "拍积分卡",
emit: "add-point-card",
theme: "primary"
}
] as const;
const photoPickerTarget = ref<CustomerAttachmentType>("PHOTO");
const isPhotoUploading = ref(false);
const photoItemList = ref<EditableCustomerPhoto[]>([]);
const photoList = computed<string[]>({
get() {
return photoItemList.value.map(item => item.url);
},
set(value) {
const urlSet = new Set(value);
photoItemList.value = photoItemList.value.filter(item => urlSet.has(item.url));
}
});
function normalizeAttachmentType(attachType?: string): CustomerAttachmentType {
if (attachType === "POINT_CARD" || attachType === "OTHER") {
return attachType;
}
return "PHOTO";
}
function validateCustomerPhotoList(): boolean {
if (hasCustomerDeletePermission.value) {
return true;
}
const attachTypeSet = new Set(photoItemList.value.map(item => item.attachType));
if (!attachTypeSet.has("PHOTO")) {
Message.warning("请上传客户照片");
return false;
}
if (!attachTypeSet.has("POINT_CARD")) {
Message.warning("请上传积分卡照片");
return false;
}
return true;
}
async function handlePhotoSelected(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) {
return;
}
isPhotoUploading.value = true;
try {
const compressedFile = await compressUploadImage(file);
const [tempFile] = await AttachmentAPI.upload(compressedFile);
if (tempFile?.id) {
photoItemList.value.push({
attachType: photoPickerTarget.value,
mimeType: file.type,
tempFileId: tempFile.id,
url: AttachmentAPI.getTempReadURL(tempFile.id)
});
}
} finally {
isPhotoUploading.value = false;
input.value = "";
}
}
// ---------- 保存 ----------
const isSubmitting = ref(false);
async function doSubmit(): Promise<void> {
if (isSubmitting.value) {
return;
}
if (!await ensureCustomerCodeAvailable()) {
return;
}
if (!canSubmit.value) {
if (!formData.name?.trim()) {
Message.warning("请填写姓名");
return;
}
Message.warning("当前门店未设置");
return;
}
if (!validateCustomerPhotoList()) {
return;
}
isSubmitting.value = true;
try {
const payload: Customer = { ...formData };
payload.storeId = currentStoreStore.currentStoreId;
payload.conditioningPart = selectedAreas.value;
payload.introducerCustomerId = introducerCustomerId.value || "";
payload.attachmentList = buildAttachmentList();
delete payload.tagApply;
if (canEditTag.value) {
payload.tagApply = {
bizType: "GAO_CUSTOMER",
bizId: payload.id || "",
tagIdList: [...selectedTagIdList.value]
};
}
delete payload.introducerCustomer;
if (isCreateMode.value) {
await CustomerAPI.create(payload);
Message.success("创建成功");
const redirect = String(route.query.redirect || "");
await router.replace(redirect || "/management/customers");
return;
} else {
await CustomerAPI.update(payload);
Message.success("保存成功");
const redirect = String(route.query.redirect || "");
if (redirect) {
await router.replace(redirect);
return;
}
}
await router.replace("/management/customers");
} finally {
isSubmitting.value = false;
}
}
async function ensureCustomerCodeAvailable(): Promise<boolean> {
if (!formData.code?.trim()) {
return true;
}
await checkBoundCustomerCode();
if (!isCustomerBound.value) {
return true;
}
Message.warning(isCreateMode.value ? "该客户编码已绑定客户,不可新录入,请编辑已有客户" : "该客户编码已绑定其他客户,请使用新的编码");
return false;
}
async function toBoundCustomerEdit(): Promise<void> {
const customerId = boundCodeCustomer.value?.id;
if (!customerId) {
return;
}
await router.push(`/management/customers/${customerId}/edit`);
}
onUnmounted(() => {
navBarStore.clearRight();
});
function buildAttachmentList(): Attachment[] {
return photoItemList.value.flatMap(item => {
if (item.attachment) {
return [{
...item.attachment,
attachType: item.attachType || item.attachment.attachType || "PHOTO"
}];
}
if (item.tempFileId) {
return [{
attachType: item.attachType,
tempFileId: item.tempFileId
}];
}
return [];
});
}
</script>
<style scoped lang="less">
.customer-edit {
gap: 1rem;
padding: calc(var(--app-nav-height) + 1rem) 0 1rem 0;
display: flex;
flex-direction: column;
.form {
padding: .5rem 0;
background: rgba(255, 255, 255, .92);
box-shadow: var(--td-shadow-1);
border-radius: 1.4rem;
.code-scanner-wrapper {
padding: 1rem;
}
.bound-customer {
gap: .75rem;
padding: 1rem;
display: flex;
flex-direction: column;
border-radius: 1rem;
.tips {
gap: .25rem;
display: flex;
font-size: .875rem;
align-items: center;
}
}
.textarea {
width: 100%;
}
.picker-text {
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.selector {
gap: .75rem;
display: flex;
.actions {
gap: .5rem;
display: flex;
justify-content: flex-end;
}
}
.introducer-profile {
flex: 1;
}
.sex {
gap: .5rem;
display: flex;
}
.photo {
width: 100%;
.tips {
font-size: .875rem;
text-align: center;
margin-top: .5rem;
}
}
}
.file-input {
display: none;
}
}
:global(html.theme-dark) {
.customer-edit {
:deep(.form-item .t-form__label) {
color: #94a3b8;
}
.form {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
}
:deep(.textarea .t-textarea__inner) {
color: #e2e8f0;
background: rgba(15, 23, 42, .72);
border-color: rgba(148, 163, 184, .16);
}
}
}
</style>