local-store.uts 24.2 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 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
/**
 * 本地存储数据库方案
 *
 * 提供灵活、安全、简洁、类数据库的本地存储功能
 * 完美契合 uni-app x 开发需求
 *
 * @example
 * ```uts
 * type UserSchema = {
 *   name: string;
 *   age: number;
 *   email: string;
 *   createdAt: number;
 * }
 *
 * const userStore = new LocalStore<UserSchema>('user', {
 *   name: '',
 *   age: 0,
 *   email: '',
 *   createdAt: 0
 * });
 *
 * // 插入数据
 * const id = userStore.insert({ name: 'Alice', age: 25, email: 'alice@example.com', createdAt: Date.now() });
 *
 * // 查询数据
 * const user = userStore.findOne(id);
 * const users = userStore.find({ age: { $gte: 18 } });
 *
 * // 更新数据
 * userStore.update(id, { age: 26 });
 *
 * // 删除数据
 * userStore.delete(id);
 * ```
 */

import { get, has, isArray, isNull, keys, set } from "./common";

// 更新数据类型
// UTS 不支持 Partial<T>,使用 any 类型,运行时检查
type UpdateData<T> = any;

// 查询操作符类型
type QueryOperator =
	| "$eq"
	| "$exists"
	| "$gt"
	| "$gte"
	| "$in"
	| "$like"
	| "$lt"
	| "$lte"
	| "$ne"
	| "$nin";

// 字段查询操作符类型(UTS 不支持内联对象字面量类型和条件类型,需要先定义)
// 注意:由于 UTS 不支持条件类型,这里使用 number 和 string 类型
// 比较操作符($gt, $gte, $lt, $lte)通常只用于数字类型
// $like 操作符通常只用于字符串类型
// 运行时会在 matchCondition 方法中进行类型检查
type FieldQueryOperator<FieldType> = {
	$eq?: FieldType;
	$exists?: boolean;
	$gt?: number; // 比较操作符用于数字类型
	$gte?: number;
	$in?: FieldType[];
	$like?: string; // like 操作符用于字符串类型
	$lt?: number;
	$lte?: number;
	$ne?: FieldType;
	$nin?: FieldType[];
};

// 查询条件类型
// UTS 不支持映射类型 [K in keyof T],使用 any 类型
// 运行时会在 matchCondition 方法中进行字段检查
type QueryCondition<T> = any;

// 记录类型(包含 id)
// UTS 不支持对象字面量类型的交叉,使用 any 类型
// 实际使用中通过类型断言确保类型安全
// 注意:由于 UTS 的限制,这里使用 any 类型,但在使用时通过类型断言确保类型安全
type RecordWithId<T> = any;

// 排序选项
// UTS 不支持 keyof T,使用 string 类型
// 运行时会在使用时检查字段是否存在
type SortOption<T> = {
	field: string;
	order: "asc" | "desc";
};

// 查询选项
type FindOptions<T> = {
	limit?: number;
	skip?: number;
	sort?: SortOption<T>[];
	where?: QueryCondition<T>;
};

// 统计信息类型
type Stats = {
	size: number;
	total: number;
};

/**
 * 本地存储数据库类
 */
// UTS 不支持 Record<string, any>,使用 any 约束
class LocalStore<T extends any> {
	// Schema 默认值
	private defaults: T;

	// ID 列表的 key(用于快速查询所有记录)
	private idsKey: string;

	// 索引存储前缀
	private indexPrefix: string;

	// 存储前缀
	private prefix: string;

	/**
	 * 构造函数
	 * @param name 存储名称(作为命名空间前缀)
	 * @param schema 数据结构的默认值定义
	 */
	constructor(name: string, schema: T) {
		this.prefix = name;
		this.defaults = schema;
		this.idsKey = `${this.prefix}:__ids__`;
		this.indexPrefix = `${this.prefix}:__index__`;
	}

	/**
	 * 清空所有记录
	 */
	clear(): void {
		const ids = this.getIds();
		for (const id of ids) {
			const key = this.getRecordKey(id);
			uni.removeStorageSync(key);
		}
		this.saveIds([]);
	}

	/**
	 * 统计记录数量
	 */
	count(where?: QueryCondition<T>): number {
		if (where == null) {
			return this.getIds().length;
		}
		return this.find({ where }).length;
	}

	/**
	 * 创建索引(用于快速查找)
	 * @param field 要建立索引的字段名
	 */
	// UTS 不支持 keyof T,使用 string 类型
	createIndex(field: string): void {
		// 获取所有记录
		const records = this.findAll();

		// 清空该字段的旧索引
		// UTS 不支持 String() 构造函数,field 已经是 string 类型
		const indexKey = `${this.indexPrefix}:${field}:__all__`;
		uni.removeStorageSync(indexKey);

		// 建立新索引:字段值 -> ID 列表
		// UTS 不支持 Record 类型,使用 any 类型
		const index: any = {};

		for (const record of records) {
			// UTS 对象属性访问需要使用 get 函数
			const value = get(record, field);
			// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
			const valueKey =
				value != null ? (typeof value === "string" ? value : value.toString()) : "__null__";

			// 使用 set 和 get 维护索引,避免直接使用下标访问
			// 显式指定空数组类型为 any[]
			const emptyArray: any[] = [];
			if (!has(index, valueKey)) {
				set(index, valueKey, emptyArray);
			}
			let idList = get(index, valueKey) as any[] | null;
			// 确保 idList 不为 null,强制断言为非空数组
			if (isNull(idList) || !isArray(idList)) {
				idList = [];
			}
			// 使用非空断言,确保 idList 是数组类型
			const idListArray = idList as any[];
			const recordAny = record as any;
			const idValue = get(recordAny, "id");
			// idValue 可能为 null,需要检查后使用类型断言
			if (!isNull(idValue)) {
				// idListArray 是非空数组,idValue 也不为 null
				idListArray.push(idValue as any);
			}
			set(index, valueKey, idListArray);
		}

		// 保存索引
		uni.setStorageSync(indexKey, index);
	}

	/**
	 * 删除记录
	 */
	delete(id: number | string): boolean {
		if (!this.exists(id)) {
			return false;
		}

		const key = this.getRecordKey(id);
		try {
			uni.removeStorageSync(key);
		} catch (error) {
			console.error(`[LocalStore] 删除失败:`, error);
			return false;
		}

		// 从 ID 列表中移除
		this.removeId(id);

		return true;
	}

	/**
	 * 批量删除(优化版本,直接操作 ID 列表)
	 * @param ids 要删除的 ID 数组
	 */
	deleteByIds(ids: (number | string)[]): number {
		if (ids.length === 0) {
			return 0;
		}

		let count = 0;
		const allIds = this.getIds();

		// 批量删除存储
		for (const id of ids) {
			const key = this.getRecordKey(id);
			try {
				uni.removeStorageSync(key);
				count++;
			} catch (error) {
				console.error(`[LocalStore] 删除失败 ID=${id}:`, error);
			}
		}

		// 批量更新 ID 列表(一次性操作)
		const remainingIds: (number | string)[] = [];
		for (const allId of allIds) {
			if (!ids.includes(allId)) {
				remainingIds.push(allId);
			}
		}
		this.saveIds(remainingIds);

		return count;
	}

	/**
	 * 批量删除
	 */
	deleteMany(where: QueryCondition<T>): number {
		const records = this.find({ where });
		if (records.length === 0) {
			return 0;
		}

		let count = 0;
		for (const record of records) {
			const recordAny = record as any;
			// 通过 get 获取 id,避免直接访问属性导致类型问题
			const idValue = get(recordAny, "id") as null | number | string;
			if (record != null && !isNull(idValue) && this.delete(idValue as number | string)) {
				count++;
			}
		}
		return count;
	}

	/**
	 * 删除索引
	 */
	// UTS 不支持 keyof T,使用 string 类型
	dropIndex(field: string): void {
		// UTS 不支持 String() 构造函数,field 已经是 string 类型
		const indexKey = `${this.indexPrefix}:${field}:__all__`;
		uni.removeStorageSync(indexKey);
	}

	/**
	 * 检查记录是否存在
	 */
	exists(id: number | string): boolean {
		const key = this.getRecordKey(id);
		const record = uni.getStorageSync(key);
		return record != null && record != "";
	}

	/**
	 * 查询记录
	 */
	find(options?: FindOptions<T>): RecordWithId<T>[] {
		const ids = this.getIds();
		let results: RecordWithId<T>[] = [];

		// 获取所有记录
		for (const id of ids) {
			const record = this.get(id);
			if (record != null) {
				results.push(record);
			}
		}

		// 应用查询条件
		if (options != null && options.where != null) {
			results = results.filter((record) => this.matchCondition(record, options.where!));
		}

		// 应用排序
		if (options != null && options.sort != null && options.sort.length > 0) {
			results.sort((a, b) => {
				for (let i = 0; i < options.sort!.length; i++) {
					const sortOption = options.sort![i];
					const field = sortOption.field;
					// UTS 对象属性访问需要使用 get 函数,get 返回 any | null
					const aValueAny = get(a, field);
					const bValueAny = get(b, field);

					// 如果值为 null,跳过比较(null 值排在最后)
					if (isNull(aValueAny) || isNull(bValueAny)) {
						if (isNull(aValueAny) && isNull(bValueAny)) {
							continue; // 两个都是 null,继续下一个字段
						}
						// 一个为 null,另一个不为 null,null 排在后面
						return isNull(aValueAny) ? 1 : -1;
					}

					// 确保值不为 null,使用类型断言
					const aValue = aValueAny as any;
					const bValue = bValueAny as any;

					let comparison = 0;
					if (typeof aValue === "number" && typeof bValue === "number") {
						comparison = aValue - bValue;
					} else if (typeof aValue === "string" && typeof bValue === "string") {
						// UTS 不支持直接使用 < > 比较字符串,手动实现字符串比较
						const aStr = aValue as string;
						const bStr = bValue as string;
						const aLen = aStr.length;
						const bLen = bStr.length;
						const minLen = Math.min(aLen, bLen);

						// 逐个字符比较(使用字符串索引访问)
						for (let j = 0; j < minLen; j++) {
							// UTS 字符串索引访问,charCodeAt 返回 Number?,这里断言为 number
							const aCharCode = aStr.charCodeAt(j) as number;
							const bCharCode = bStr.charCodeAt(j) as number;
							if (aCharCode < bCharCode) {
								comparison = -1;
								break;
							} else if (aCharCode > bCharCode) {
								comparison = 1;
								break;
							}
						}

						// 如果前面的字符都相同,比较长度
						if (comparison == 0) {
							if (aLen < bLen) {
								comparison = -1;
							} else if (aLen > bLen) {
								comparison = 1;
							}
						}
					}

					if (comparison != 0) {
						return sortOption.order == "asc" ? comparison : -comparison;
					}
				}
				return 0;
			});
		}

		// 应用 skip
		if (options != null && options.skip != null) {
			const skipValue = options.skip;
			if (skipValue > 0) {
				results = results.slice(skipValue);
			}
		}

		// 应用 limit
		if (options != null && options.limit != null) {
			const limitValue = options.limit;
			if (limitValue > 0) {
				results = results.slice(0, limitValue);
			}
		}

		return results;
	}

	/**
	 * 获取所有记录
	 */
	findAll(): RecordWithId<T>[] {
		// UTS 要求显式传入参数,这里传入空配置对象
		const emptyOptions: any = {};
		return this.find(emptyOptions as FindOptions<T>);
	}

	/**
	 * 根据索引查找记录
	 * @param field 索引字段
	 * @param value 字段值
	 */
	// UTS 不支持 keyof T,使用 string 类型
	findByIndex(field: string, value: any): RecordWithId<T>[] {
		// UTS 不支持 String() 构造函数,field 已经是 string 类型
		const indexKey = `${this.indexPrefix}:${field}:__all__`;
		// UTS 不支持 Record 类型,使用 any 类型
		const index = uni.getStorageSync(indexKey) as any | null;

		if (isNull(index)) {
			// 索引不存在,使用普通查询
			// UTS 不支持计算属性名 [field],需要先创建对象
			const whereCondition: any = {};
			set(whereCondition, field, value);
			return this.find({ where: whereCondition as QueryCondition<T> });
		}

		// index 已经检查过不为 null,使用类型断言
		// UTS 不支持 Record 类型,使用 any 类型
		const indexObj = index as any;
		// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
		const valueKey =
			value != null ? (typeof value === "string" ? value : value.toString()) : "__null__";
		// 使用 get 获取 ids,避免下标访问
		const idsAny = get(indexObj, valueKey);

		if (isNull(idsAny) || !isArray(idsAny)) {
			return [];
		}

		// 确保 ids 是数组类型
		const ids = idsAny as any[];
		const results: RecordWithId<T>[] = [];
		for (const id of ids) {
			const record = this.get(id);
			if (record != null) {
				results.push(record);
			}
		}

		return results;
	}

	/**
	 * 查找第一条匹配的记录
	 */
	findFirst(where?: QueryCondition<T>): null | RecordWithId<T> {
		const results = this.find({ where, limit: 1 });
		return results.length > 0 ? results[0] : null;
	}

	/**
	 * 查找单条记录
	 */
	findOne(id: number | string): null | RecordWithId<T> {
		return this.get(id);
	}

	/**
	 * 获取单条记录
	 */
	get(id: number | string): null | RecordWithId<T> {
		if (!this.exists(id)) {
			return null;
		}

		const key = this.getRecordKey(id);
		const record = uni.getStorageSync(key) as null | T;

		if (isNull(record)) {
			return null;
		}

		// 合并默认值,确保所有字段都存在
		// record 已经检查过不为 null,使用类型断言
		const merged = this.mergeDefaults(record as any);
		// UTS 不支持对象展开运算符,需要手动创建对象
		const result: any = {};
		const mergedKeys = keys(merged);
		for (const key of mergedKeys) {
			const value = get(merged, key);
			set(result, key, value);
		}
		set(result, "id", id);
		return result as RecordWithId<T>;
	}

	/**
	 * 获取存储统计信息
	 */
	getStats(): Stats {
		const ids = this.getIds();
		let totalSize = 0;

		// 估算存储大小(简单实现)
		for (const id of ids) {
			const record = this.get(id);
			if (record != null) {
				const recordStr = JSON.stringify(record);
				totalSize += recordStr.length;
			}
		}

		return {
			total: ids.length,
			size: totalSize
		};
	}

	/**
	 * 插入新记录
	 * @param idOrData 可以是 ID(string/number),也可以是数据对象(此时自动生成 ID)
	 * @param data 如果第一个参数是 ID,则此为数据;否则忽略
	 * @returns 实际使用的 ID
	 */
	// UTS 不支持 Partial<T>,使用 any 类型
	insert(idOrData: any | number | string, data?: any): number | string {
		let id: number | string;
		let finalData: any;

		if (typeof idOrData === "object") {
			// 调用方式:store.insert({ name: 'Alice' })
			finalData = idOrData;
			id = this.generateId();
		} else {
			// 调用方式:store.insert('user_123', { name: 'Alice' })
			id = idOrData;
			finalData = data != null ? data : {};
		}

		// 验证数据
		if (!this.validateData(finalData)) {
			throw new Error(`[LocalStore] 数据验证失败`);
		}

		// 检查 ID 是否已存在
		if (this.exists(id)) {
			throw new Error(`[LocalStore] ID "${id}" 已存在`);
		}

		// 合并默认值
		const record = this.mergeDefaults(finalData);

		// 保存记录
		const key = this.getRecordKey(id);
		try {
			uni.setStorageSync(key, record);
		} catch (error) {
			throw new Error(`[LocalStore] 存储失败: ${error}`);
		}

		// 添加到 ID 列表
		this.addId(id);

		return id;
	}

	/**
	 * 批量插入
	 * 内部自动分批处理,避免一次性操作过多导致性能问题
	 * @param items 要插入的数据数组
	 * @param batchSize 每批处理的条数,默认100条
	 */
	// UTS 不支持 Partial<T>,使用 any 类型
	insertMany(items: any[], batchSize: number = 100): (number | string)[] {
		const ids: (number | string)[] = [];
		const total = items.length;

		// 如果数据量小于批次大小,直接处理
		if (total <= batchSize) {
			for (const item of items) {
				try {
					// UTS 不支持 undefined,使用 null 作为可选参数占位
					const id = this.insert(item, null);
					ids.push(id);
				} catch (error) {
					console.error(`[LocalStore] 批量插入失败:`, error);
				}
			}
			return ids;
		}

		// 大数据量时,分批处理
		const batchCount = Math.ceil(total / batchSize);

		for (let batch = 0; batch < batchCount; batch++) {
			const start = batch * batchSize;
			const end = Math.min(start + batchSize, total);

			// 处理当前批次
			for (let i = start; i < end; i++) {
				try {
					// UTS 不支持 undefined,使用 null 作为可选参数占位
					const id = this.insert(items[i], null);
					ids.push(id);
				} catch (error) {
					console.error(`[LocalStore] 批量插入失败 [${i + 1}/${total}]:`, error);
				}
			}
		}

		return ids;
	}

	/**
	 * 重建所有索引(在数据迁移后使用)
	 */
	// UTS 不支持 keyof T,使用 string[] 类型
	rebuildIndexes(fields: string[]): void {
		for (const field of fields) {
			this.createIndex(field);
		}
	}

	/**
	 * 更新记录(部分更新)
	 */
	update(id: number | string, updates: UpdateData<T>): boolean {
		if (!this.exists(id)) {
			console.warn(`[LocalStore] 记录 "${id}" 不存在`);
			return false;
		}

		// 验证数据
		if (!this.validateData(updates)) {
			return false;
		}

		// 获取现有记录
		const existing = this.get(id);
		if (isNull(existing)) {
			return false;
		}

		// 合并更新
		// UTS 不支持对象展开运算符,需要手动合并
		// existing 已经检查过不为 null,使用类型断言
		const existingAny = existing as any;
		const updatesObj = updates as UTSJSONObject;
		const updated: any = {};
		// 先复制 existing 的所有属性
		const existingKeys = keys(existingAny);
		for (const key of existingKeys) {
			if (key != "id") {
				// 跳过 id 字段
				const value = get(existingAny, key);
				set(updated, key, value);
			}
		}
		// 再复制 updates 的所有属性(覆盖 existing)
		const updatesKeys = keys(updates);
		for (const key of updatesKeys) {
			const value = get(updates, key);
			set(updated, key, value);
		}
		const updatedResult = updated as T;

		// 保存更新后的记录
		const key = this.getRecordKey(id);
		try {
			uni.setStorageSync(key, updated);
		} catch (error) {
			console.error(`[LocalStore] 更新失败:`, error);
			return false;
		}

		return true;
	}

	/**
	 * 批量更新
	 */
	updateMany(where: QueryCondition<T>, updates: UpdateData<T>): number {
		const records = this.find({ where });
		let count = 0;
		for (const record of records) {
			const recordAny = record as any;
			// 通过 get 获取 id,避免直接访问属性导致类型问题
			const idValue = get(recordAny, "id") as null | number | string;
			if (!isNull(idValue) && this.update(idValue as number | string, updates)) {
				count++;
			}
		}
		return count;
	}

	/**
	 * 添加 ID 到列表
	 */
	private addId(id: number | string): void {
		const ids = this.getIds();
		if (!ids.includes(id)) {
			ids.push(id);
			this.saveIds(ids);
		}
	}

	/**
	 * 深拷贝对象
	 */
	private deepClone(obj: any): any | null {
		// UTS 要求返回类型明确包含 null
		if (obj == null) {
			return null;
		}
		if (typeof obj === "object") {
			return JSON.parse(JSON.stringify(obj));
		}
		return obj;
	}

	/**
	 * 生成唯一 ID
	 * 使用时间戳 + 随机字符串,确保唯一性
	 */
	private generateId(): string {
		return `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
	}

	/**
	 * 获取所有记录的 ID 列表
	 */
	private getIds(): (number | string)[] {
		const ids = uni.getStorageSync(this.idsKey);
		if (isNull(ids) || !isArray(ids)) {
			return [];
		}
		return ids as (number | string)[];
	}

	/**
	 * 获取索引的存储 key
	 */
	private getIndexKey(field: string, value: any): string {
		const valueStr = typeof value === "string" ? value : JSON.stringify(value);
		return `${this.indexPrefix}:${field}:${valueStr}`;
	}

	/**
	 * 获取记录的存储 key
	 */
	private getRecordKey(id: number | string): string {
		// UTS 不支持 String() 构造函数,使用 toString() 或模板字符串
		const idStr = typeof id === "string" ? id : id.toString();
		return `${this.prefix}:${idStr}`;
	}

	/**
	 * 匹配查询条件
	 */
	// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
	private matchCondition(record: RecordWithId<T>, condition: QueryCondition<T>): boolean {
		const conditionKeys = keys(condition);
		for (const field of conditionKeys) {
			// UTS 对象属性访问需要使用 get 函数
			const fieldValue = get(record, field);
			const conditionValue = get(condition, field);

			if (isNull(conditionValue)) {
				continue;
			}

			// 简单值匹配(等于)
			if (typeof conditionValue !== "object") {
				if (fieldValue != conditionValue) {
					return false;
				}
				continue;
			}

			// 操作符匹配
			const operators = conditionValue as any;

			// $eq - 等于
			// UTS 对象属性访问需要使用 get 函数
			if (has(operators, "$eq")) {
				const eqValue = get(operators, "$eq");
				if (fieldValue != eqValue) {
					return false;
				}
			}

			// $ne - 不等于
			if (has(operators, "$ne")) {
				const neValue = get(operators, "$ne");
				if (fieldValue == neValue) {
					return false;
				}
			}

			// $gt - 大于
			if (has(operators, "$gt")) {
				const gtValue = get(operators, "$gt") as number;
				if (typeof fieldValue !== "number") {
					return false;
				}
				const numValue = fieldValue as number;
				if (numValue <= gtValue) {
					return false;
				}
			}

			// $gte - 大于等于
			if (has(operators, "$gte")) {
				const gteValue = get(operators, "$gte") as number;
				if (typeof fieldValue !== "number") {
					return false;
				}
				const numValue = fieldValue as number;
				if (numValue < gteValue) {
					return false;
				}
			}

			// $lt - 小于
			if (has(operators, "$lt")) {
				const ltValue = get(operators, "$lt") as number;
				if (typeof fieldValue !== "number") {
					return false;
				}
				const numValue = fieldValue as number;
				if (numValue >= ltValue) {
					return false;
				}
			}

			// $lte - 小于等于
			if (has(operators, "$lte")) {
				const lteValue = get(operators, "$lte") as number;
				if (typeof fieldValue !== "number") {
					return false;
				}
				const numValue = fieldValue as number;
				if (numValue > lteValue) {
					return false;
				}
			}

			// $in - 在数组中
			if (has(operators, "$in")) {
				const inArray = get(operators, "$in") as any[];
				// fieldValue 可能是 null,需要检查
				if (isNull(fieldValue)) {
					return false;
				}
				if (!inArray.includes(fieldValue as any)) {
					return false;
				}
			}

			// $nin - 不在数组中
			if (has(operators, "$nin")) {
				const ninArray = get(operators, "$nin") as any[];
				// fieldValue 可能是 null,需要检查
				if (isNull(fieldValue)) {
					return false;
				}
				if (ninArray.includes(fieldValue as any)) {
					return false;
				}
			}

			// $like - 字符串匹配(简单实现)
			if (has(operators, "$like")) {
				const likeValue = get(operators, "$like") as string;
				if (typeof fieldValue !== "string" || typeof likeValue !== "string") {
					return false;
				}
				const pattern = likeValue.replaceAll("%", ".*");
				const regex = new RegExp(`^${pattern}$`);
				if (!regex.test(fieldValue)) {
					return false;
				}
			}

			// $exists - 字段是否存在
			if (has(operators, "$exists")) {
				const shouldExist = get(operators, "$exists") as boolean;
				// UTS 对象属性访问需要使用 get 函数
				const fieldExists = has(record, field as string) && get(record, field) != null;
				if (fieldExists != shouldExist) {
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * 合并默认值
	 */
	// UTS 不支持 Partial<T>,使用 any 类型
	// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
	// UTS 对象属性访问需要使用 UTSJSONObject 方式
	private mergeDefaults(data: any): T {
		const result = this.deepClone(this.defaults) as T;
		const dataKeys = keys(data);
		for (const key of dataKeys) {
			if (has(this.defaults, key)) {
				// UTS 对象属性访问需要使用 get 和 set 函数
				const value = get(data, key);
				set(result, key, value);
			}
		}
		return result;
	}

	/**
	 * 从列表中移除 ID
	 */
	private removeId(id: number | string): void {
		const ids = this.getIds();
		const index = ids.indexOf(id);
		if (index != -1) {
			ids.splice(index, 1);
			this.saveIds(ids);
		}
	}

	/**
	 * 保存 ID 列表
	 */
	private saveIds(ids: (number | string)[]): void {
		uni.setStorageSync(this.idsKey, ids);
	}

	/**
	 * 验证数据是否符合 schema
	 */
	// UTS 不支持 Partial<T>,使用 any 类型
	// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
	private validateData(data: any): boolean {
		const dataKeys = keys(data);
		for (const key of dataKeys) {
			if (!has(this.defaults, key)) {
				console.warn(`[LocalStore] 未知字段 "${key}" 在 store "${this.prefix}" 中`);
				return false;
			}
		}
		return true;
	}
}

export default LocalStore;
export type { FindOptions, QueryCondition, RecordWithId, SortOption, Stats, UpdateData };