import {
	uploadImg,
	userMobileOperation,
	getUserInfoName,
	getWaterMark
} from '../api/apiList';
const getUserLocation = require('../mixins/getUserLocation')
import {
	formatGMT
} from "../utils/util.js";
import AMap from "../utils/AMapUtil.js"
import compress from '../utils/compress'
module.exports = {
	data() {
		return {
			fileList: [], //文件列表
			fileDetailList: [], //文件列表, 含文件名等
			isIos: false,
			userInfo: {},
			locationInfo: {},
			isShowWaterMark: false,
			fileListPromise: [],
			width: uni.getSystemInfoSync().windowWidth,
			height: uni.getSystemInfoSync().windowHeight
		};
	},
	//引入地址混入
	mixins: [getUserLocation],
	created() {
		this.getSiteName();
		this.judgeAddWaterMark();
		this.getUserInfo();
		// #ifdef H5
		const platform = uni.getSystemInfoSync().platform
		if (platform === 'ios') {
			// this.isIos = true
		}
		// #endif
	},
	//事件处理函数
	methods: {
		//图片上传 IOS兼容
		onUpLoad() {
			if (this.$jwx) {
				const _this = this
				const sourceType = this.isIos ? ['album'] : ['album', 'camera'] // 可以指定来源是相册还是相机, ios指定为仅相册
				this.$jwx.chooseImage({
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: sourceType,
					success: function(res) {
						_this.onConvert(res.localIds)
					}
				})
			}
		},
		async onConvert(localIds) {
			for (var i = 0; i < localIds.length; i++) {
				await this.onReadImage(localIds[i]);
			}
		},
		onReadImage(localId) {
			const _this = this
			return new Promise((resolve, reject) => {
				_this.$jwx.getLocalImgData({
					localId: localId, // 图片的localID
					success: function(res) {
						const localData = res.localData
						_this.fileList = _this.fileList.concat(localData)
						setTimeout(()=>	resolve('done!'),0)
					}
				});
			})
		},

		//上传图片
		uploadImage(callback) {
			let {
				fileList
			} = this;
			if (!fileList.length && !this.required) return callback('');
			if (!fileList.length) {
				uni.showToast({
					title: `请选择${this.uploadTitle}`,
					icon: 'error',
					duration: 3000
				});
				return;
			}
			let images = [];
			fileList.forEach(item => {
				// const file = this.fileDetailList.find(file => file.url === item)
				// uploadImg(item, file.type).then(res => { //微信小程序仅支持单文件上传,传多个文件需要反复调用本API。所以跨端的写法就是循环调用本API。
				uploadImg(item).then(res => {

					uni.hideLoading();
					console.log('res',res)
					let data = JSON.parse(res).data;
					images.push(data.path);
					if (images.length === fileList.length) {
						return callback(images.join('|'));
					}
				})
			});
		},

		//上传图片
		async uploadImageSync() {
			let {
				fileList
			} = this;
			if (!fileList.length && !this.required) return "";
			if (!fileList.length) {
				uni.showToast({
					title: '请上传图片',
					icon: 'error',
					duration: 3000
				});
				return;
			}
			let images = "";
			for (const imageFile of fileList) {
				const file = this.fileDetailList.find(file => file.url === imageFile)
				const res = await uploadImg(imageFile, file.type)
				uni.hideLoading();
				let data = JSON.parse(res).data;
				if (images === "") {
					images = data.path
				} else {
					images = images + "|" + data.path
				}
			}
			return images
		},

		// 上传文件回调
		async uploadAfterRead(info) {
			let {
				file
			} = info;
			this.fileDetailList = [...this.fileDetailList, ...file];
			//判断是否需要添加水印
			// if (this.isShowWaterMark) {
			if (this.isShowWaterMark) {
				console.log(1, "123abc-tang")
				let fileList = []
				for (let i = 0; i < file.length; i++) {
					const res = await this.addWatermark(file[i].url);
					fileList.push(res)
				}
				this.fileList = [...this.fileList,...fileList]
				// Promise.all(fileList).then((val) => {
				// 	console.log('结果',val)
				// 	this.fileList = val
				// })


				// // for循环在浏览器中会很慢
				// for(let i=0;i<file.length;i++){
				// 	const res = await this.addWatermark(file[i].url);
				// 	this.fileList = [...this.fileList, res];
				// }
				// // file.map(async (item) =>{
				// // 	const res =await this.addWatermark(item.url);
				// // 	this.fileList = [...this.fileList, res]
				// // 	console.log(111333,this.fileList)
				// // 	// this.fileListPromise=[...this.fileListPromise, this.addWatermark(item.url)]
				// // })
				// // Promise.all([...this.fileListPromise]).then(val=>{
				// // 	this.fileList = val
				// // })
			} else {
				const newFile = file.map(item => item.url);
				this.fileList = [...this.fileList, ...newFile];
			}
		},

		// 预览图片回调
		previewImage(e) {
			let {
				index
			} = e.currentTarget.dataset;
			uni.previewImage({
				current: index,
				urls: this.fileList
			})
		},

		// 删除当前选中文件
		deleteFile(index) {
			uni.showModal({
				title: '删除提示',
				content: '是否确认删除？',
				success: (res) => {
					if (res.confirm) {
						this.fileList = this.fileList.filter((item, idx) => idx !== index)
						this.fileDetailList = this.fileDetailList.filter((item, idx) => idx !== index)
					} else if (res.cancel) {}
				}
			});
		},
		//获取用户信息
		getUserInfo() {
			userMobileOperation('getUserInfo').then(res => {
				let data = res.data.data
				data.mobile = data.userExt.mobile || '暂无'
				this.userInfo = {
					...data
				}
			})
		},

		//是否添加水印
		judgeAddWaterMark() {
			getWaterMark().then(({
				data: res
			}) => {
				this.isShowWaterMark = res.data.preference["client.add.photo.watermark"];
			})
		},

		// //绘画水印
		// drawWaterMark(ctx,multiple=1){
		// 	const markDate = formatGMT(this.locationInfo.time,"D");
		// 	const markTime = formatGMT(this.locationInfo.time,"H")?.slice(0,5);
		// 	const arr = ["日","一","二","三","四","五","六"];
		// 	let address="";
		// 	this.locationInfo.address?.split("").forEach((item,index)=>{
		// 		if(index===12||index===30){
		// 			address+="\n";
		// 		}
		// 		address+=item;
		// 	})
		// 	console.log(address);
		// 	const week = `星期${arr[new Date(this.locationInfo.time)?.getDay()]}`;
		// 	const waterMarkInfo=`${markTime}\n${markDate}\n${week}\n地点：${address}\n司机名：${this.userInfo.userExt.driverName}`.split('\n');
		// 	ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
		// 	const x = 15*multiple; // 水印左上角 x 坐标
		// 	let y =	50*multiple; // 水印左上角 y 坐标
		// 	const lines = waterMarkInfo;
		// 	// 添加水印图标
		// 	// const lineHeight = 80; // 水印文字行高
		// 	ctx.font = `${40*multiple}px arial`;
		// 	ctx.fillText(lines[0], x, y);
		// 	// 绘制竖线
		// 	ctx.strokeStyle = 'yellow'; // 设置线条颜色为白色
		// 	ctx.lineWidth = 4*multiple; // 设置线条宽度
		// 	ctx.beginPath(); // 开始路径
		// 	ctx.moveTo(x + multiple*107, y - multiple*30); // 移动到起点坐标 (x, y)
		// 	ctx.lineTo(x + multiple*107, y); // 画一条竖线到终点坐标 (x, y)
		// 	ctx.stroke();
		// 	ctx.font = '15px arial';
		// 	ctx.fillText(lines[1], x + multiple*120, y - multiple*20);
		// 	ctx.fillText(lines[2], x + multiple*120, y);
		// 	y += multiple*25;
		// 	const lineHeight = multiple*25;
		// 	lines.forEach((line,index) => {
		// 		if(index>=3){
		// 			ctx.font = `${14*multiple}px arial`;
		// 			ctx.fillText(line, x, y);
		// 			y += lineHeight;
		// 		}
		// 	});
		// },

		//添加水印
		addWatermark(fileUrl) {
			let that = this;
			const markDate = formatGMT(this.locationInfo.time, "D");
			const markTime = formatGMT(this.locationInfo.time, "H")?.slice(0, 5);
			const arr = ["日", "一", "二", "三", "四", "五", "六"];
			let address = "";
			this.locationInfo.address?.split("").forEach((item, index) => {
				if (index === 12 || index === 30) {
					address += "\n";
				}
				address += item;
			})
			console.log('ssss',address);
			const week = `星期${arr[new Date(this.locationInfo.time)?.getDay()]}`;
			const waterMarkInfo =
				`${markTime}\n${markDate}\n${week}\n地点：${address}\n司机名：${this.userInfo.userExt.driverName}`.split(
					'\n');
			let platform = uni.getSystemInfoSync().platform;

			return new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: fileUrl,
					fail: (error) => {}, // 替换为你的图片路径
					success: async (res) => {
						let imageWidth = res.width;
						let imageHeight = res.height;
						// #ifdef H5
						const ctx = uni.createCanvasContext('upload-canvas', that);
						//计算图片比例
						const pw = imageWidth >= uni.getSystemInfoSync().windowWidth ? uni
							.getSystemInfoSync().windowWidth / imageWidth : imageWidth / uni
							.getSystemInfoSync().windowWidth;
						const py = imageHeight >= uni.getSystemInfoSync().windowHeight ? uni
							.getSystemInfoSync().windowHeight / imageHeight : imageHeight / uni
							.getSystemInfoSync().windowHeight;
						const p = pw >= py ? py : pw;
						const drawX = pw >= py ? uni.getSystemInfoSync().windowWidth -
							imageWidth * p : 0;
						const drawY = pw <= py ? uni.getSystemInfoSync().windowHeight -
							imageHeight * p : 0;
						ctx.drawImage(res.path, drawX / 2, drawY / 2, imageWidth * p,
							imageHeight * p);
						const multiple = 0.5;
						ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
						const x = 15 * multiple + drawX / 2; // 水印左上角 x 坐标
						let y = 50 * multiple + drawY / 2; // 水印左上角 y 坐标
						const lines = waterMarkInfo;
						// 添加水印图标
						// const lineHeight = 80; // 水印文字行高
						ctx.setFontSize(40 * multiple);
						ctx.fillText(lines[0], x, y);
						// 绘制竖线
						ctx.strokeStyle = 'yellow'; // 设置线条颜色为白色
						ctx.lineWidth = 4 * multiple; // 设置线条宽度
						ctx.beginPath(); // 开始路径
						ctx.moveTo(x + multiple * 107, y - multiple * 30); // 移动到起点坐标 (x, y)
						ctx.lineTo(x + multiple * 107, y); // 画一条竖线到终点坐标 (x, y)
						ctx.stroke();
						ctx.setFontSize(15 * multiple);
						ctx.fillText(lines[1], x + multiple * 120, y - multiple * 20);
						ctx.fillText(lines[2], x + multiple * 120, y);
						y += multiple * 25;
						const lineHeight = multiple * 25;
						lines.forEach((line, index) => {
							if (index >= 3) {
								ctx.setFontSize(14 * multiple);
								ctx.fillText(line, x, y);
								y += lineHeight;
							}
						});
						console.log("开始画",ctx)
						ctx.draw(false, () => {
							console.log("进来了")
							uni.canvasToTempFilePath({
								canvasId: "upload-canvas",
								success: (res) => {
									// resolve(res.tempFilePath)
									let arr = res.tempFilePath.split(','),
										mime = arr[0].match(/:(.*?);/)[1],
										bstr = atob(arr[1]),
										n = bstr.length,
										u8arr = new Uint8Array(n);
									while (n--) {
										u8arr[n] = bstr.charCodeAt(n);
									}
									const blob = new Blob([u8arr], {
										type: mime
									});
									const blobUrl = URL.createObjectURL(
										blob);
									setTimeout(() => resolve(blobUrl),0)
								},
								fail: (error) => {
									debugger
									console.error('Failed to save canvas:',
										error);
								}
							}, this);
						});
						// #endif


						// #ifdef MP-WEIXIN
						console.log(2, "123abc-tang")
						let filePath = res?.path;
						// 获取文件系统管理器
						let canvas = wx.createOffscreenCanvas({
							type: '2d',
							width: imageWidth,
							height: imageHeight
						})
						let img = canvas.createImage(); // 注意是使用canvas实例 不是ctx
						// 等待图片加载
						await new Promise(resolve => {
							img.onload = resolve
							img.src = filePath; // 要加载的图片 url
						})
						canvas.width = imageWidth;
						canvas.height = imageHeight;
						const ctx = canvas.getContext('2d')
						ctx.drawImage(img, 0, 0, imageWidth, imageHeight);
						const multiple = 2;
						ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
						const x = 15 * multiple; // 水印左上角 x 坐标
						let y = 50 * multiple; // 水印左上角 y 坐标
						const lines = waterMarkInfo;
						// 添加水印图标
						// const lineHeight = 80; // 水印文字行高
						ctx.font = `${40*multiple}px arial`;
						ctx.fillText(lines[0], x, y);
						// 绘制竖线
						ctx.strokeStyle = 'yellow'; // 设置线条颜色为白色
						ctx.lineWidth = 4 * multiple; // 设置线条宽度
						ctx.beginPath(); // 开始路径
						ctx.moveTo(x + multiple * 107, y - multiple * 30); // 移动到起点坐标 (x, y)
						ctx.lineTo(x + multiple * 107, y); // 画一条竖线到终点坐标 (x, y)
						ctx.stroke();
						ctx.font = `${15*multiple}px arial`;
						ctx.fillText(lines[1], x + multiple * 120, y - multiple * 20);
						ctx.fillText(lines[2], x + multiple * 120, y);
						y += multiple * 25;
						const lineHeight = multiple * 25;
						lines.forEach((line, index) => {
							if (index >= 3) {
								ctx.font = `${14*multiple}px arial`;
								ctx.fillText(line, x, y);
								y += lineHeight;
							}
						});
						// 保存Canvas绘制结果为临时文件
						let base64 = canvas.toDataURL("image/png", 0.8);
						const time = new Date().getTime();
						const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "upload" +
							".png";
						//如果图片字符串不含要清空的前缀,可以不执行下行代码.
						const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
						const fs = wx.getFileSystemManager();
						fs.writeFileSync(imgPath, imageData, "base64");
						fs.close()
						wx.getImageInfo({
							src: imgPath,
							success:  (res) => {
								console.log(3, "123abc-tang")
								
								
								setTimeout(async() =>{
									console.log("res.path",res.path)
									uni.getFileInfo({
										filePath:res.path,
										success:imgInfo=>{
											console.log("imgInfo.size",imgInfo.size)
										}
									})

								 resolve(res.path)},0)
							},
							fail: (res) => {
								console.log("读取写入的文件失败", res)
							}
						})
						// #endif
					}
				})
			})
		},
	}
};
