import { cnAreaTree } from "@/api/shop.js";
export default {
	data() {
		return {
			loading: false,
			tableRowKey: 'id', // 唯一标识
			isSelecPage: false,  // 翻页保留选择数据
			multipleSelection: [],  // 选中数据
			search: {},  // 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10
			},  // 查询参数页码页数
			total: 0,
			dataList: [],
			showSearch: true,  // 搜索栏是否收起
			dateTimeNum: 0, // 列表查询参数有几个是时间范围查询
			// 添加日期范围映射配置
			dateRangeMapping: {},
			initializationShow: true, // 初始化是否请求列表数据
			areaTreaList: [],  // 三级地区选择
			regionCodeList: ['provinceCode', 'cityCode', 'areaCode'],  // 列表查询时省市区对应的字段名称
		};
	},
	watch: {},
	created() {
		this.multipleSelection = [];
		if (this.initializationShow) this.handleQuery();
	},
	methods: {
		/** 导出按钮操作 */
		handleExport() {
			if (this.exportObj && this.exportObj.url) {
				// 处理日期范围参数
				const exportParams = this.processDateRangeParams({
					...this.queryParams,
					...this.search,
				});

				this.download(this.exportObj.url, {
					...exportParams
				}, `${this.exportObj.name || 'list'}_${new Date().getTime()}.xlsx`)
			}
		},
		/** 获取列表数据  */
		async getList() {
			if (!this.listURL) return
			this.loading = true;

			// 处理日期范围参数
			const processedParams = this.processDateRangeParams({
				...this.queryParams,
				...this.search,
			});

			await this.listURL(processedParams).then(res => {
				// console.log(res)
				this.loading = false;
				if (res.code == 200) {
					this.dataList = [...res.rows];
					this.total = res.total;
				}
			}).catch(err => {
				this.loading = false;
			})
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.handleRefreshPage ? this.handleRefreshPage() : this.getList();
		},
		/** 重置按钮操作 */
		async resetQuery(formName) {
			try {
				formName && this.$refs[formName].resetFields();
			} catch { }
			this.search = {};
			await this.$nextTick();
			this.handleQuery();
		},
		/**
		 * 处理日期范围参数
		 * 将日期范围对象拆分为开始时间和结束时间两个独立参数
		 * @param {Object} params - 原始参数对象
		 * @returns {Object} 处理后的参数对象
		 */
		processDateRangeParams(params) {
			const result = { ...params };

			// 遍历 dateRangeMapping 配置
			for (const [rangeKey, mapping] of Object.entries(this.dateRangeMapping || {})) {
				const rangeValue = result[rangeKey];

				// 如果存在日期范围且为数组格式
				if (rangeValue && Array.isArray(rangeValue) && rangeValue.length === 2) {
					// 删除原始的日期范围字段
					delete result[rangeKey];

					// 添加拆分后的开始和结束时间字段
					result[mapping.start] = rangeValue[0];
					result[mapping.end] = rangeValue[1];
				}
			}
			if (result.areaTreaList && typeof result.areaTreaList === 'object') {
				result.areaTreaList.forEach((area, index) => {
					if (this.regionCodeList[index]) {
						result[this.regionCodeList[index]] = area;
					}
				});

				result.areaTreaList = undefined;
			}
			return result;
		},

		/** 获取中国地区树 */
		getCnAreaTree() {
			cnAreaTree().then(res => {
				this.areaTreaList = res.data?.children || []
			})
		},

		// 多选操作
		selectionChange(val) {
			if (this.isSelecPage) {
				const data_sign = this.dataList.map(item => { return item[this.tableRowKey] });
				const rests_data = this.multipleSelection.filter(item => !data_sign.includes(item[this.tableRowKey]));
				console.log("data_sign = ", data_sign, rests_data, this.multipleSelection);

				if (val.length === 0) {
					this.multipleSelection = rests_data;
				} else {
					this.multipleSelection = [...rests_data, ...val];
				}
			} else {
				this.multipleSelection = val;
			};
		},
		// 当用户手动勾选数据行的 Checkbox 时触发的事件	
		handleSelectionRow(selection, row) {
			// if (this.multipleSelection.length === 0) {
			// 	this.multipleSelection.push(row);
			// } else {
			// 	const index = this.multipleSelection.findIndex(item => item[this.tableRowKey] === row[this.tableRowKey]);
			// 	if (index >= 0) {
			// 		this.multipleSelection.splice(index, 1);
			// 	} else {
			// 		this.multipleSelection.push(row);
			// 	}
			// }
		},
		// 当用户手动勾选全选 Checkbox 时触发的事件
		handleSelectionAll(val) {
			// const numbers = [1, 12, 5, 18, 7, 22];
			// const filteredNumbers = numbers.filter(number => number > 10);
			// console.log(filteredNumbers); // 输出: [12, 18, 22]
			// console.log("tableRowKey = ", val, this.tableRowKey);
			// const data_sign = this.dataList.map(item => { return item[this.tableRowKey] });
			// const rests_data = this.multipleSelection.filter(item => !data_sign.includes(item[this.tableRowKey]));
			// console.log("data_sign = ", data_sign, rests_data, this.multipleSelection);

			// if (val.length === 0) {
			// 	this.multipleSelection = rests_data;
			// } else {
			// 	this.multipleSelection = [...rests_data, ...val];
			// }
			// console.log('handleSelectionAll = ', val);
		},
	},
	watch: {
		dataList: {
			deep: true,
			immediate: true,
			handler(newVal, oldVal) {
				this.$nextTick(() => {
					if (newVal.length && this.multipleSelection.length && this.isSelecPage) {
						this.multipleSelection.forEach(item => {
							const row = newVal.find(newItem => newItem[this.tableRowKey] === item[this.tableRowKey]);
							if (row) this.$refs.multipleTableRef && this.$refs.multipleTableRef.toggleRowSelection(row, true);
						});
					}
				})
			}
		}
	}
}