import { getToken, getTokenFromApi } from './auth'
import { saveMediaInfo, saveMediaRecord, getLatestRecord, removeInfoAndRecord, getJoinList } from '@/api/work'
import { globalConfig } from '@/config'


// 类型定义保持不变
export type ApiResponse = {
	code : number;
	msg : string;
	data : MediaInfoData[];
}

export type MediaInfoData = {
	pk : string;
	workorder ?: string;
	invname ?: string;
	productcode ?: string;
	cardno ?: string;
	model ?: string;
	graphid ?: string;
	ver ?: string;
	phase ?: string;
	processno ?: string;
	createtime ?: string;
	createuser ?: string;
	updatetime ?: string;
	updateuser ?: string;
	qmImageTaskClist ?: MediaRecordData[];
}

export type MediaRecordData = {
	senum ?: string;
	photoitem ?: string;
	part ?: string;
	partno ?: string;
	pk : string;
	exampleid ?: string;
	descb ?: string;
	num ?: number;
	urlspl ?: string;
	imgname ?: string;
	urlpdt ?: string;
	createtime ?: string;
	createuser ?: string;
	updatetime ?: string;
	updateuser ?: string;
	photoFiles_example ?: PhotoFilesExample[];
}

export type PhotoFilesExample = {
	_id ?: string,
}

export const showProgress = (index : number, title : string) => {
	// 在Android设备上，需要给hideLoading和showLoading之间添加延迟
	// 先隐藏之前的加载提示
	uni.hideLoading();
	// 添加50ms的延迟，确保hideLoading完全执行后再显示新的进度
	setTimeout(() => {
		uni.showLoading({
			title: `正在${title}第${index}个任务数据`,
			mask: true
		});
	}, 50);
}

//声像任务下载
export const downloadDataFromAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
	try {
		uni.showLoading({ title: '任务开始下载' });
		const apiToken = await getTokenFromApi();

		if (apiToken == null || apiToken == '') {
			uni.hideLoading();
			uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
			return false
		}

		//校验是否已经存在未执行的产品号，若已经存在则提示用户该产品号是否需要被覆盖，
		//如果没有则直接保存。如果有存在已经在执行中的产品号，则提示已存在执行中的任务
		const infoJson = await getLatestRecord(productCode, null);
		if (infoJson?.['data'] != null) {
			let info = infoJson?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
			let ingNum = parseInt(info?.['statusRecordCount'] as string);
			//覆盖标识位
			let overwiteFlag = ref(false);
			// 先检查是否有任务正在执行中
			if (info != null && ingNum > 0) {
				uni.showToast({ title: `当前产品号已有任务在执行中！`, icon: 'error' });
				return false;
			}
			// 使用Promise来处理异步流程
			let deleteDataPromise = new Promise<boolean>((resolve) => {
				if (info != null && ingNum == 0) {
					//可以被覆盖，需要有提示框，给用户确认
					uni.showModal({
						title: '系统提示',
						content: '该产品号已存在任务是否覆盖掉？',
						cancelText: '取消',
						confirmText: '确定',
						success: function (res) {
							if (res.confirm) {
								// 标记为需要覆盖
								overwiteFlag.value = true;
								// 执行删除数据操作
								let pid = info?.['pdid'] as string;
								removeInfoAndRecord(pid).then((recordDelResponse) => {
									console.log('删除数据响应:', recordDelResponse);
									// 删除成功，解析Promise并允许继续执行
									// 确保模态框已完全关闭后再解析Promise
									setTimeout(() => {
										resolve(true);
									}, 300);
								}).catch((error) => {
									console.error('删除数据失败:', error);
									uni.showToast({ title: '删除旧数据失败', icon: 'error' });
									resolve(false);
								});
							} else {
								// 用户取消覆盖
								overwiteFlag.value = false;
								resolve(false);
							}
						}
					});
				} else {
					// 不需要显示确认框，直接解析Promise
					resolve(true);
				}
			});

			// 等待删除数据操作完成
			const canContinue : boolean = await deleteDataPromise;
			if (!canContinue) {
				// 如果不能继续（删除失败或用户取消），则终止函数执行
				return false;
			}
		}

		// 使用Promise处理HTTP请求，避免嵌套Promise
		return new Promise<boolean>((resolve) => {
			uni.request({
				url: `${globalConfig.host}${globalConfig.downloadURL}${productCode}`,
				method: 'GET',
				header: {
					'token': apiToken
				},
				success: (res) => {
					let singleObject = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;

					if (singleObject != null && singleObject.code == 666) {
						let mediaInfoList = singleObject?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
						if (mediaInfoList != null && mediaInfoList.length > 0) {
							mediaInfoList.forEach(item => {
								if (item != null) {
									let data = JSON.parse<MediaInfoData>(item.toJSONString());
									if (data != null) {
										saveMediaInfo(item).then((resSave : UTSJSONObject) => {
											const lastIdStr = resSave?.['lastId'] as string | null;
											const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
											if (lastId != null) {
												let recordList = data?.['qmImageTaskClist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
												if (recordList != null && recordList.length > 0) {
													const totalRecords = recordList.length;
													let processedRecords = 0;

													// 使用async/await处理循环中的异步操作
													const processAllRecords = async () => {
														// 创建一个Map来跟踪不同photoitem的计数
														const photoItemCounter : Map<string, number> = new Map();

														for (var i = 0; i < recordList.length; i++) {
															// 更新进度
															processedRecords++;
															showProgress(processedRecords, '下载');

															const record : MediaRecordData = recordList[i] as MediaRecordData;
															// 获取各个字段的值
															const photoitem = record.photoitem as string;
															// 根据photoitem类型统计senum
															if (!photoItemCounter.has(photoitem)) {
																photoItemCounter.set(photoitem, 1);
															} else {
																const currentCount = photoItemCounter.get(photoitem);
																photoItemCounter.set(photoitem, (currentCount != null ? currentCount : 0) + 1);
															}
															const senum = photoItemCounter.get(photoitem);
															const finalSenum = senum != null ? senum : 1;
															const partno = record.partno;
															const part = record.part;
															const pk = record.pk;
															const descb = record.descb;
															const num = record.num;
															const imgname = record.imgname;
															const urlpdt = record.urlpdt;
															const createtime = record.createtime;
															const createuser = record.createuser;
															const updatetime = record.updatetime;
															const updateuser = record.updateuser;

															// 创建数组来存储图片ID和保存路径
															var exampleidArr = [] as string[];
															var imagePathsArr = [] as string[];

															let exampleList = record?.['photoFiles_example'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
															if (exampleList != null && exampleList.length > 0) {
																// 下载所有图片并等待完成
																const imageDownloadPromises = [] as Promise<void>[];

																// 顺序下载和保存图片，避免并行导致的随机失败
																for (var j = 0; j < exampleList.length; j++) {
																	const example : PhotoFilesExample = exampleList[j] as PhotoFilesExample;
																	if (example._id != null) {
																		exampleidArr.push(example._id);

																		try {
																			// 串行执行，等待前一张图片处理完成再处理下一张
																			await new Promise<void>((resolve, reject) => {
																				// 使用uni.downloadFile下载图片
																				uni.downloadFile({
																					url: `${globalConfig.getImgURL}${example._id}`,
																					header: {
																						'token': apiToken
																					},
																					success: (res) => {
																						if (res.statusCode === 200) {
																							// 等待一小段时间确保文件完全下载
																							setTimeout(() => {
																								// 图片下载成功，使用uni.saveImageToPhotosAlbum保存到相册
																								uni.saveImageToPhotosAlbum({
																									filePath: res.tempFilePath,
																									success: () => {
																										console.log('图片保存成功:', res.tempFilePath);
																										// 将保存路径添加到数组中
																										imagePathsArr.push(res.tempFilePath);

																										// 保存成功后等待1秒再处理下一张
																										setTimeout(() => {
																											resolve();
																										}, 1000);
																									},
																									fail: (err) => {
																										console.error('保存图片失败:', err);
																										// 保存失败也继续处理下一张，但记录错误
																										setTimeout(() => {
																											reject(err);
																										}, 500);
																									}
																								});
																							}, 500); // 等待500ms确保文件完全下载
																						} else {
																							console.error('下载图片失败，状态码:', res.statusCode);
																							reject(new Error(`下载图片失败，状态码: ${res.statusCode}`));
																						}
																					},
																					fail: (err) => {
																						console.error('请求图片失败:', err);
																						reject(err);
																					}
																				});
																			});
																		} catch (error) {
																			console.error(`处理第${j + 1}张图片时出错:`, error);
																			// 出错后继续处理下一张图片
																		}
																	}
																}
															}

															// 拼接图片ID和路径
															const exampleid = exampleidArr.join(",");
															const imagePaths = imagePathsArr.join(",");
															console.log("=========================================>");
															console.log(imagePaths);

															// 使用三目运算符判断，当值为null时直接插入null，否则用单引号括起来
															var values = `${finalSenum === null ? '1' : `'${finalSenum}'`}, ${photoitem === null ? 'null' : `'${photoitem}'`}, ${data?.['productcode'] === null ? 'null' : `'${data?.['productcode']}'`},${part === null ? 'null' : `'${part}'`},${partno === null ? 'null' : `'${partno}'`},${pk === null ? 'null' : `'${pk}'`},${exampleid === null ? 'null' : `'${exampleid}'`},${descb === null ? 'null' : `'${descb}'`},${num === null ? 0 : num},1,'', ${imagePaths === null ? 'null' : `'${imagePaths}'`},${imgname === null ? 'null' : `'${imgname}'`},${urlpdt === null ? 'null' : `'${urlpdt}'`}, ${createtime === null ? 'null' : `'${createtime}'`}, ${createuser === null ? 'null' : `'${createuser}'`}, ${updatetime === null ? 'null' : `'${updatetime}'`}, ${updateuser === null ? 'null' : `'${updateuser}'`}, ${lastId === null ? 0 : lastId}`;

															// 只有在所有图片下载完成后才调用saveMediaRecord
															saveMediaRecord(values);
														}

														// 所有记录处理完成，显示完成提示
														setTimeout(() => {
															uni.hideLoading();
															uni.showToast({ title: `下载完成`, icon: 'success' });
															if (callback != null) {
																callback();
															}
														}, 500);
													};

													// 开始处理所有记录
													processAllRecords();
												}
											} else {
												console.log('保存媒体信息成功，但未获取到主键ID');
											}
										})
									}
								}
							});
							resolve(true);
						} else {
							uni.hideLoading();
							uni.showToast({ title: '未获取到数据', icon: 'error' });
							resolve(false);
						}
					} else {
						const errorMsg = singleObject.msg != null ? singleObject.msg : '未知错误';
						uni.hideLoading();
						uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
						resolve(false);
					}
				},
				fail: (err) => {
					console.error('请求数据失败:', err);
					uni.hideLoading();
					uni.showToast({ title: `请求失败: ${err.errMsg}`, icon: 'error' });
					resolve(false);
				}
			});
		});
	} catch (error) {
		console.error(error);
		uni.showToast({ title: '下载失败，请重试', icon: 'error' });
		uni.hideLoading();
		return false;
	}
}


//声像任务上传
export const uploadDataToAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {

	try {
		//暂定需要上传的数据文件
		//const infoJson = await getLatestRecord(productCode, null);
		const apiToken = await getTokenFromApi();
		if (apiToken == null || apiToken == '') {
			uni.hideLoading();
			uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
			return false
		}


		getJoinList('app_media_record as r', 'app_media_info as i', 'r.*,i.productno', 'r.pid=i.pdid', 'i.productno', productCode, null).then(async (res : UTSJSONObject) => {
			let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
			console.log(dataList);
			if (dataList != null && dataList.length > 0) {
				let doneRecordList = dataList.filter(item => item.getString("status") == '3')
				console.log(doneRecordList);
				if (doneRecordList.length === 0) {
					uni.showToast({ title: '上传图片数据为空', icon: 'error' });
					return;
				}
				let processStep = 1;
				for (let index = 0; index < dataList.length; index++) {
					const record = dataList[index];

					if (record.getString('urlpdt') == '' || record.getString('urlpdt') == null
						|| record.getString('pk') == '' || record.getString('pk') == null) {
						continue
					}
					showProgress(processStep, '上传');
					//文件上传
					let urlpdtStr = record.getString('urlpdt')
					let pk = record.getString('pk')
					let urlArr = urlpdtStr?.split(",") ?? []
					
					for (let j = 0; j < urlArr.length; j++) {
						let path = urlArr[j];
						const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
						console.log(`开始上传文件: ${fullFilePath}, 索引: ${j}, apiToken: ${apiToken}, billid: ${pk}`);
						await new Promise<void>((resolve, reject) => {
							// 使用uni.uploadFile进行文件上传
							uni.uploadFile({
								url: `${globalConfig.uploadURL}`,
								filePath: fullFilePath,
								name: 'file', // 文件参数名
								header: {
									'token': apiToken
								},
								formData: {
									'billid': pk
								},
								success: (uploadRes) => {
									if (uploadRes.statusCode === 200) {
										console.log(`文件${path}上传成功`, uploadRes);
										// 解析响应数据
										const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
										console.log(resData)
										if (resData?.['_id'] != null && resData?.['_id'] != '') {
											setTimeout(() => {
												resolve();
											}, 3000);
										} else {
											setTimeout(() => {
												reject('');
											}, 500);
										}
									}
								},
								fail: (err) => {
									console.error(`文件${path}上传失败`, err);
									uni.showToast({
										title: `文件${j}上传失败: ${err.errMsg != null ? err.errMsg : '网络错误'}`,
										icon: 'error'
									});
									setTimeout(() => {
										reject(err); // 在fail回调中调用reject
									}, 500);
								},
								complete: () => {
									console.log(`文件${path}上传完成`);
								}
							});
						}).catch(err => {
							// 捕获上传失败的错误，但继续上传下一个文件
							console.log(`当前文件上传失败，但继续下一个文件上传,异常 ${err}`);
						});
					}
					processStep++;
				}

			}
		})
	} catch (error) {
		console.error(error);
		// uni.showToast({ title: '上传失败，请重试', icon: 'error' });
		uni.hideLoading();
		return false;
	}
	
	uni.hideLoading();
	return true;
}