<template>
	<view class="page flex-col">
		<view class="title" :style="{'top': uniMenuInfo.top + 6 + 'px'}">{{template.templateName}}</view>
		<view class="back" @tap="goBack()" :style="{'top' : uniMenuInfo.top - 12 + 'px'}"></view>
		<view class="content" :style="{'top' : uniMenuInfo.top + 40 + 'px'}">
			<image class="img_1" mode="aspectFill" :src="template.coverPicture" />
			<view class="tries-limit" v-if="template.paymentType == 2 && residues != 0">
				此模板剩余使用次数:&nbsp;&nbsp;{{ residues }}
			</view>
			<view class="tries-limit" v-if="template.paymentType == 1">
				付费 {{ template.fee }} 元 &nbsp;&nbsp;体验{{ template.triesLimit }} 次
			</view>
			<view class="tries-limit" v-if="template.paymentType == 3">
				免费体验一次
			</view>
			<view class="section_11 flex-row">
				<view class="section_8 flex-row" @tap="chooseImage('album')">
					<view class="image-text_7 flex-col">
						<image
							class="label_1"
							referrerpolicy="no-referrer"
							src="https://humeng-res.oss-cn-beijing.aliyuncs.com/hm_aigc/applet/icon_%E6%8B%8D%E6%91%84%E7%85%A7%E7%89%87%402x.png"
						/>
						<text class="text-group_3">选择相册图片</text>
					</view>
				</view>
				<view class="section_9 flex-row" @tap="chooseImage('camera')">
					<view class="image-text_8 flex-col">
						<image
							class="label_2"
							referrerpolicy="no-referrer"
							src="https://humeng-res.oss-cn-beijing.aliyuncs.com/hm_aigc/applet/icon_%E7%9B%B8%E5%86%8C%E7%85%A7%E7%89%87%402x.png"
						/>
						<text class="text-group_4">拍摄照片</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 支付弹窗 -->
		<view>
			<uni-popup ref="share" type="share" safeArea backgroundColor="#fff">
				<uni-popup-pay ref="pay" @select="toPay"></uni-popup-pay>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	const uploadFile= require('../../utils/uploadToAliOss/uploadAliyun.js');
	import { mul } from "@/utils/calculate/calculate.js"
	const getNowTime = require('../../utils/timeUtil/timeUtil.js')
	let pageNumber = 3;
	let startTime = '';
	let destroyTime = '';
	export default {
		data() {
			return {
				uniMenuInfo: {},
				templateSets: [],
				templateSet: {},
				template: {},
				residues: 0,
				imgs: '',
				templateId: '',
				payId: -1,
				buyType: 0,
			}
		},
		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.template.id,
					"mchId": _this.template.mchId,
				};
				uni.request({
					url: _this.java_http_url + '/applet/smart_camera/logRecord',
					method: 'POST',
					data: reqData,
					success(res) {}
				})
			},
			getPayment() {
				var _this = this;
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				uni.request({
					url: _this.java_http_url + '/applet/smart_camera/getUserIsPay',
					method: 'POST',
					data: {
						user_id: uni.getStorageSync('userInfo').id,
						template_id: _this.templateId
					},
					success(res) {
						console.log('res', res)
						if(res.data.data.code == 200) {
							_this.residues = res.data.data.residualUse;
							_this.payId = res.data.data.payId;
							if(_this.residues <= 0 && _this.template.paymentType == 2) {
								_this.template.paymentType = 1;
							}
						}
					},
					complete() {
						uni.hideLoading();
					}
				})
			},
			toPay(e) {
				uni.showLoading({
					title: '请稍候',
					mask: true
				})
				var _this = this;
				console.log('支付类型', e)
				_this.buyType = e;
				let totalFee = e == 2?mul(_this.template.printFee,100):mul(_this.template.fee,100);
				let triesLimit = e == 2?1:_this.template.triesLimit;
				if(totalFee == 0) {
					_this.syntheticImage(_this.imgs);
					return
				}
				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.$refs.share.close();
											_this.template.paymentType = e!=2?2:1;
											_this.residues = _this.template.triesLimit;
											_this.syntheticImage(_this.imgs);
										},
										fail() {
											uni.hideLoading()
										}
									})
								}
							}
						},
						fail() {
							uni.hideLoading();
							uni.showToast({
								title: '支付失败',
								icon: "error",
								mask: true
							})
						}
					})
				}
			},
			generateCode(length) {
				let code = '';
				const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
				const charactersLength = characters.length;
				for (let i = 0; i < length; i++) {
					code += characters.charAt(Math.floor(Math.random() * charactersLength));
				}
				return code;
			},
			getToday() {
				var now = new Date();  
				var year = now.getFullYear();  
				var month = now.getMonth() + 1;  
				var day = now.getDate();  
				month = month.toString().padStart(2, '0');  
				day = day.toString().padStart(2, '0');  
				return `${year}-${month}-${day}`;
			},
			syntheticImage(url) {
				var _this = this;
				let dir = 'smartcamera/' + _this.getToday()  + '/';
				var match = url[0].match(/\.([^.]+)$/);
				let promise = Promise.all(
					url.map((tempFilePath, index) => {
						return new Promise(function(resolve, reject) {
							uploadFile({
								filePath: tempFilePath,
								dir: dir,
								type: match[0],
								success: function(res) {
									// console.log('上传成功---', res);
									resolve(res);
								},
								fail: function(res) {
									// console.log('上传失败---', res);
									uni.hideLoading();
									uni.showToast({
										title: '上传失败,请重试！',
										icon: 'none',
										duration: 4000
									})
								}
							});
						});
					})
				).then((res) => {
					let code = _this.generateCode(24);
					uni.request({
						url: _this.java_http_url + '/applet/smart_camera/synthesisAiPhoto',
						method: 'POST',
						data: {
							'code': code,
							'templateId': _this.template.id,
							'templateSetId': _this.templateSet.id,
							'photo': res[0],
							'userId': uni.getStorageSync('userInfo').id,
							'payId': _this.payId,
							'mchId': _this.templateSet.mchId,
							'buyType': _this.buyType,
							'appletType': 2
						},
						success: (res) => {
							console.log('aiphotoRes', res)
							if(res.data.code == 200) {
								uni.navigateTo({
									url: "../display/display?code=" + code + "&templateId=" + _this.template.id
										+ "&mchId=" + _this.template.mchId +"&buyType=" + _this.buyType 
										+ "&templateSetId=" + _this.templateSet.id,
									success() {
										uni.hideLoading();
									}
								})
							} else {
								uni.hideLoading();
								uni.showToast({
									title: '图片含有多个人脸或无人脸，请重新上传！',
									icon: 'none',
									duration: 5000
								})
							}
						},
						fail(err) {
							console.log('err', err)
							uni.hideLoading()
						}
					});
				});
			},
			selectImage(img) {
				var _this = this;
				uni.showModal({
					title: '温馨提示',
					content: '是否开始制作',
					confirmColor: '#6b99fb',
					success: function (res) {
						if (res.confirm) {
							console.log('用户点击确定');
							if((_this.template.paymentType == 1 || _this.template.paymentType == 2) && _this.residues <= 0) {
								_this.$refs.pay.setTemplate(_this.template);
								_this.$refs.share.open();
								_this.imgs = img;
							} else {
								uni.showLoading({
									title: '上传中',
									mask: true
								});
								_this.syntheticImage(img);
							}
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			chooseImage(type) {
				var _this = this
				uni.chooseMedia({
					count: 1,
					sizeType: ['original', 'compressed'], 
					sourceType: [type],
					camera: 'front',
					success: function (res) {
						let img = [res.tempFiles[0].tempFilePath];
						_this.selectImage(img);
					}
				});
			},
			getTemplate(setId, templateId) {
				var _this = this;
				_this.templateSets.forEach((set, idx)=> {
					if(set.id == setId) {
						_this.templateSet = set;
						set.templates.forEach((tem, idx)=> {
							if(tem.id == templateId) {
								_this.template = tem;
								uni.setStorageSync('aiPhotoTemplate', tem)
							}
						})
					}
				})
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
		},
		onLoad(option) {
			var _this = this;
			_this.uniMenuInfo = uni.getStorageSync('uniMenuInfo');
			_this.templateSets = uni.getStorageSync('templateSets');
			_this.templateId = option.templateId;
			_this.getTemplate(option.templateSetId, option.templateId);
		},
		onShow() {
			if(this.template.paymentType == 1 || this.template.paymentType == 2) {
				this.getPayment();
			}
			startTime = getNowTime();
		},
		onHide() {
			if(uni.getStorageSync('userInfo').id) {
				this.logRecord();
			}
		},
		onUnload() {
			if(uni.getStorageSync('userInfo').id) {
				this.logRecord();
			}
		},
	}
</script>

<style>
@import url("@/css/common.css");
@import url("@/pages/selectPhoto/index.css");
</style>
