import { UPLOAD_URL } from '@/settings/siteSetting.js';
import { useUserStore } from '@/store/user.js';
const userStore = useUserStore();

/**
 * type  // image / video / file
 * opts {
	dir  上传路径
	filePath 文件资源
	count // 默认 1 
 }
**/

let APIURLSET = uni.getStorageSync('APIURL')
let APIURL = UPLOAD_URL
if (APIURLSET) APIURL = `${String(APIURLSET).replace(/\/$/, '')}/file/upload`;

export function chooseAndUploadFile(type, opts, dir = '') {
	if (type === 'image') {
		chooseImage({
			dir,
			...opts
		});
	} else if (type === 'video') {
		chooseVideo({
			dir,
			...opts
		});
	} else if (type === 'audio' || type === 'voice') {
		chooseAudio({
			dir,
			...opts
		});
	} else {
		chooseFile({
			dir,
			...opts
		});
	}
}

// 选择图片
function chooseImage(opts = {}) {
	const { count = 1, sizeType = ['original'], sourceType = ['album', 'camera'], extension = ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'], callBack } = opts;
	uni.chooseImage({
		count,
		sizeType,
		extension,
		sourceType,
		success: async (res) => {
			console.log('chooseImage res res', res);
			const tempFiles = res.tempFiles;
			const file = await batchUploadFile({
				files: tempFiles,
				...opts
			});
			console.log('file', file);
			callBack && callBack(file);
		},
		fail: (err) => {
			console.log('chooseImage-fail', err);
		}
	});
}

// 选择文件
function chooseFile(opts = {}) {
	const { count = 1 } = opts;
	wx.chooseMessageFile({
		type: 'file',
		count,
		success: async (res) => {
			const { tempFiles } = res;
			const file = await batchUploadFile({
				files: tempFiles,
				...opts
			});
			console.log('file', file);
		},
		fail(error) {
			console.log('fail', error);
		}
	});
}

// 选择视频
function chooseVideo(opts = {}) {
	const { sourceType, callBack, dir, compressed = false, isVideo = false } = opts;
	// console.log('compressed', compressed);
	uni.chooseVideo({
		sourceType,
		compressed,
		success: async (res) => {
			const { size, tempFilePath } = res;
			let videoMaxSize = 300;
			if (userStore.getDefaultConfig) videoMaxSize = userStore.getDefaultConfig.videoMaxSize;
			// console.log('232333', videoMaxSize, size, userStore.getDefaultConfig);
			if (size > 1024 * 1024 * videoMaxSize) {
				uni.showModal({
					title: `视频需要${videoMaxSize}M以内`,
					success: (res) => {}
				});
				return;
			}
			const url = await uploadFile({
				dir,
				filePath: tempFilePath,
				isVideo,
				size: size ? (size / 1024 / 1024).toFixed(2) : 0
			});
			uni.setStorageSync('videoUrlUp', tempFilePath);
			callBack && callBack(url);

			// uni.compressVideo({
			// 	src: res.tempFilePath,
			// 	quality: 'high',
			// 	success: async (ress) => {
			// 		// 压缩成功
			// 		console.log('压缩成功', ress);
			// 		const { size, tempFilePath } = ress;
			// 		const url = await uploadFile({
			// 			dir,
			// 			filePath: tempFilePath
			// 		});
			// 		callBack && callBack(url);
			// 	},
			// 	fail: async (err) => {
			// 		// 压缩失败
			// 		console.log('压缩失败', err);
			// 		const { size, tempFilePath } = res;
			// 		const url = await uploadFile({
			// 			dir,
			// 			filePath: tempFilePath
			// 		});
			// 		callBack && callBack(url);
			// 	}
			// });
			// console.log('chooseVideo res res', res);
		},
		fail: (err) => {
			console.log('chooseVideo-fail', err);
		}
	});
}

// 选择音频
function chooseAudio(opts = {}) {
	const { dir, callBack } = opts;
	wx.chooseMessageFile({
		count: 1,
		type: 'file',
		extension: ['mp3', 'wav', 'aac', 'ogg', 'wma', 'alac', 'amr', 'm4a'],
		success: async (res) => {
			console.log('chooseAudio res res', res.tempFiles[0].path);
			if (
				res.tempFiles[0].path.indexOf('.mp3') == -1 &&
				res.tempFiles[0].path.indexOf('.m4a') == -1 &&
				res.tempFiles[0].path.indexOf('.wav') == -1 &&
				res.tempFiles[0].path.indexOf('.MP3') == -1 &&
				res.tempFiles[0].path.indexOf('.M4A') == -1 &&
				res.tempFiles[0].path.indexOf('.WAV') == -1 &&
				res.tempFiles[0].path.indexOf('.aac') == -1 &&
				res.tempFiles[0].path.indexOf('.AAC') == -1 &&
				res.tempFiles[0].path.indexOf('.ogg') == -1 &&
				res.tempFiles[0].path.indexOf('.OGG') == -1 &&
				res.tempFiles[0].path.indexOf('.wma') == -1 &&
				res.tempFiles[0].path.indexOf('.WMA') == -1 &&
				res.tempFiles[0].path.indexOf('.alac') == -1 &&
				res.tempFiles[0].path.indexOf('.ALAC') == -1 &&
				res.tempFiles[0].path.indexOf('.amr') == -1 &&
				res.tempFiles[0].path.indexOf('.AMR') == -1
			) {
				uni.showToast({
					title: '音频格式只能是mp3/m4a/wav',
					icon: 'none'
				});
				return;
			}

			const { tempFiles } = res;
			// if (tempFiles[0].size / 1024 / 1024 > 35) {
			// 	uni.showToast({ icon: 'none', mask: true, title: '音频需要35M以内' });
			// 	return;
			// }
			const url = await uploadFile({
				dir,
				filePath: tempFiles[0].path,
				size: tempFiles[0].size ? (tempFiles[0].size / 1024 / 1024).toFixed(2) : 0
			});
			callBack && callBack(url);
		},
		fail: (err) => {
			console.log('chooseAudio-fail', err);
		}
	});
}

// 上传之前
function beforeUnload(files) {
	return new Promise(async (resolve, reject) => {
		const filesSize = files.map((x) => x.size / 1024 / 1024);
		const isExceed = filesSize.some((x) => x > 8);
		if (isExceed && files.length === 1) {
			uni.showToast({ icon: 'none', mask: true, title: '文件需要8M以内' });
		} else if (isExceed && files.length > 1) {
			files = files.filter((x) => x.size / 1024 / 1024 < 8);
			uni.showModal({
				title: '提示',
				content: '部分文件超过8M 已过滤，是否继续上传',
				confirmText: '继续上传',
				success: (res) => {
					if (res.confirm) {
						resolve(files);
					}
				}
			});
		} else {
			resolve(files);
		}
	});
}

// 批量上传
export const batchUploadFile = async (opts = {}) => {
	const { dir = '', files } = opts;
	const fileFilter = await beforeUnload(files);
	let index = 0,
		filesLength = fileFilter.length,
		urls = [],
		errorArr = [];

	return new Promise(async (resolve, reject) => {
		let header = {
			'Content-Type': 'application/json;charset=UTF-8',
			userId: userStore.getSiteId,
			Authorization: userStore.getToken
		};
		uni.showLoading({ mask: true, title: '上传中' });
		let str = dir ? '?typeId=' + dir : '';
		const startUpload = () => {
			return new Promise((resolve, reject) => {
				let start = () => {
					uni.uploadFile({
						url: APIURL + str,
						name: 'file',
						header,
						timeout: 1000 * 60 * 5,
						filePath: fileFilter[index].path,
						success: (res) => {
							console.log('uploadFile res', res);
							if (res.statusCode === 200) {
								const { data } = res;
								const jsonData = JSON.parse(data);
								console.log('jsonData', jsonData);
								if (jsonData.code == -3){
									uni.hideLoading()
									uni.showModal({
										title: '请先登录',
										success: (res) => {
											if (res.confirm) {
												uni.redirectTo({
													url: '/pages/index/index'
												});
											}
										},
									});
									return
								}
								if (jsonData.count === 0) {
									const { relativePath } = jsonData.data;
									urls.push(relativePath);
									index++;

									if (index >= filesLength) {
										resolve(true);
									} else {
										setTimeout(() => {
											start();
										}, 200);
									}
								} else {
									index++;
								}
							} else {
								index++;
								setTimeout(() => {
									uni.showModal({
										title: '上传失败',
										success: (res) => {}
									});
								}, 500);
							}
						}
					});
				};
				start();
			});
		};

		const flag = await startUpload();
		if (flag) {
			uni.hideLoading();
			// setTimeout(() => {
			// 	uni.showModal({
			// 		title: '上传失败',
			// 		success: (res) => {}
			// 	});
			// }, 500);
			resolve(urls);
		} else {
			reject(null);
		}
	});
};

// 上传
export const uploadFile = (params = {}) => {
	const { dir = '', filePath, isVideo, size = '' } = params;
	let header = {
		'Content-Type': 'application/json;charset=UTF-8',
		userId: userStore.getSiteId,
		Authorization: userStore.getToken
	};

	let sizeMsg = size ? `当前文件大小${size}M` : '';

	return new Promise((resolve, reject) => {
		if (!isVideo) uni.showLoading({ mask: true, title: '上传中' });
		let str = dir ? '?typeId=' + dir : '';
		let uploadTask = uni.uploadFile({
			url: APIURL + str,
			name: 'file',
			filePath,
			header,
			timeout: 1000 * 60 * 10,
			success: (res) => {
				if (res.statusCode === 200) {
					const { data } = res;
					const jsonData = JSON.parse(data);
					console.log('uploadFile.jsonData', jsonData);
					if (jsonData.code == 1) {
						const { relativePath } = jsonData.data;
						resolve(relativePath);
					} else {
						uni.showModal({
							title: jsonData.msg,
							success: (res) => {}
						});
						reject(new Error(jsonData.msg || '上传失败'));
					}
				} else {
					setTimeout(() => {
						uni.showModal({
							title: `接口错误！请重新上传！${sizeMsg}`,
							success: (res) => {}
						});
					}, 500);
					reject(new Error('接口错误'));
				}
			},
			fail: (err) => {
				setTimeout(() => {
					uni.showModal({
						title: `上传超时 ${sizeMsg}`,
						success: (res) => {}
					});
				}, 500);
				reject(err || new Error('上传失败'));
			},
			complete: () => {
				uni.hideLoading();
			}
		});

		uploadTask.onProgressUpdate((res) => {
			let progressText = '上传进度：' + res.progress + '%';
			if (res.progress === 100) {
				progressText = '上传完成';
				setTimeout(() => {
					progressText = '';
				}, 1500);
			}
			if (isVideo) {
				userStore.setUploadProgress(progressText);
			} else {
				uni.showLoading({ mask: true, title: progressText });
			}
		});
	});
};
