<template>
	<view class="page flex-col">
		<view class="title" :style="{'top': uniMenuInfo.top + 6 + 'px'}">照片展示</view>
		<view class="back" @tap="goBack()" :style="{'top' : uniMenuInfo.top - 12 + 'px'}"></view>
		<view class="content"  :style="{'top': uniMenuInfo.top + 50 + 'px'}" >
			<view v-if="wait">
				<view class="img_loading">
					<image src="https://humeng-res.oss-cn-beijing.aliyuncs.com/hm_aigc/applet/img_%E5%8A%A0%E8%BD%BD%402x.png" mode="aspectFit" class="img_1" />
				</view>
				<view class="loading">
					<text class="tip">请稍候，照片生成中...</text>
					<zero-loading type="atom" position="absolute"></zero-loading>
				</view>
				<!-- <view class="progressBar">
					<liu-progressbar :progress="jdt" color="#FFFFFF" :height="'25rpx'" :borderRadius="'40rpx'" />
				</view> -->
				<view class="wait_box">
					<text class="wait_1">当前第&nbsp;{{waitIdx}}&nbsp;位/共&nbsp;{{waitTotal}}&nbsp;位</text>
					<text class="wait_2">预计需要等候&nbsp;{{waitTime}}&nbsp;分钟</text>
				</view>
			</view>
			<view class="box_show" v-if="!wait">
				<image class="showImage" :src="showImage" mode="aspectFill" @tap="previewImage(showImage)"/>
				<view class="printTip" v-if="buyType == 2">{{ printScreenTip }}</view>
				<view class="upload-btn" @tap="saveImage()">保存到手机</view>
			</view>
		</view>
	</view>
</template>

<script>
	const getNowTime = require('../../utils/timeUtil/timeUtil.js')
	let pageNumber = 4;
	let startTime = '';
	let destroyTime = '';
	export default {
		data() {
			return {
				uniMenuInfo: {},
				wait: true,
				showImage: '',
				code: '',
				waitIdx: 0,
				waitTotal: 0,
				waitTime: 0,
				jdt: 0,
				templateId: 0,
				mchId: 0,
				downloading: false,
				buyType: 0,
				printCode: '',
				printScreenTip: ''
			}
		},
		onLoad(option) {
			var _this = this;
			uni.showLoading({
				title: '正在加载...',
				mask: true
			})
			this.uniMenuInfo = uni.getStorageSync('uniMenuInfo');
			this.code = option.code;
			this.templateId = Number(option.templateId);
			this.mchId = Number(option.mchId);
			this.buyType = Number(option.buyType);
			this.firstGetPhoto(_this.code);
			this.getPhoto(this.code);
		},
		onShow() {
			startTime = getNowTime();
		},
		onHide() {
			if(uni.getStorageSync('userInfo').id) {
				this.logRecord();
			}
		},
		onUnload() {
			if(uni.getStorageSync('userInfo').id) {
				this.logRecord();
			}
		},
		methods: {
			logRecord() {
				var _this = this;
				destroyTime = getNowTime();
				let reqData = {
					"startTime": startTime,
					"destroyTime": destroyTime,
					"pageNumber": pageNumber,
					"qrcodeScenicId": uni.getStorageSync('scanQrcodeInfo').scenicId,
					"qrcodeMchId": uni.getStorageSync('scanQrcodeInfo').mchId,
					"qrcodeId": uni.getStorageSync('scanQrcodeInfo').qrcodeId,
					"userId": uni.getStorageSync('userInfo').id,
					"appType": 5,
					"photoId": _this.templateId,
					"mchId": _this.mchId,
				};
				uni.request({
					url: _this.java_http_url + '/applet/smart_camera/logRecord',
					method: 'POST',
					data: reqData,
					success(res) {}
				})
			},
			uploadImage () {
				var _this = this;
				uni.getImageInfo({
					src: _this.showImage,
					success: function(image) {
						uni.saveImageToPhotosAlbum({
							filePath: image.path,
							success: function() {
								uni.showToast({
									title: '照片保存成功',
									icon: 'success',
									duration: 2000
								});
							},
							fail: (err) => {
								console.log(err)
							},
							complete: (env) => {
								uni.hideLoading()
								_this.downloading = false;
							}
						});
					},
					fail: (err) => {
						console.log('err', err)
						uni.hideLoading()
						_this.downloading = false;
					}
				});
			},
			saveImage() {
				var _this = this;
				if(!_this.downloading) {
					_this.downloading = true;
					uni.showLoading({
						title: '请稍候',
						mark: true
					})
					wx.getSetting({
					  success: (res) => {
					    if (!res.authSetting['scope.writePhotosAlbum']) {
					      // 用户未授权，需要请求授权
					      wx.authorize({
					        scope: 'scope.writePhotosAlbum',
					        success: () => {
					          // 用户已授权，可以进行保存图片操作
							  console.log('已授权')
							  _this.uploadImage();
					        },
					        fail: () => {
					          // 用户拒绝授权，需要引导用户去设置页面手动授权
							  uni.hideLoading()
							  _this.downloading = false;
					          wx.showModal({
					            title: '需要保存图片权限',
					            content: '请在设置中打开保存图片到相册权限',
					            success: (res) => {
					              if (res.confirm) {
					                // 用户点击确定，跳转到设置页面
					                wx.openSetting({
					                  success: (res) => {
					                    // 检查是否授权
					       //              if (res.authSetting['scope.writePhotosAlbum']) {
					       //                // 授权成功，可以进行保存图片操作
										  // _this.uploadImage();
					       //              }
					                  }
					                })
					              }
					            }
					          })
					        }
					      })
					    } else {
							_this.uploadImage();
						}
					  },
					  fail(err) {
					  	console.log(err)
						uni.showToast({
							title: '获取设置失败'
						})
						uni.hideLoading()
						_this.downloading = false;
					  }
					})
				}
			},
			getPhoto(code) {
				var _this = this;
				// 获取照片制作状态
				var stateInterval = setInterval(function() {
					uni.request({
						url: _this.java_http_url + '/applet/smart_camera/getSingleTemplateSynthesisPhoto',
						method: 'POST',
						data: {
							"code": code,
							"mchId": _this.mchId,
							"print": _this.buyType
						},
						success(res) {
							console.log('res', res)
							if(res.data.code == 200) {
								let resData = res.data.data;
								_this.waitIdx = resData.waitIdx == -1?1:resData.waitIdx;
								_this.waitTotal = resData.waitTotal;
								_this.waitTime = resData.waitTotal * 1;
								console.log('url', resData.url)
								// 判断是否拿到照片路径
								if(resData.url) {
									clearInterval(stateInterval)
									let url = resData.url.replace(/\[|\]/g, "");
									_this.showImage = 'https://oss.humengfilms.com/' +  url;
									// 判断是否有打印码
									if(resData.printCode != null) {
										_this.printCode = resData.printCode;
										let text = uni.getStorageSync('aiPhotoTemplate').printScreenTip;
										_this.printScreenTip = text.replace("*", resData.printCode);
									}
									pageNumber = 5;
									_this.wait = false;
								}
							}
						}
					})
				}, 5000);
			},
			firstGetPhoto(code) {
				var _this = this;
				uni.request({
					url: _this.java_http_url + '/applet/smart_camera/getSingleTemplateSynthesisPhoto',
					method: 'POST',
					data: {
						"code": code
					},
					success(res) {
						console.log('res', res)
						if(res.data.code == 200) {
							let resData = res.data.data;
							_this.waitIdx = resData.waitIdx == -1?1:resData.waitIdx;
							_this.waitTotal = resData.waitTotal == 0?1:resData.waitTotal;
							_this.waitTime = resData.waitTotal * 1;
							if(res.data.url) {
								let url = res.data.data.replace(/\[|\]/g, "");
								_this.showImage = 'https://oss.humengfilms.com/' +  url;
								_this.wait = false;
							}
						}
					},
					complete() {
						uni.hideLoading();
					}
				})
			},
			previewImage(url) {
				// 预览图片
				uni.previewImage({
					urls: [url],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
		}
	}
</script>

<style lang="scss">
@import '@/css/common.css';
@import './index.css';
</style>
