import { ref, nextTick } from 'vue';
import { ListReceipts1Params, DrugTypeEnum } from '../api/HemodiPatients/types';
import { listReceipts1Api, listReceipts2Api, listReceipts3Api } from '../api/HemodiPatients/index';
import { billInfoListReceipts1Api, billInfoListReceipts2Api, billInfoListReceipts3Api } from '../api/fee/index';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { useStore } from '/@/store/index';
import { getMedHistoryList } from '/@/api/HemodiPatients/medHistory';
import { getDefaultHisPharmacistApi } from '/@/api/fee/his_pharmacy';
import { getUsersByRoleGroup } from '/@/api/user';

export default function usePrescriptionPrint() {
	const prescriptionNotesRef = ref(); // 处方笺
	const injectionSheetRef = ref(); // 注射单
	const diagnosisAndTreatmentFormRef = ref(); // 诊疗单
	const applicationFormRef = ref(); // 申请单
	const prescriptionNotesByZqRef = ref(); // 肇庆单独的西药单
	const comprehensiveSingleRef = ref(); // 综合单

	const store: any = useStore();

	const prescriptionNotesToTwosClients = ['CLIENT9303194426563kPrK'];

	const printPrescriptionLoading = ref(false);

	/**
	 * 打印
	 * @param drugType 药物类型
	 * @param pbsCode 处方编号
	 * @param patCode 患者编号
	 * @param doctorOptions 药师列表
	 */
	const prescriptionPrint = async (drugType: DrugTypeEnum, pbsCode: string, patCode: string, billSetDoctorSignPic: string, doctorOptions: any[]) => {
		printPrescriptionLoading.value = true;
		const loadingInstance = ElLoading.service({
			fullscreen: true,
			text: '加载中...',
		});
		try {
			const query: ListReceipts1Params = {
				drugType,
				pbsCode,
			};

			let allDatas: any = {};


			// 获取默认药师
			let pharmacyOperator = ''; // 默认药师
			if (drugType === DrugTypeEnum.medicine) {
				const pharmRes = await getDefaultHisPharmacistApi({ clientCode: store.state.userInfos.userInfos.client.code});
				const pharmacyOperatorItem = doctorOptions.find(e => e.code === pharmRes.data);
				if (pharmacyOperatorItem) {
					pharmacyOperator = pharmacyOperatorItem.userName;
				}
			}


			if (drugType === DrugTypeEnum.medicine || drugType === DrugTypeEnum.injection) {
				const { data } = await listReceipts1Api(query);
				allDatas = data;
			} else if (drugType === DrugTypeEnum.diagnosisTreatment) {
				const { data } = await listReceipts2Api(pbsCode);
				allDatas = data;
			} else if (drugType === DrugTypeEnum.apply) {
				const { data } = await listReceipts3Api(pbsCode);
				allDatas = data;
			} else if (drugType === DrugTypeEnum.comprehensive) { 
				const result =  await Promise.all([listReceipts1Api(query), listReceipts2Api(pbsCode)]);
				const res = result[0].data;
				res.列表 = [...res.列表, ...result[1].data.列表];
				allDatas = res;
			}

			// 如果是定制的西药单，需要再请求一下病史接口
			let patHistory = '';
			if (prescriptionNotesToTwosClients.includes(store.state.userInfos.userInfos.client.code) && drugType ===  DrugTypeEnum.medicine) {
				const history = await getMedHistoryList({ page: 1, size: 1, wherecondition: `patient_code = '${patCode}'`, ordercondition: `med_date desc`});
				if (history.data.list.length > 0) {
					patHistory = history.data.list[0].historyIsAllergy === 0 ? '无过敏史' : (history.data.list[0].historyIsAllergy === 2 ? '过敏史不详' : history.data.list[0].historyAllergyText || '');
				}
			}

			console.log('allDatas: ', allDatas)
			nextTick(() => {
				loadingInstance.close();
			});
			// 判断处方类型是大于同步状态，只要有一个未同步的就不让打印
			const notAsyncHis = allDatas.列表.filter((e: any) => e.处方状态 === 0).map(e => e.药品名称 || e.名称 || e.检验项目);
			if (notAsyncHis.length > 0 && store.state.userInfos.userInfos.isUseHisSyncMode) {
				ElMessageBox.confirm(`还未同步至HIS，确认要打印吗?`, '提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						switch (drugType) {
							case DrugTypeEnum.medicine:
								if (prescriptionNotesToTwosClients.includes(store.state.userInfos.userInfos.client.code)) {
									console.log('formatPrintFormData(allDatas): ', formatPrintFormData(allDatas))
									prescriptionNotesByZqRef.value && prescriptionNotesByZqRef.value.print([formatPrintFormData(allDatas)], patHistory, billSetDoctorSignPic, allDatas.HIS药师 || pharmacyOperator);
								} else {
									prescriptionNotesRef.value && prescriptionNotesRef.value.print([formatPrintFormData(allDatas)], allDatas.HIS药师 || pharmacyOperator);
								}
								break;
							case DrugTypeEnum.injection:
								injectionSheetRef.value && injectionSheetRef.value.print([formatPrintFormData(allDatas)]);
								break;
							case DrugTypeEnum.diagnosisTreatment:
								diagnosisAndTreatmentFormRef.value && diagnosisAndTreatmentFormRef.value.print([formatPrintFormData2(allDatas)]);
								break;
							case DrugTypeEnum.apply:
								applicationFormRef.value && applicationFormRef.value.print([formatPrintFormData3(allDatas)]);
								break;
							case DrugTypeEnum.comprehensive:
								// 这里是综合单
								comprehensiveSingleRef.value && comprehensiveSingleRef.value.print([formatPrintFormData4(allDatas)], allDatas.HIS药师 || pharmacyOperator);
								break;
						}
					})
					.catch(() => {
					});
			} else {
				switch (drugType) {
					case DrugTypeEnum.medicine:
						if (prescriptionNotesToTwosClients.includes(store.state.userInfos.userInfos.client.code)) {
							prescriptionNotesByZqRef.value && prescriptionNotesByZqRef.value.print([formatPrintFormData(allDatas)], patHistory, billSetDoctorSignPic, allDatas.HIS药师 || pharmacyOperator);
						} else {
							prescriptionNotesRef.value && prescriptionNotesRef.value.print([formatPrintFormData(allDatas)], allDatas.HIS药师 || pharmacyOperator);
						}
						break;
					case DrugTypeEnum.injection:
						injectionSheetRef.value && injectionSheetRef.value.print([formatPrintFormData(allDatas)]);
						break;
					case DrugTypeEnum.diagnosisTreatment:
						diagnosisAndTreatmentFormRef.value && diagnosisAndTreatmentFormRef.value.print([formatPrintFormData2(allDatas)]);
						break;
					case DrugTypeEnum.apply:
						console.log('化验单的数据: ', [allDatas]);
						applicationFormRef.value && applicationFormRef.value.print([formatPrintFormData3(allDatas)]);
						break;
						case DrugTypeEnum.comprehensive:
							comprehensiveSingleRef.value && comprehensiveSingleRef.value.print([formatPrintFormData4(allDatas)], allDatas.HIS药师 || pharmacyOperator);
							break;
				}
			}
		} catch (error) {
			ElMessage.error('处方打印失败:' + error?.message);
			console.log(error)
		} finally {
			printPrescriptionLoading.value = false;
			loadingInstance.close();
		}
	};

	const formatPrintFormData = (data) => {
		const dataCopy = JSON.parse(JSON.stringify(data));

		let 开方日期 = '';
		let 处方单号 = '';
		let 开方医生 = '';
		let 总金额: any = 0;

		if (dataCopy.列表 && dataCopy.列表.length > 0) {
			开方日期 = formatDate(new Date(dataCopy.列表[0].处方开立时间), 'YYYY-mm-dd');
			处方单号 = dataCopy.列表[0].处方编号;
			开方医生 = dataCopy.列表[0].开单医生;
			dataCopy.列表.forEach((e) => {
				总金额 += e.金额;
			});
		}

		总金额 = 总金额.toFixed(4);
		return Object.assign(dataCopy, { 开方日期, 处方单号, 总金额, 开方医生 });
	};

	const formatPrintFormData2 = (data) => {
		const dataCopy = JSON.parse(JSON.stringify(data));

		let 开方日期 = '';
		let 处方单号 = '';
		let 开方医生 = '';
		let 总金额: any = 0;

		if (dataCopy.列表 && dataCopy.列表.length > 0) {
			开方日期 = formatDate(new Date(dataCopy.列表[0].处方开立时间), 'YYYY-mm-dd');
			处方单号 = dataCopy.列表[0].处方编号;
			开方医生 = dataCopy.列表[0].开单医生;
			dataCopy.列表.forEach((e) => {
				总金额 += e.金额;
				e.药品名称 = e.名称;
			});
		}
		总金额 = 总金额.toFixed(4);
		return Object.assign(dataCopy, { 开方日期, 处方单号, 总金额, 开方医生 });
	};

	const formatPrintFormData3 = (data) => {
		const dataCopy = JSON.parse(JSON.stringify(data));

		let 开方日期 = '';
		let 处方单号 = '';
		let 开方医生 = '';
		let 总金额: any = 0;

		if (dataCopy.列表 && dataCopy.列表.length > 0) {
			开方日期 = formatDate(new Date(dataCopy.列表[0].送检日期), 'YYYY-mm-dd');
			处方单号 = dataCopy.列表[0].处方编号;
			开方医生 = dataCopy.列表[0].开单医生;
			dataCopy.列表.forEach((e) => {
				总金额 += e.价格;
				e.单价 = e.价格;
				e.药品名称 = e.检验项目;
			});
		}
		总金额 = 总金额.toFixed(4);
		return Object.assign(dataCopy, { 开方日期, 处方单号, 总金额, 开方医生 });
	};

	const formatPrintFormData4 = (data) => {
		const dataCopy = JSON.parse(JSON.stringify(data));

		let 开方日期 = '';
		let 处方单号 = '';
		let 开方医生 = '';
		let 总金额: any = 0;

		if (dataCopy.列表 && dataCopy.列表.length > 0) {
			开方日期 = formatDate(new Date(dataCopy.列表[0].处方开立时间), 'YYYY-mm-dd');
			处方单号 = dataCopy.列表[0].处方编号;
			开方医生 = dataCopy.列表[0].开单医生;
			dataCopy.列表.forEach((e) => {
				总金额 += e.金额;
			});
		}
		if (Array.isArray(dataCopy.列表)) {
			dataCopy.列表 = dataCopy.列表.map(v => {
				const item = {
					药品名称: v?.药品名称 || v?.名称 || '',
					药品规格: v?.药品规格 || '',
					单价: v?.单价 || '',
					数量: v?.数量 || '',
					包装单位: v?.包装单位 || '',
					用药天数: v?.用药天数 || '',
					单次用量: v?.单次用量 || '',
					剂量单位: v?.剂量单位 || '',
					用药间隔: v?.用药间隔 || '',
					给药途径: v?.给药途径 || '',
					是否药品: !!v?.药品名称
				}
				return item
			})
		}

		总金额 = 总金额.toFixed(4);
		return Object.assign(dataCopy, { 开方日期, 处方单号, 总金额, 开方医生 });
	};

	/**
	 * 收费清单的打印
	 * @param patientCode
	 * @param date
	 * @param drugType
	 */
	const prescriptionPrintBySfqd = async (patientCodeLists: string[], date: string, drugType: number) => {
		printPrescriptionLoading.value = true;
		const loadingInstance = ElLoading.service({
			fullscreen: true,
			text: '加载中...',
		});

		try {
			const items = patientCodeLists.map((v) => {
				const item = {
					patientCode: v,
					date,
					drugType,
				};
				return item;
			});

			console.log(items);

			let allDatas = [];

			// 获取默认药师
			let pharmacyOperator = ''; // 默认药师
			if (drugType === DrugTypeEnum.medicine) {
				let doctorOptions = []; // 获取医生列表
				const params = {
					clientCode: store.state.userInfos.userInfos.client.code,
					isFilterDisabledUser: 0 as 0 | 1,
					roleClasses: ['药师'],
				}
				const { data } = await getUsersByRoleGroup(params);
				doctorOptions = data;

				const pharmRes = await getDefaultHisPharmacistApi({ clientCode: store.state.userInfos.userInfos.client.code});
				const pharmacyOperatorItem = doctorOptions.find(e => e.code === pharmRes.data);
				if (pharmacyOperatorItem) {
					pharmacyOperator = pharmacyOperatorItem.userName;
				}
			}

			await Promise.all(
				items.map(async (v) => {
					if (drugType === DrugTypeEnum.medicine || drugType === DrugTypeEnum.injection) {
						// @ts-ignore
						const { data } = await billInfoListReceipts1Api(v);
						allDatas.push(formatPrintFormData(data));
					} else if (drugType === DrugTypeEnum.diagnosisTreatment) {
						const { data } = await billInfoListReceipts2Api(v);
						allDatas.push(formatPrintFormData2(data));
					} else if (drugType === DrugTypeEnum.apply) {
						const { data } = await billInfoListReceipts3Api(v);
						allDatas.push(formatPrintFormData3(data));
					}
				})
			);

			console.log('allData: ', allDatas);

			nextTick(() => {
				loadingInstance.close();
			});
			console.log(drugType);
			switch (drugType) {
				case DrugTypeEnum.medicine:
					allDatas = allDatas.map(v => {
						if (!v?.HIS药师) {
							v.HIS药师 = pharmacyOperator
						}
						return v
					})
					console.log('============allDatas:', allDatas);
					prescriptionNotesRef.value && prescriptionNotesRef.value.print(allDatas);
					break;
				case DrugTypeEnum.injection:
					injectionSheetRef.value && injectionSheetRef.value.print(allDatas);
					break;
				case DrugTypeEnum.diagnosisTreatment:
					diagnosisAndTreatmentFormRef.value && diagnosisAndTreatmentFormRef.value.print(allDatas);
					break;
				case DrugTypeEnum.apply:
					applicationFormRef.value && applicationFormRef.value.print(allDatas);
					break;
			}
		} catch (error) {
			ElMessage.error('收费清单打印失败:' + error?.message);
		} finally {
			printPrescriptionLoading.value = false;
			nextTick(() => {
				loadingInstance.close();
			});
		}
	};

	return {
		prescriptionNotesRef,
		injectionSheetRef,
		diagnosisAndTreatmentFormRef,
		applicationFormRef,
		prescriptionNotesByZqRef,
		comprehensiveSingleRef,
		printPrescriptionLoading,
		prescriptionPrint,
		prescriptionPrintBySfqd,
	};
}
