import { ref, computed, onUnmounted, nextTick } from 'vue';
import { exportJsonToExcel } from '../utils/Export2';
import { ElMessage } from 'element-plus';

/**
 * 导出全部数据为excel
 * @param fetchPageData 获取数据方法
 * @param fetchTotl 获取总条数方法
 * @param excelName excel名称
 * @param comparison 键值对对照
 * @param pageSize 每页的条数
 * @returns 
 */
export function useExportAll(fetchPageData: Function, fetchTotl: Function, excelName: string, comparison: Object, pageSize: number = 200) {
	const exporting = ref(false); // 导出状态
	const abortController = ref<AbortController | null>(null); // 用于中止请求
    const total = ref(0);
    const comparisonRef = ref(comparison); // 创建响应式引用
    
    // 提供更新comparison的方法
    const updateComparison = (newComparison: Object) => {
        comparisonRef.value = newComparison;
    };

	const exportAll = async () => {
		if (exporting.value) return;
		exporting.value = true;
        const totalNum = await fetchTotl();
        total.value = totalNum;
        if (total.value <= 0) {
            exporting.value = false;
            return ElMessage.warning('暂无可导出数据')
        }
		abortController.value = new AbortController();
		const signal = abortController.value.signal;

		const pages = Math.ceil(total.value / pageSize);
		const allData: any[] = [];

		try {
			for (let page = 1; page <= pages; page++) {
				if (signal.aborted) break;
				const pageData: any[] = await fetchPageData(page, pageSize);
				// 只保留comparison中定义的字段
				const filteredData = pageData.map(item => {
					const filteredItem: any = {};
					Object.keys(comparisonRef.value).forEach(key => {
						if (item.hasOwnProperty(key)) {
							filteredItem[key] = item[key];
						}
					});
					return filteredItem;
				});
				allData.push(...filteredData);
			}

			if (!signal.aborted && allData.length > 0) {
				// comparison 的 key 是字段名，value是标题
				const exportData = [comparisonRef.value, ...allData];
			const keys = Object.keys(comparisonRef.value).map((k) => k);
				// 调用工具导出
				exportJsonToExcel({
					header: null,
					data: exportData,
					key: keys,
					title: '',
					filename: excelName,
					autoWidth: false,
				});
        ElMessage.success('导出成功')
			}
		} catch (err: any) {
			console.error('导出全部数据失败：', err);
            ElMessage.error('导出失败');
		} finally {
			exporting.value = false;
			abortController.value = null;
		}
	};

	const abortExport = () => {
		if (abortController.value) {
			abortController.value.abort();
			exporting.value = false;
		}
	};

	onUnmounted(() => {
		abortExport();
	});

	return {
		exporting,
		exportAll,
		abortExport,
		updateComparison,
	};
}
