EditMerchantDialog.vue 17.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
<!-- 编辑商户弹窗 - 复用信息核验商户表单逻辑 -->
<template>
  <d2-dialog class="info-verify-merchant-dialog"
             title="商户信息"
             width="1080px"
             :append-to-body="true"
             :is-visible="dialogVisible"
             @closeDialog="closeDialog"
             @confirmDialog="handleConfirm">
    <div v-loading="loading" class="dialog-body-inner">
      <glsx-combi-form ref="editFormRef"
                       class="info-verify-form"
                       default-width="205px"
                       label-width="120px"
                       :form-data="editFormData"
                       :form-obj="editData"
                       :form-ref="editChildRef"
                       :form-rules="formRules"
                       :is-block="isBlock"
                       :is-edit="true">
        <template #parentId="scope">
          <div class="parent-select-wrap">
            <el-select v-model="editData[scope.scope.name]"
                       v-el-select-loadmore="interestsLoadmoreMerchant"
                       v-loading="merchantLoading"
                       style="width: 205px"
                       filterable
                       remote
                       :placeholder="scope.scope.placeholder || '请选择'"
                       :remote-method="(event) => remoteMethod(event, scope.scope.searchKey, 'store')"
                       @change="scope.scope.changeAttr($event, scope.scope)"
                       @visible-change="(event) => selectVisibleChange(event, scope.scope)">
              <el-option v-for="subItem in scope.scope.optionList"
                         :key="subItem[scope.scope.optionId]"
                         :label="subItem[scope.scope.optionLabel]"
                         :value="subItem[scope.scope.optionId]" />
            </el-select>
          </div>
        </template>
        <template #provinceCity>
          <div class="province-city-slot">
            <ProvinceCity ref="provinceForm"
                          province-label="商户地址:"
                          embed-mode
                          :detail-address-label="detailAddressLabel"
                          :embed-select-width="100"
                          :subdistrict="subdistrict"
                          @merchant-address-part-blur="validateMerchantAddressOnBlur"
                          @selectAddressByMap="selectAddressByMap"
                          @selectCity="selectCity"
                          @selectProvince="selectProvince"
                          @selectTown="selectTown" />
          </div>
        </template>
        <template #selectBrand>
          <div class="brand-select-slot">
            <SelectBrand ref="brandListTree"
                         :brand-list-tree="brandListTree"
                         @brand-change="onBrandFieldChange"
                         @clickBrand="clickBrand" />
          </div>
        </template>
      </glsx-combi-form>
    </div>
  </d2-dialog>
</template>

<script>
import { potentialCustomerDetail } from "@api/salesManagement";
import { showMerchantCreateSuccess, showMerchantSubmitConfirm } from "@/components/merchantVerify/merchantVerifyDialogs";
import { pickCoordDisplayString as pickCoordString } from "@/components/merchantVerify/merchantVerifyDisplay";
import ProvinceCity from "@/components/province-city/index.vue";
import SelectBrand from "@/components/SelectBrand/index.vue";
import util from "@/libs/util";
import merchantVerifyEditFormMixin from "./merchantVerifyEditFormMixin";

/** 表单 id 字段转 number;空不传 */
function submitNumber(val) {
	if (val === "" || val === null || val === undefined) {
		return undefined;
	}
	const n = typeof val === "number" && Number.isFinite(val) ? val : Number.parseInt(val, 10);
	return Number.isNaN(n) ? undefined : n;
}

/** 提交流:统一转成字符串 */
function submitStringField(val) {
	return String(val ?? "").trim();
}

/**
 * merchantBrandList[].cars(integer 车系 id)、
 * merchantBrandList[].merchantBrandId(integer[] 二级车品牌 id)
 */
function normalizeMerchantBrandListForSubmit(list) {
	if (!Array.isArray(list) || !list.length) {
		return [];
	}
	return list
		.map((row) => {
			const cars = Number.parseInt(row.cars, 10);
			const merchantBrandId = Array.isArray(row.merchantBrandId)
				? row.merchantBrandId
						.map(id => Number.parseInt(id, 10))
						.filter(n => !Number.isNaN(n))
				: [];
			return { cars, merchantBrandId };
		})
		.filter(row => !Number.isNaN(row.cars));
}

/** 从商户详情数据映射到表单 editData */
function mapMerchantDetailToEditData(detail) {
	if (!detail) {
		return null;
	}
	const m = detail;

	return {
		// 商户类型:编辑时固定为 4S店(值为 2)
		accounttypeId: m.merchantType || 2,
		// 账户等级
		merchantAccountLevel: m.merchantAccountLevel || "",
		// 上级商户ID(编辑场景使用 parentMerchantNo
		parentId: m.parentMerchantNo,
		// 渠道ID
		channelId: m.channelId || "-",
		// 开通模式
		merchantModel: m.merchantModel || "",
		// 商户名称
		merchantName: m.merchantName || "",
		// 联系电话
		contactPhone: m.merchantLegalPersonPhone || "",
		// 详细地址
		detailAddress: m.merchantAddress || "",
		// 登录账号
		loginAccount: m.merchantLoginAccount || "",
		// 密码不回显
		loginPassword: m.merchantLoginPassword || "",
		// 主营品牌(稍后通过品牌树回显)
		merchantBrandMain: [],
		merchantBrandSlot: "",
		// 上级商户名称
		parentMerchantName: m.parentMerchantName,
		// 省市区信息
		provinceName: m.provinceName || "",
		provinceCode: m.provinceCode || "",
		cityName: m.cityName || "",
		cityCode: m.cityCode || "",
		// 区县信息
		districtCode: m.districtCode || "",
		districtName: m.districtName || "",
		// 经纬度:兼容多种字段名
		lat: m.lat || "",
		lng: m.lng || "",
		latitude: m.lat || "",
		longitude: m.lng || "",
	};
}

/** 从商户详情映射品牌树勾选数据 */
function mapMerchantBrandListFromDetail(detail) {
	if (!detail?.brandTreeList) {
		return [];
	}
	return detail.brandTreeList.flatMap((val) => {
		return val.subList?.map(v => v.id) ?? [];
	});
}

export default {
	name: "EditMerchantDialog",
	components: {
		ProvinceCity,
		SelectBrand,
	},
	mixins: [merchantVerifyEditFormMixin],
	props: {
		visible: {
			type: Boolean,
			default: false,
		},
		submitApi: {
			type: Function,
			required: true,
		},
		/** 客户行数据(包含 merchantNo 用于获取商户详情) */
		customerRow: {
			type: Object,
			default: null,
		},
		/** 商户类型选项(字典 label),如客户信息核验仅 4S:['4S店'] */
		merchantTypeLabels: {
			type: Array,
			default: () => ["4S店"],
		},
	},
	computed: {
		dialogVisible: {
			get() {
				return this.visible;
			},
			set(v) {
				this.$emit("update:visible", v);
			},
		},
	},
	watch: {
		visible(val) {
			if (val) {
				// 弹窗显示时立即开启loading,避免空白闪烁
				this.loading = true;
				this.$nextTick(() => {
					this.onDialogOpened();
				});
			} else {
				this.onDialogClose();
			}
		},
	},
	mounted() {
		if (this.visible) {
			// 弹窗显示时立即开启loading
			this.loading = true;
			this.$nextTick(() => {
				this.onDialogOpened();
			});
		}
	},
	created() {
		this.debouncedOnBrandFieldChange = util.debounce(() => {
			this.syncMerchantBrandSlotPlaceholder();
			if (this.isFirstBrand) {
				this.$refs.editFormRef?.$refs[this.editChildRef]?.validateField("merchantBrandSlot");
			}
		}, 120);
	},
	beforeDestroy() {
		if (this.debouncedOnBrandFieldChange && typeof this.debouncedOnBrandFieldChange.cancel === "function") {
			this.debouncedOnBrandFieldChange.cancel();
		}
	},
	methods: {
		async onDialogOpened() {
			// loading 已在 watch/mounted 中设置,此处无需重复设置
			try {
				this.resetMerchantVerifyForm();
				// 编辑场景:设置当前编辑商户的 merchantNo(用于排除上级商户列表)
				if (this.customerRow && this.customerRow.merchantId) {
					this.setCurrentEditMerchantNo(this.customerRow.merchantId);
				}
				// 编辑场景:立即设置字段为只读文本显示(避免loading期间显示输入框)
				this.initEditFieldDisplayTypes();
				// 编辑场景:修改上级商户字段使用 merchantNo 作为 optionId
				this.setParentIdFieldToUseMerchantNo();
				// 加载表单基础配置(商户类型、账户等级、渠道、开通模式、品牌树)
				await this.initMerchantVerifyForm();
				// 加载商户详情并回显
				await this.loadMerchantDetail();
				this.$nextTick(() => {
					this.$refs.editFormRef?.$refs[this.editChildRef]?.clearValidate();
				});
			} catch (e) {
				console.error("编辑商户弹窗初始化失败:", e);
				// this.$message.error("数据加载失败,请关闭弹窗后重试");
			} finally {
				// 所有接口加载完成后关闭loading
				this.loading = false;
			}
		},
		/**
		 * 编辑场景:修改上级商户字段使用 merchantNo 作为 optionId
		 * 不影响信息核验的表单逻辑,仅在编辑弹窗中使用
		 */
		setParentIdFieldToUseMerchantNo() {
			const parentIdx = this.findIdx("parentId");
			if (parentIdx < 0) {
				return;
			}
			const field = this.editFormData[parentIdx];
			// 修改 optionId 为 merchantNo
			field.optionId = "merchantNo";
			// 保存原始的 changeAttr(用于后续调用)
			if (!field._originalChangeAttr) {
				field._originalChangeAttr = field.changeAttr;
			}
			// 重写 changeAttr,使用 merchantNo 而不是 id
			field.changeAttr = (value, targetItem) => {
				if (value) {
					// value 现在是 merchantNo
					const findItem = targetItem.optionList.find(
						item => String(value) === String(item.merchantNo),
					);
					if (findItem) {
						this.editData.channelId = findItem.channelId;
						this.editData.merchantModel = findItem.merchantModel;
					}
				}
				if (this.lockMerchantType) {
					return;
				}
				this.refreshMerchantTypeRadioDisabled();
				const cur = this.editData.accounttypeId;
				const accIdx = this.findIdx("accounttypeId");
				const opts = this.editFormData[accIdx]?.optionList || [];
				const curOpt = opts.find(
					o => String(o.confId) === String(cur),
				);
				if (cur && curOpt && curOpt.disabled) {
					this.editData.accounttypeId = "";
					this.$nextTick(() => {
						this.$refs.editFormRef?.$refs[
							this.editChildRef
						]?.validateField("accounttypeId");
					});
				}
			};
		},
		onDialogClose() {
			if (this.debouncedOnBrandFieldChange && typeof this.debouncedOnBrandFieldChange.cancel === "function") {
				this.debouncedOnBrandFieldChange.cancel();
			}
			this.resetMerchantVerifyForm();
		},
		closeDialog() {
			this.dialogVisible = false;
		},
		onBrandFieldChange() {
			this.debouncedOnBrandFieldChange();
		},
		/** 加载商户详情并回显到表单 */
		async loadMerchantDetail() {
			if (!this.customerRow || !this.customerRow.merchantId) {
				return;
			}

			// 标记正在加载编辑数据(初始化阶段),避免账户等级联动时重复请求上级商户列表
			this.isLoadingEditDetail = true;

			try {
				const res = await potentialCustomerDetail({
					merchantNo: this.customerRow.merchantId,
				});
				if (!res) {
					return;
				}

				// 回显表单数据
				const editDataMapped = mapMerchantDetailToEditData(res);
				if (editDataMapped) {
					Object.keys(editDataMapped).forEach((key) => {
						this.$set(this.editData, key, editDataMapped[key]);
					});

					// 编辑场景:设置初始商户名称(用于排除重复校验)
					if (editDataMapped.merchantName) {
						this.setInitialMerchantName(editDataMapped.merchantName);
					}
				}

				// 触发账户等级联动(初始化阶段不会自动请求上级商户列表,避免重复请求)
				this.syncMerchantAccountLevelSideEffects(this.editData.merchantAccountLevel);

				// 如果不是工厂级(账户等级=1)且有上级商户,按需加载上级商户列表用于回显(只请求一次)
				// 清空关键词,获取所有上级商户数据,而不是只搜索上级商户名称
				if (this.editData.merchantAccountLevel !== "1" && this.editData.parentId) {
					this.merchantNameKeyword = ""; // 清空关键词,获取所有数据
					await this.get4sAndServiceMerchantList("store");

					// 检查当前列表是否包含回显的上级商户(编辑场景:parentId 是 merchantNo)
					const parentMerchantList = this.baseData.parentMerchantList || [];
					const hasParent = parentMerchantList.some(
						p => String(p.merchantNo) === String(this.editData.parentId),
					);
					if (!hasParent && this.editData.parentId && this.editData.parentMerchantName) {
						// 构造兜底选项(编辑场景:只需要 merchantNo 和 merchantName)
						const fallbackParent = {
							merchantNo: this.editData.parentId,
							merchantName: this.editData.parentMerchantName,
						};
						this.baseData.parentMerchantList.push(fallbackParent);
						// 更新下拉选项
						this.getOptionsList("editFormData", false, "parentId");
					}
				}

				// 回显省市区地址组件
				this.$nextTick(() => {
					const provinceRef = this.$refs.provinceForm;
					if (provinceRef && provinceRef.init) {
						provinceRef.init({
							province: this.editData.provinceName,
							city: this.editData.cityName,
							townName: this.editData.districtName,
							fullAddress: this.editData.detailAddress,
							lng: this.editData.longitude || this.editData.lng,
							lat: this.editData.latitude || this.editData.lat,
						});
					}
				});

				// 回显品牌树勾选
				this.$nextTick(() => {
					const brandRef = this.$refs.brandListTree;
					if (brandRef) {
						// merchantBrandMain 直接返回品牌ID数组
						const brandIds = mapMerchantBrandListFromDetail(res);
						if (brandIds.length) {
							// 直接传入品牌ID数组进行勾选
							brandRef.getCheckList(brandIds);
						}
					}
				});

				// 更新主营品牌占位符
				this.syncMerchantBrandSlotPlaceholder();
			} catch (e) {
				console.error("加载商户详情失败:", e);
				// 接口失败时,设置默认商户类型为2(4S店)
				this.$set(this.editData, "accounttypeId", 2);
			} finally {
				// 初始化完成,取消标记,后续用户手动修改账户等级时正常触发联动
				this.isLoadingEditDetail = false;
			}
		},
		/**
		 * 组装提交请求体(与信息核验新建商户字段保持一致)
		 */
		buildSubmitPayload(merchantBrandList) {
			const d = this.editData;
			const payload = {};
			// 联系电话
			payload.merchantLegalPersonPhone = submitStringField(d.contactPhone);

			// 密码
			if (d.loginPassword && d.loginPassword.trim()) {
				payload.merchantLoginPassword = submitStringField(d.loginPassword);
			}
			// 商户名称
			const nameTrim = submitStringField(d.merchantName);
			if (nameTrim) {
				payload.merchantName = nameTrim;
			}
			// 坐标
			const lngStr = pickCoordString(d.lng, d.longitude);
			const latStr = pickCoordString(d.lat, d.latitude);
			if (lngStr) {
				payload.longitude = lngStr;
				payload.lng = lngStr;
			}
			if (latStr) {
				payload.latitude = latStr;
				payload.lat = latStr;
			}
			// 省code名称
			const pc = submitStringField(d.provinceCode);
			if (pc) {
				payload.provinceCode = pc;
			}
			const pn = submitStringField(d.provinceName);
			if (pn) {
				payload.provinceName = pn;
			}
			// 市code名称
			const cc = submitStringField(d.cityCode);
			if (cc) {
				payload.cityCode = cc;
			}
			const cn = submitStringField(d.cityName);
			if (cn) {
				payload.cityName = cn;
			}
			// 区县code名称
			const dc = submitStringField(d.districtCode);
			if (dc) {
				payload.districtCode = dc;
			}
			const dn = submitStringField(d.districtName);
			if (dn) {
				payload.districtName = dn;
			}
			// 详细地址
			const addrTrim = submitStringField(d.detailAddress);
			if (addrTrim) {
				payload.merchantAddress = addrTrim;
			}
			// 账户等级
			const mal = submitNumber(d.merchantAccountLevel);
			if (mal !== undefined) {
				payload.merchantAccountLevel = mal;
			}
			// 商户类型
			const merchantTypeNum = submitNumber(d.accounttypeId);
			if (merchantTypeNum !== undefined) {
				payload.merchantType = merchantTypeNum;
			}
			// 上级商户号
			const parentMerchantNo = submitStringField(d.parentId);
			if (parentMerchantNo) {
				payload.parentMerchantNo = parentMerchantNo;
			}
			// 商户号
			const merchantId = submitNumber(d.merchantId || this.customerRow?.merchantId);
			if (merchantId !== undefined) {
				payload.merchantNo = merchantId;
			}
			// 主营品牌
			const normalizedBrandList = normalizeMerchantBrandListForSubmit(merchantBrandList);
			payload.merchantBrandList = normalizedBrandList;

			return payload;
		},
		async handleConfirm() {
			const formRef = this.$refs.editFormRef?.$refs[this.editChildRef];
			if (!formRef) {
				return;
			}
			this.syncMerchantBrandSlotPlaceholder();
			formRef.validate(async (valid) => {
				if (!valid) {
					return;
				}
				const merchantBrandList = this.$refs.brandListTree.getMerchantBrandList();
				if (!merchantBrandList?.length) {
					this.$message({
						message: "请选择主营品牌",
						type: "error",
					});
					return;
				}
				try {
					await showMerchantSubmitConfirm(this);
				} catch {
					return;
				}
				this.syncEditDataRegionFromProvinceCityRef();
				const params = this.buildSubmitPayload(merchantBrandList);
				this.loading = true;
				try {
					await Promise.resolve(this.submitApi(params));
					await showMerchantCreateSuccess(this);
					this.$emit("success");
					this.closeDialog();
				} catch (e) {
					/* 接口失败由全局封装提示 */
				} finally {
					this.loading = false;
				}
			});
		},
	},
};
</script>

<style lang="scss" scoped>
$slot-exclude: ":not(.province-city-slot):not(.brand-select-slot)";

.dialog-body-inner {
	min-height: 120px;
	max-height: 70vh;
	overflow-y: auto;

	> .merchant-form-section-title:not(:first-child) {
		margin-top: 16px;
	}
}

.merchant-form-section-title {
	width: 100%;
	height: 50px;
	line-height: 50px;
	font-size: 16px;
	font-weight: bold;
	color: #333333;
	margin-bottom: 16px;
	border-bottom: 1px solid #e5e5e5;
}
</style>