<template>
	<view>
		<canvas v-if="imgList.imgWidth" canvas-id="myCanvas"
			:style="`width:${imgList.imgWidth}px;height:${imgList.imgHeight}px;`"></canvas>
	</view>
</template>

<script>
	import {
		pathToBase64,
		base64ToPath
	} from '@/utils/imgPachToBase64/index.js'
	import {
		handleAuthLocation
	} from "@/common/permissionTips"
	export default {
		data() {
			return {
				imgUrl: '',
				date: '', //现在时间
				locationInfo: '--',
				weatherInfo: '--', //天气
				adressDetail: '--', //地址
				url: '',
				systemInfo: {},
			}
		},
		props: ['imgList'],
		watch: {

		},
		mounted() {
			console.log("啦啦啦啦啦", this.imgList)
			var that = this;
			uni.getSystemInfo({
				success(res) {
					that.systemInfo = res;
					console.log(111222, res)
				}
			})
			this.date = this.dateFormat(new Date().toISOString())
			this.loadWeather();
		
		},
		methods: {
			//获取天气温度等信息
			loadWeather() {
				let that = this
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					isHighAccuracy: "true",
					accuracy: "best", // 精度值为20m
					success: function(res) {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						var location = res.longitude + ',' + res.latitude
						// var location = '113.804826,22676933'
						console.log("location", location)
						uni.request({
							url: "https://restapi.amap.com/v3/geocode/regeo",
							data: {
								key: "56c91fb2683e5bf0f46014ac200d4c1b",
								location: location
							},
							method: "GET",
							success(res) {
								console.log("地址", res)
								if (res.data.status == "1") {
									//总地址
									var one = res.data.regeocode.formatted_address;
									that.locationInfo = one;
									if (one) {
										that.adressDetail = one.substr(3, 3) + one.substr(9, 4) + one
											.substr(20, 7)
									}
									var city = res.data.regeocode.addressComponent.city
									console.log("地址", that.adressDetail)
									uni.request({
										url: "http://restapi.amap.com/v3/weather/weatherInfo",
										data: {
											key: "56c91fb2683e5bf0f46014ac200d4c1b",
											city: city,
											extensions: "base",
											output: "JSON",
										},
										method: "GET",
										success(res) {
											if (res.data.status == "1") {
												that.weatherInfo = res.data.lives[0].weather
												console.log("成功获取天气地址")
												that.canversImg();
											}
										}
									})
								}
							}
						})
					},
					fail: function(msg) {
						console.log("获取位置失败", msg)
						handleAuthLocation('需要获取当前位置用于展示天气，请允许此App获取此设备的位置信息!')
					}
				});
			},
			drawMultilineText(ctx, text, x, y, lineHeight) {
				const lines = text.split('\n');
				lines.forEach((line, index) => {
					ctx.fillText(line, x, y + index * lineHeight);
				});
			},
			canversImg() {
				uni.showLoading({
					title: '正在合成中'
				})
				let that = this;
				console.log('我开始画啦 ：' + JSON.stringify(that.imgList))
				console.log(that.systemInfo)
				const ctx = uni.createCanvasContext('myCanvas', that); //获取一个画布对象
				ctx.drawImage(that.imgList.imgUrl, 0, 0, that.imgList.imgWidth, that.imgList
					.imgHeight); //画一个图片底图（路径，位置，大小）
				if(that.imgList.imgWidth > that.imgList.imgHeight){
					ctx.drawImage(require('@/static/CanvarsImg.png'), that.imgList.imgWidth * 0.52, that.imgList
						.imgHeight *
						0.72, that.imgList.imgWidth * 0.5, that.imgList.imgHeight * 0.22); //画一个图片底图（路径，位置，大小）
						ctx.setFontSize(25); // 文字字号
				} else if(that.imgList.imgHeight / that.imgList.imgWidth < 2) {
					ctx.drawImage(require('@/static/CanvarsImg.png'), that.imgList.imgWidth * 0.52, that.imgList
						.imgHeight *
						0.72, that.imgList.imgWidth * 0.5, that.imgList.imgHeight * 0.2); //画一个图片底图（路径，位置，大小）
						ctx.setFontSize(25); // 文字字号
				} else if(that.imgList.imgHeight / that.imgList.imgWidth < 2.2) {
					ctx.drawImage(require('@/static/CanvarsImg.png'), that.imgList.imgWidth * 0.52, that.imgList
						.imgHeight *
						0.74, that.imgList.imgWidth * 0.5, that.imgList.imgHeight * 0.16); //画一个图片底图（路径，位置，大小）
						ctx.setFontSize(25); // 文字字号
				} else {
					ctx.drawImage(require('@/static/CanvarsImg.png'), that.imgList.imgWidth * 0.52, that.imgList
						.imgHeight *
						0.74, that.imgList.imgWidth * 0.5, that.imgList.imgHeight * 0.16); //画一个图片底图（路径，位置，大小）
						ctx.setFontSize(17); // 文字字号
				}
				ctx.setFillStyle('#FFFFFF'); // 文字颜色
				ctx.setFillStyle('#000000'); // 文字颜色
				ctx.fillText('天   气：' + that.weatherInfo, that.imgList.imgWidth * 0.56, that.imgList
					.imgHeight *
					0.8); // 绘制文字
				ctx.fillText('拍摄时间：' + that.date, that.imgList.imgWidth * 0.56, that.imgList.imgHeight *
					0.83); // 绘制文字
				// ctx.fillText('地点：' + that.adressDetail, that.imgList.imgWidth * 0.56, that.imgList
				// 	.imgHeight *
				// 	0.88); // 绘制文字
				const insertIntervalString = (originStr, disNum = 10, insertStr = "\n") => originStr.replace(new RegExp("(.{" + disNum + "})", "g"), "$1" + insertStr);
				that.drawMultilineText(ctx, insertIntervalString('地点：' + that.locationInfo, 18), that.imgList.imgWidth * 0.56, that.imgList.imgHeight *
					0.86, 40);
				// ctx.fillText('拍摄人：' + that.imgList.shooter, that.imgList.imgWidth * 0.56, that.imgList
				// 	.imgHeight *
				// 	0.92); // 绘制文字
				console.log('canvs画布返回的地址：---', that.locationInfo);
				ctx.draw(false, () => {
					// canvas画布转成图片并返回图片地址
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						width: that.imgList.imgWidth,
						height: that.imgList.imgHeight,
						destWidth: that.imgList.imgWidth,
						destHeight: that.imgList.imgHeight,
						// quality: 0.1,
						fileType: 'png',
						success: res => {
							console.log("成功啦返回的地址", res.tempFilePath)
							this.photosBtn(res.tempFilePath)
							that.imgUrl = res.tempFilePath;
							that.showShareImg = true;
							uni.showToast({
								title: '绘制成功'
							});
							uni.hideLoading()

						},
						fail: err => {
							uni.showToast({
								title: '绘制失败'
							});
						},
						complete: () => {
							uni.hideLoading();
							uni.hideToast();
							uni.hideLoading()

						}
					}, );
				});
			},
			photosBtn(url) {
				let that = this
				pathToBase64(url).then(data => {
					// console.log('转换后的base64格式的图片', data); //data为base64格式的图片
					that.$emit('imgUrl', {
						imageBase64: data,
						imgUrl: that.imgUrl,
					})
					that.imgList.imgWidth = null
				})
			},
			dateFormat(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "年" + month + "月" + day + "日" + hours + ":" + minutes + ":" + seconds;
				// return year + "-" + month + "-" + day;
			},
		}
	}
</script>

<style>
</style>