<template>
	<view>
		<image class="background" src="/static/homepages/homes/ai_recognize_plan/pictures/background.png"></image>
		<image class="back_button" src="/static/homepages/homes/ai_recognize_plan/pictures/button.png"></image>
		<image v-if="planImage" class="plan-image" :src="planImage"></image>
		<image class="generate_button" @click="generate()" src="/static/homepages/homes/ai_recognize_plan/pictures/generate.png"></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				planImage: null // 用于存储图片的本地路径
			};
		},
		methods: {
			generate() {
				uni.request({
					url: app.globalData.fit_journey_ai_address+`/ai/plan`, // 请替换为实际的后端接口URL
					method: 'GET',
					success: (res) => {
						if (res.data && res.data.base64) {
							this.saveBase64Image(res.data.base64);
						}
					}
				});
			},
			saveBase64Image(base64Data) {
				// 创建文件系统对象
				plus.io.resolveLocalFileSystemURL(plus.io.convertLocalFileSystemURL('_doc/'), (entry) => {
					// 生成文件名
					const fileName = `_doc/${new Date().getTime()}.png`;
					// 创建文件
					entry.getFile(fileName, {create: true}, (fileEntry) => {
						// 将base64转换为Blob对象
						const arr = base64Data.split(',');
						const mime = arr[0].match(/:(.*?);/)[1];
						const bstr = atob(arr[1]);
						let n = bstr.length;
						const u8arr = new Uint8Array(n);
						while (n--) {
							u8arr[n] = bstr.charCodeAt(n);
						}
						const blob = new Blob([u8arr], {type: mime});
						// 写入文件
						fileEntry.createWriter((fileWriter) => {
							fileWriter.write(blob);
							// 更新图片路径
							this.planImage = plus.io.convertLocalFileSystemURL(fileName);
						}, (e) => {
							console.log("Write file failed: " + e.message);
						});
					}, (e) => {
						console.log("Get file failed: " + e.message);
					});
				}, (e) => {
					console.log("Resolve file system failed: " + e.message);
				});
			}
		}
	}
</script>

<style lang="scss">
	.background {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0%;
		left: 0%;
	}
	.back_button {
		position: absolute;
		width: 3%;
		height: 3%;
		top: 4%;
		left: 7%;
	}
	.generate_button {
		position: absolute;
		width: 70%;
		height: 12%;
		top: 85%;
		left: 14%;
	}
	.plan-image {
		position: absolute;
		width: 80%; // 根据实际需要调整宽度
		height: auto; // 高度自适应
		top: 50%; // 根据实际需要调整垂直位置
		left: 50%; // 水平居中
		transform: translate(-50%, -50%); // 使用transform进行居中
		z-index: 10; // 确保图片显示在最顶层
	}
</style>