<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)"/>
				<image class="image-sy" v-if="template.paymentType == 3 && template.fee != 0 && !isPay"
					src="https://humeng-res.oss-cn-beijing.aliyuncs.com/humeng/vlog/whiteboard_portraitmode.png" mode="aspectFill"></image>
				<view class="printTip" v-if="buyType == 2">{{ printScreenTip }}</view>
				<view class="upload-btn" v-if="template.paymentType != 3" @tap="saveImage()">保存到手机</view>
				<view class="btn_content" v-if="template.paymentType == 3 && template.fee != 0">
					<view class="buyBtn" v-if="!isPay" @tap="toPay()">
						{{template.fee}}购买高清版
					</view>
					<view class="buyBtn" v-if="isPay" @tap="saveImage()">
						保存到手机
					</view>
					<view class="skipBtn" @tap="jumpApplet()">
						去定制
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { mul } from "@/utils/calculate/calculate.js"
	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: '',
				template: {},
				templateSet: {},
				payId: '',
				isPay: false,
				record: {},
				templateSetId: '',
				isOnUnload: 0
			}
		},
		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.templateSetId = Number(option.templateSetId);
			this.mchId = Number(option.mchId);
			this.buyType = Number(option.buyType);
			if(option.myPhoto == "1") {
				this.wait = false
				this.record = uni.getStorageSync('record')
				this.isPay = this.record.payId != "-1"
				this.showImage = 'https://oss.humengfilms.com/' +  this.record.aiPhoto;
				if(this.record.printCode != null) {
					_this.printCode = this.record.printCode;
					let text = _this.template.printScreenTip;
					_this.printScreenTip = text.replace("*", resData.printCode);
				}
			} else {
				this.getPhotoGenerationRecord();
				this.firstGetPhoto(_this.code);
				this.getPhoto(this.code);
			}
			this.getTemplate(this.templateId)
			this.getTemplateSet(this.templateSetId);
		},
		onShow() {
			startTime = getNowTime();
		},
		onHide() {
			console.log('onHide')
			if(uni.getStorageSync('userInfo').id) {
				this.logRecord();
			}
		},
		onUnload() {
			this.isOnUnload = 1
			if(uni.getStorageSync('userInfo').id) {
				this.logRecord();
			}
		},
		methods: {
			getTemplateSet(id) {
				var _this = this;
				uni.request({
					url: _this.java_http_url + '/aiweb/templateSet/getTemplateSetById',
					method: "POST",
					header: {
						'content-type': "application/x-www-form-urlencoded"
					},
					data: {
						id: id 
					},
					success(res) {
						_this.templateSet = res.data.data
					}
				})
			},
			getTemplate(id) {
				var _this = this;
				uni.request({
					url: _this.java_http_url + '/aiweb/sdTemplate/getSdTemplateById',
					method: "POST",
					data: {
						id: id 
					},
					success(res) {
						_this.template = res.data.data
					}
				})
			},
			recordBindPayId(payId) {
				var _this = this;
				uni.request({
					url: _this.java_http_url + '/applet/photo_generation_record/updateRecord',
					method: 'POST',
					data: {
						id: _this.record.id,
						payId: payId
					},
					success(res) {
						console.log('payIdRes:', res)
					}
				})
			},
			getPhotoGenerationRecord() {
				var _this = this;
				uni.request({
					url: _this.java_http_url + '/applet/photo_generation_record/getRecordByCode',
					method: 'POST',
					data: {
						userId: uni.getStorageSync('userInfo').id,
						code: _this.code,
					},
					success(res) {
						console.log('res:', res)
						_this.record = res.data.data
					}
				})
			},
			toPay(e) {
				uni.showLoading({
					title: '请稍候',
					mask: true
				})
				var _this = this;
				let totalFee = mul(_this.template.fee, 100);
				let triesLimit = 1;
				let data = {
					open_id: uni.getStorageSync('userInfo').openId,
					user_id: uni.getStorageSync('userInfo').id,
					total_fee: totalFee,
					merchant_id: _this.templateSet.mchId,
					template_id: _this.template.id,
					template_name: _this.template.templateName,
					payment_type: _this.template.paymentType,
					tries_limit: triesLimit
				};
				console.log('支付参数', data)
				if (e != 0) {
					console.log('data', data)
					uni.request({
						url: _this.pay_http_url + '/wxpay/pay',
						method: 'POST',
						data: data,
						success: res => {
							console.log('pay request success', res);
							if (res.statusCode !== 200) {
								uni.showModal({
									content: '支付失败，请重试！',
									showCancel: false,
									success() {
										uni.hideLoading();
									}
								});
							} else {
								if (res.data.code == 'pay') {
									console.log('res', res.data)
									let payId = res.data.order_id;
									uni.requestPayment({
										timeStamp: res.data.timeStamp,
										nonceStr: res.data.nonceStr,
										package: res.data.package,
										signType: 'MD5',
										paySign: res.data.paySign,
										success: res => {
											console.log('res', res)
											_this.payId = payId;
											_this.isPay = true;
											console.log('支付成功')
											_this.recordBindPayId(payId);
											uni.hideLoading()
										},
										fail() {
											uni.hideLoading()
										}
									})
								}
							}
						},
						fail() {
							uni.hideLoading();
							uni.showToast({
								title: '支付失败',
								icon: "error",
								mask: true
							})
						}
					})
				}
			},
			jumpApplet() {
				wx.navigateToMiniProgram({
					appId: 'wx1aee6186e7cfd004',
					path: 'pages/home/home?aid=33304411&yid=1&storeId=1&_r=1',
					//develop开发版；trial体验版；release正式版
					envVersion: 'release', 
					success(res) {
						// 打开成功
						console.log("跳转小程序成功！",res);
					},
					fail(err) {
						console.log('跳转失败', err)
					}
				})
			},
			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;
								}
								if(_this.isOnUnload == 1) {
									clearInterval(stateInterval)
								}
							}
						}
					})
				}, 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>
