EquityHomePanel.uvue 14 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
<template>
	<view class="page-container equity-page hf-equity-tab-root fade-in">
		<HomeFrame ref="homeRef"
		           :embed-in-tab-slot="true"
		           :show-footer="true"
		           :swiper-custom="true"
		           :intro-load-complete="loadComplete"
		           :intro-swiper-list="equitySwiperList"
		           :intro-modules="moduleList"
		           intro-eyebrow="权益中心"
		           intro-empty-title="权益配置中"
		           @intro-slide-tap="onIntroSlideTap"
		           @start="handleStart">
		</HomeFrame>
	</view>
</template>

<script setup lang="uts">
import { ComponentPublicInstance, computed, ref } from "vue";
// ✅ UVUE 类型导入:uview-unix 模块为二进制文件,使用本地定义的类型
import { UnSwiperItem } from "@/types/uview-unix-types.uts";

import { getCarBrandsListApi, getEmployeeListApi, getMerchantCarBrandList, getPadBusinessTypeListApi } from "@/api/common-api.uts";
import { getMockData, getSoureData } from "@/api/system-api.uts";
import HomeFrame from "@/components/HomeFrame/index.uvue";
import imageCache from "@/services/cache/ImageCacheService.uts";
import { recordService } from "@/services/recorder/index.uts";
import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts";

const homeRef = ref(null);
const loadComplete = ref<boolean>(false);
const moduleList = ref<Array<any>>([]);
const toolList = ref<Array<any>>([]);
const mediaId = ref<number | string>("");

const EQUITY_SWIPER_PLACEHOLDER = "/static/images/login/nothing.webp";

function normalizeModuleItem(item: any): UTSJSONObject {
	const obj = item as UTSJSONObject;
	const detailTitle =
		(obj.detailTitle as null | string)
		?? (obj.materialTitle as null | string)
		?? (obj.shortTitle as null | string)
		?? (obj.materialName as null | string)
		?? (obj.title as null | string)
		?? (obj.name as null | string)
		?? "";
	const briefIntroduction =
		(obj.briefIntroduction as null | string)
		?? (obj.productIntroduction as null | string)
		?? (obj.introduction as null | string)
		?? (obj.desc as null | string)
		?? "";
	return {
		...obj,
		detailTitle,
		briefIntroduction
	} as UTSJSONObject;
}

function normalizeViewData(data: any): UTSJSONObject {
	const src = data as UTSJSONObject;
	const rawModuleList =
		(src.moduleList as null | Array<any>)
		?? (src.materialInfoList as null | Array<any>)
		?? [];
	const modules = rawModuleList.map((item: any) => normalizeModuleItem(item));
	const tools = (src.toolList as null | Array<any>) ?? [];
	return {
		...src,
		moduleList: modules,
		toolList: tools
	} as UTSJSONObject;
}

function isRenderableImage(value: string): boolean {
	if (value == null || value == "") {
		return false;
	}
	return (
		value.startsWith("http://")
		|| value.startsWith("https://")
		|| value.startsWith("file://")
		|| value.startsWith("content://")
		|| value.startsWith("/")
		|| value.startsWith("./")
		|| value.startsWith("../")
	);
}

function pickModuleCover(obj: UTSJSONObject): string {
	const candidates = [
		obj.thumbnail as any | null,
		obj.thumbnailUrl as any | null,
		obj.bannerImg as any | null,
		obj.contentPicUrl as any | null,
		obj.homeEntranceCover as any | null,
		obj.imageUrl as any | null,
		obj.imgUrl as any | null,
		obj.coverUrl as any | null,
		obj.coverImg as any | null,
		obj.productPoster as any | null,
		obj.detailUrl as any | null
	];
	for (const candidate of candidates) {
		if (candidate == null || typeof candidate !== "string") {
			continue;
		}
		const src = candidate as string;
		if (isRenderableImage(src)) {
			return src;
		}
	}
	return "";
}

function setViewInfo(data: any): void {
	const dataObj = normalizeViewData(data);
	moduleList.value = dataObj.moduleList as Array<any>;
	toolList.value = dataObj.toolList as Array<any>;
	const idValue = dataObj.id;
	mediaId.value = typeof idValue === "number" ? idValue.toString() : (idValue as string) ?? "";
	loadComplete.value = true;
	console.log("[equity] setViewInfo data:", dataObj);
	console.log("[equity] setViewInfo moduleList:", moduleList.value);
	if (moduleList.value.length > 0) {
		console.log("[equity] setViewInfo first module:", moduleList.value[0]);
	}
}

/** 与 `useBoutiqueLogic.normalizePadBizTypeRows` 一致:biz-types/list 响应容错 */
function normalizePadBizTypeRows(bizRes: any | null): any[] {
	if (bizRes == null) {
		return [] as any[];
	}
	if (Array.isArray(bizRes)) {
		return bizRes as any[];
	}
	const root = bizRes as UTSJSONObject;
	const d = root["data"];
	if (d != null && Array.isArray(d)) {
		return d as any[];
	}
	if (d != null) {
		const obj = d as UTSJSONObject;
		const list = obj["list"];
		if (list != null && Array.isArray(list)) {
			return list as any[];
		}
		const records = obj["records"];
		if (records != null && Array.isArray(records)) {
			return records as any[];
		}
	}
	return [] as any[];
}

const rowPadTypeCode = (row: UTSJSONObject): string => {
	const a = row["typeCode"] as string | null;
	if (a != null && a !== "") {
		return a;
	}
	const b = row["type_code"] as string | null;
	return b != null ? b : "";
};

const rowPadTypeName = (row: UTSJSONObject): string => {
	const a = row["typeName"] as string | null;
	if (a != null && a !== "") {
		return a;
	}
	const b = row["type_name"] as string | null;
	return b != null ? b : "";
};

/** 无 `typeItem` 时拉 biz-types 首条写入 storage,与 simgle_app 权益首页 onLoad 一致 */
async function ensurePadTypeItemForReception(): Promise<void> {
	const existing = storage.get("typeItem") as UTSJSONObject | null;
	if (existing != null) {
		const tc = existing["typeCode"] as string | null;
		if (tc != null && tc !== "") {
			return;
		}
	}
	try {
		const bizRes = await getPadBusinessTypeListApi();
		const rows = normalizePadBizTypeRows(bizRes);
		if (rows.length == 0) {
			return;
		}
		const first = rows[0] as UTSJSONObject;
		const typeCode = rowPadTypeCode(first);
		const typeName = rowPadTypeName(first);
		if (typeCode === "") {
			return;
		}
		storage.set(
			"typeItem",
			{
				typeCode: typeCode,
				typeName: typeName
			} as UTSJSONObject,
			0
		);
	} catch (_e) {
		// 忽略:handleStart 会提示无 typeCode
	}
}

async function handleStart(): Promise<void> {
	const permitted = await recordService.isPermission();
	if (permitted != true) {
		return;
	}
	await ensurePadTypeItemForReception();
	const typeItem = storage.get("typeItem") as UTSJSONObject | null;
	let typeCode = "";
	if (typeItem != null) {
		const tc = typeItem["typeCode"] as string | null;
		typeCode = tc != null ? tc : "";
	}
	if (typeCode === "") {
		uni.showToast({ title: "未获取到展业类型,请稍后重试", icon: "none" });
		return;
	}
	const q = `typeCode=${encodeURIComponent(typeCode)}&type=edit`;
	uni.navigateTo({ url: `/pages/equity/detail/index?${q}` });
}

function getReceptionCover(obj: UTSJSONObject): string {
	const source = obj.receptionSourceDetailList;
	if (source == null) {
		return "";
	}
	if (Array.isArray(source)) {
		const list = source as Array<any>;
		for (const item of list) {
			if (item == null) {
				continue;
			}
			const itemObj = item as UTSJSONObject;
			const detailUrl = itemObj.detailUrl as string;
			if (detailUrl != null && isRenderableImage(detailUrl)) {
				return detailUrl;
			}
		}
		return "";
	}
	if (typeof source === "object") {
		const sourceObj = source as UTSJSONObject;
		const detailUrl = sourceObj.detailUrl as string;
		if (detailUrl != null && isRenderableImage(detailUrl)) {
			return detailUrl;
		}
		for (const key in sourceObj) {
			const value = sourceObj[key];
			if (value != null && typeof value === "string" && isRenderableImage(value as string)) {
				return value as string;
			}
			if (value != null && typeof value === "object") {
				const nestedObj = value as UTSJSONObject;
				const nestedUrl = nestedObj.detailUrl as string;
				if (nestedUrl != null && isRenderableImage(nestedUrl)) {
					return nestedUrl;
				}
			}
		}
	}
	return "";
}

function getToolCoverById(moduleId: any | null): string {
	if (moduleId == null) {
		return "";
	}
	for (const item of toolList.value) {
		const itemObj = item as UTSJSONObject;
		if (itemObj.id == moduleId) {
			const cover = itemObj.shortTitleUrl as string;
			if (cover != null && isRenderableImage(cover)) {
				return cover;
			}
		}
	}
	return "";
}

const equitySwiperList = computed((): UnSwiperItem[] => {
	const list = moduleList.value;
	const out: UnSwiperItem[] = [];
	for (let i = 0; i < list.length; i++) {
		const obj = list[i] as UTSJSONObject;
		let cover = pickModuleCover(obj);
		if (cover == null || cover == "") {
			const receptionCover = getReceptionCover(obj);
			if (receptionCover != "") {
				cover = receptionCover;
			} else {
				const moduleId: any | null = obj.id;
				cover = getToolCoverById(moduleId);
			}
		}

		out.push({
			url: cover != "" ? cover : EQUITY_SWIPER_PLACEHOLDER
		} as UnSwiperItem);
	}
	return out;
});

function toPreview(item: any): void {
	const obj = item as UTSJSONObject;
	const id = obj.id as null | number | string;
	if (id == null) return;
	uni.navigateTo({ url: `/pages/equity/detail/index?id=${id}&type=preview` });
}

function onIntroSlideTap(index: number): void {
	const list = moduleList.value;
	if (index >= 0 && index < list.length) {
		toPreview(list[index]);
	}
}
async function getSoure(brandIdList: number[], subBrandIdList: number[]): Promise<void> {
	const userInfo = storage.get("userInfo") as UTSJSONObject;
	const shopMerchantId: string = (userInfo.shopMerchantId as string) ?? "";
	const sceneType: number = (userInfo.sceneType as number) ?? 0;

	const storageKey = `source_${sceneType}_${shopMerchantId}`;
	
	// ✅ 简化调用:imageCache 内部自动判断是否启用
	let data: null | UTSJSONObject = null;
	const cachedData = imageCache.getCache(storageKey);
	
	if (cachedData != null) {
		data = cachedData as UTSJSONObject;
		console.log('[equity] 使用缓存数据');
	}
	
	if (data != null) {
		setViewInfo(data);
	}

	try {
		const requestData = await getSoureData(shopMerchantId, sceneType, {
			brandIdList,
			subBrandIdList
		});
		console.log("[equity] getSoureData response:", requestData);
		
		if (requestData != null) {
			setViewInfo(requestData as UTSJSONObject);
			
			// ✅ 简化调用:imageCache 内部自动判断是否写入
			imageCache.setCache(storageKey, requestData);
		} else {
			loadComplete.value = true;
		}
	} catch (error) {
		console.error("获取数据失败:", error);
		loadComplete.value = true;
	}
}
/** 按序加载车型 */
async function getCarBrandsList(carBrandList: Array<any>, index: number) {
	const item = carBrandList[index] as UTSJSONObject;
	if (item == null) return;

	const storageKey = `${(item.id as number)}_${(item.brandId as number)}_carlist`;
	const carList = uni.getStorageSync(storageKey);

	if (index < carBrandList.length - 1) {
		const nextIndex = index + 1;
		if (carList == null) {
			const list = await getCarBrandsListApi({
				brandId: (item.brandId as string) ?? "",
				childBrandId: (item.id as string) ?? ""
			});
			if (list != null) {
				uni.setStorageSync(storageKey, list);
			}
			getCarBrandsList(carBrandList, nextIndex);
		} else {
			getCarBrandsList(carBrandList, nextIndex);
		}
	}
}
function get_Vehicle_Sales_Data(): void {
	const userInfo = storage.get("userInfo") as UTSJSONObject;
	const storageCarBrandList = storage.get("carBrandList");
	const storageEmployeeList = storage.get("employeeList");
	const shopMerchantId = userInfo.shopMerchantId;
	getMerchantCarBrandList([shopMerchantId ?? ""]).then((res: any) => {
		const resObj = res as UTSJSONObject;
		const dataArray = resObj.data as Array<any>;
		const firstItem = dataArray[0] as UTSJSONObject;
		const carBrandList = [] as any[];
		const list = firstItem.carBrandList as Array<any>;

		const brandIdList: number[] = [];
		const subBrandIdList: number[] = [];
		list?.forEach((e: any) => {
			const eObj = e as UTSJSONObject;
			const childs = eObj.childs as Array<any>;

			childs.forEach((i: any) => {
				const iObj = i as UTSJSONObject;
				iObj.brandName = (eObj.name as string) ?? "";
				iObj.brandId = (eObj.id as number);
				carBrandList.push(iObj);
				const idStr: number = (iObj.id as number);
				subBrandIdList.push(idStr);
			});

			const idStr: number = (eObj.id as number);
			brandIdList.push(idStr);
		});
		getSoure(brandIdList, subBrandIdList);
		dispatch("setCarBrandsList", carBrandList);
		storage.set("carBrandList", carBrandList, 0);
		if (carBrandList.length > 0) {
			const index = 0;
			getCarBrandsList(carBrandList, index);
		}
	});
	/** 获取销售人员 */
	getEmployeeListApi({
		merchantId: shopMerchantId
	}).then(res => {
		dispatch("setEmployeeList", res);
		storage.set("employeeList", res, 0);
	});
}

onLoad((_options) => {
	getMockData(true).then(mockdata => {
		console.log(mockdata, "===");
		const userInfo = storage.get("userInfo") as UTSJSONObject;
		const mockDataObj = mockdata as UTSJSONObject;
		const channelType = userInfo.channelType as number;
		if (channelType == 1 && mockDataObj.boutiqueDefaultCarBrandId != null) {
			state.user.boutiqueDefaultCarBrandId = (mockDataObj.boutiqueDefaultCarBrandId as number);
			if (mockDataObj.defaultCarId != null) {
				state.user.defaultCarId = (mockDataObj.defaultCarId as number);
			}
		}
	});
	get_Vehicle_Sales_Data();
});

onShow(() => {
	const userInfo = storage.get("userInfo");
	if (userInfo == null) {
		storage.remove("userInfo");
		storage.remove("sessionId");
		uni.reLaunch({ url: "/pages/common/login/index" });
		return;
	}

	const userInfoObj = userInfo as UTSJSONObject;
	const shopMerchantId = (userInfoObj.shopMerchantId as string) ?? "";
	const sceneType = (userInfoObj.sceneType as number) ?? 0;

	if (shopMerchantId == null) {
		storage.remove("userInfo");
		storage.remove("sessionId");
		uni.reLaunch({ url: "/pages/common/login/index" });
		return;
	}
});
</script>

<style scoped lang="scss">
@import "../styles/common.scss";
@import "../styles/landscape.scss";
@import "../styles/portrait.scss";

/* 与 BoutiqueHomePanel 一致:嵌在 TabBarShell 槽内时参与 flex,避免竖屏高度链断掉 */
.hf-equity-tab-root {
	flex: 1;
	min-height: 0;
	min-width: 0;
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
}
</style>