import { ref, computed, onUnmounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useStore } from '../store/index';
import { batchPrint2, batchPrint } from '../api/patient_hemo_med_record/index'; // 打印模板2
import { delay } from '../utils/utils';

interface BatchParams {
	print2_dateBegin: string; // 开始时间
	print_dateEnd: string; // 结束时间
	print2_patientCode: '';
    isRebuild: number;
}
type CheckParams = string[];

type Params = CheckParams | BatchParams;

interface CheckQuery {
	mode: number;
	print1_records: CheckParams;
}

interface BatchQuery extends BatchParams {
	mode: number;
}

type Query = CheckQuery | BatchQuery;

enum PrintModeType {
	BATCH = 2, // 批量打印
	CHECK = 1, // 勾选打印
}

enum Template {
    template1 = '/gettxform',
    template2 = '/gettxform2',
    template3 = '/backendReport',
}

enum Type {
    ONE = 1, // 直接打印
    TWO = 2, // 先预览再打印
}

export default function usePrintDialysisForm(mode: PrintModeType = PrintModeType.BATCH) {
	const store = useStore();

	const previewGettxdFormOneRef = ref(); // 前端模板1
	const previewGettxdFormTwoRef = ref(); // 前端模板2
	const previewGettxdFormThreeRef = ref(); // 后端模板1

	const printLoading = ref(false);
    const printLoading2 = ref(false);

    const printData = ref<any[]>([]);

	// 当前客户所选择的打印模板
	const templateName = computed(():Template  =>  {
        // @ts-ignore
		return store.state.userInfos.userInfos.client.recordPrintTemplate;
	});

	/**
	 * 获取透析单数据
	 * @param params
	 * @returns
	 */
	async function getDialysData(params: Params) {
		if (!params) return ElMessage.warning('打印透析单参数异常，请联系管理员');
        printData.value = [];
        console.log(templateName.value)
        if (templateName.value === Template.template3) {
            await getRearEndData(params)
        } else {
            await getFrontEndData(params)
        }
	}

	/**
	 * 获取前端打印的数据
	 * @param params
	 * @returns
	 */
	async function getFrontEndData(params: Params) {
		let query: Query;
		printLoading.value = true;
        printData.value = [];
		try {
			if (Array.isArray(params)) {
				// query = {
				// 	mode,
				// 	print1_records: params,
				// };

			const taskQueue = [...params]; // 复制任务队列

            while(taskQueue.length > 0) {
                const batch = taskQueue.splice(0, 10); // 取出一批任务
                const promises = batch.map((tast) => batchPrint({
                    mode,
                    print1_records: tast,
                }));
                await delay(1000);
                const results = await Promise.all(promises);
                results.forEach(item => {
                    printData.value.push(...item.data);
                })
            }

			} else {
                query = {
                    mode,
                    print2_dateBegin: params.print2_dateBegin, // 开始时间
                    print_dateEnd: params.print_dateEnd, // 结束时间
                    print2_patientCode: params.print2_patientCode,
                    isRebuild: params.isRebuild
                }
                const { data } = await batchPrint(query);
                printData.value = data;
			}

		} catch (error) {
			ElMessage.error('透析单数据获取失败：' + error);
		} finally {
            printLoading.value = false;
        }
	}

    /**
     * 获取后端打印的数据
     * @param params 
     */
    async function getRearEndData(params: Params) {
        let query: Query;
        printLoading.value = true;
        printData.value = [];
		try {
			if (Array.isArray(params)) {
				query = {
					mode,
					print1_records: params,
				};
                const taskQueue = [...params]; // 复制任务队列

                while(taskQueue.length > 0) {
                    const batch = taskQueue.splice(0, 10); // 取出一批任务
                    const promises = batch.map((tast) => batchPrint2({
                        mode,
                        print1_records: tast,
                    }));
                    await delay(1000);
                    const results = await Promise.all(promises);
                    results.forEach(item => {
                        printData.value.push(...item.data); 
                    })
                }
    
			} else {
                query = {
                    mode,
                    print2_dateBegin: params.print2_dateBegin, // 开始时间
                    print_dateEnd: params.print_dateEnd, // 结束时间
                    print2_patientCode: params.print2_patientCode,
                    isRebuild: params.isRebuild
                }
                const { data } = await batchPrint2(query);
                printData.value = data;
			}

        } catch (error) {
          ElMessage.error('透析单数据获取失败：' + error);
        } finally {
            printLoading.value = false;
        }
    }

    /**
     * 打印，如果是直接打印需要传第二个参数，如果是预览打印则不需要
     * @param type 打印模式
     * @param params 
     */
    const printDialysis = async (type: Type = Type.TWO, params?: Params) => {
        printLoading2.value = true;
        try {
            if(params){
                // 第二次 就不访问
                await getDialysData(params);
            }
            if (type === Type.ONE) {

                nextTick(() => {
                    if (printData.value.length <= 0) return ElMessage.warning('没有找到可以打印的透析单');
                    domRefPrint()
                });
            } else {
                nextTick(() => {
                    if (printData.value.length <= 0) return ElMessage.warning('没有找到可以打印的透析单');
                    domRefPrint()
                });
            }
        } catch (error) {
            ElMessage.error('透析单打印失败' + error);
        } finally {
            printLoading2.value = false;
        }
    };

    const domRefPrint = () => {
        switch (templateName.value) {
            case Template.template1:
                previewGettxdFormOneRef.value && previewGettxdFormOneRef.value.print();
                break;
            case Template.template2:
                previewGettxdFormTwoRef.value && previewGettxdFormTwoRef.value.print();
                break;
            case Template.template3:
                previewGettxdFormThreeRef.value && previewGettxdFormThreeRef.value.print();
                break;
            default: 
                previewGettxdFormOneRef.value && previewGettxdFormOneRef.value.print();
                break;
        }
    }

    onUnmounted(() => {
        printLoading.value = false;
    })

	return {
        printLoading,
        printLoading2,
        printData,
        previewGettxdFormOneRef,
        previewGettxdFormTwoRef,
        previewGettxdFormThreeRef,
        printDialysis,
		getDialysData,
	};
}
