<template>
	<view class="page flex-col">
		<view class="title" :style="{'top': uniMenuInfo.top + 6 + 'px'}">{{ headline }}</view>
		<!-- <view class="back" v-if="!scanQRCodes" @tap="goBack()" :style="{'top' : uniMenuInfo.top - 12 + 'px'}"></view> -->
		<!-- 切换商户 -->
		<view class="root" v-if="!scanQRCodes" :style="{'top': uniMenuInfo.top + 40 + 'px'}">
			<ren-dropdown-filter ref="root" :filterData='filterData' :defaultIndex='defaultIndex'
			        @onSelected='onSelected' @dateChange='dateChange'></ren-dropdown-filter>
		</view>
		<view class="box_1 flex-col" :style="{'top': uniMenuInfo.top + boxTop + 'px'}">
			<view class="box_3 flex-col" v-for="item1 in templateSet" :key="item1.id">
				<view class="text-wrapper_2 flex-row">
					<text class="text_4">{{item1.name}}</text>
				</view>
				<scroll-view class="scroll-view_H" scroll-x="true" :show-scrollbar="false" :enhanced="true">
					<view id="demo1" class="scroll-view-item_H" @tap="shareToggle(item2, item1)" v-for="(item2, idx) in item1.templates" :key="item2.id">
						<image class="img_1" :src="item2.coverPicture" mode="aspectFill"></image>
						<view :class="item2.paymentType == 1? 'text-wrapper_5 flex-col':item2.paymentType == 2? 'text-wrapper_6 flex-col':'text-wrapper_3 flex-col'">
							<text class="text_5" >{{item2.paymentType == 1?'付费':item2.paymentType == 2?'已购':'限免'}}</text>
						</view>
						<view class="text-wrapper_4 flex-col" >
							<text class="text_6">{{item2.templateName}}</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 隐私授权弹窗 -->
		<zero-privacy ref="privacy" @agree='handleAgree' @disagree='handleDisagree'></zero-privacy>
		<!-- 底部导航 -->
		<view class="section_8 flex-row justify-between">
			<custom-tab-bar :selected="0" />
		</view>
		
  </view>
</template>
<script>
const uploadFile= require('../../utils/uploadToAliOss/uploadAliyun.js');
const getNowTime = require('../../utils/timeUtil/timeUtil.js')
import CustomTabBar from "@/components/customTabBar/customTabBar.vue"
import RenDropdownFilter from '@/components/ren-dropdown-filter/ren-dropdown-filter.vue'
let pageNumber = 2;
let startTime = '';
let destroyTime = '';
export default {
	components: {
		CustomTabBar,
		RenDropdownFilter
	},
	data() {
		return {
			uniMenuInfo: {},
			selectTemplateImg: '',
			templateSet: [],
			selectTemplateId: 0,
			headline: '森蓝富拉格',
			scanQRCodes: false,
			qrcodeId: 0,
			userInfo: {},
			init: true,
			filterData:[
				[
					{ text: '选择景区', value: 0, select: false}
				]
			],
			defaultIndex:[0],
			boxTop: 90
		};
	},
	onLoad(option) {
		console.log(option)
		var _this = this;
		uni.showLoading({
			title: '正在加载...',
			mask: true
		});
		this.uniMenuInfo = uni.getMenuButtonBoundingClientRect();
		uni.setStorageSync('uniMenuInfo', this.uniMenuInfo);
		if (option.scene) {
			let data_arr = decodeURIComponent(option.scene).split('&');
			let _data = {};
			for (let i = 0; i < data_arr.length; i++) {
				let temp_arr = data_arr[i].split("=");
				_data[temp_arr[0]] = temp_arr[1]
			}
			_this.qrcodeId = Number(_data['qrcodeId']);
			_this.scanQRCodes = true;
			_this.boxTop = 40;
		}
		uni.removeStorageSync('mchId');
		if(_this.qrcodeId != 0) {
			_this.init = false;
			uni.removeStorageSync('userInfo');
			new Promise(function(resolve,reject) {
				_this.getQrcodeInfo(resolve, _this.qrcodeId);
			}).then(function() {
				_this.getPrivacySetting();
			})
		} else {
			_this.getMchList();
			_this.getPrivacySetting();
		}
	},
	onShow() {
		if(this.init && uni.getStorageSync('mchId')) {
			this.initialize();
		}
		startTime = getNowTime();
	},
	onHide() {
		if(uni.getStorageSync('userInfo').id) {
			this.logRecord();
		}
	},
	onUnload() {
		if(uni.getStorageSync('userInfo').id) {
			this.logRecord();
		}
	},
	methods: {
		getMchList() {
			var _this = this;
			uni.request({
				url: _this.java_http_url + '/applet/smart_camera/getMchList',
				method: 'POST',
				data: {
					appletType: 2
				},
				success(res) {
					console.log('商户列表', res.data.data)
					let mchList = res.data.data;
					_this.filterData = [
						[
							{ text: '选择景区', value: 0, select: false}
						]
					]
					mchList.forEach((el)=>{
						_this.filterData[0].push({
							text: el.mchName,
							value: el.id,
							select: false
						})
					})
					_this.$refs.root.updateFilterData(_this.filterData);
				}
			})
		},
		onSelected(res){
			console.log(res[0][0].value)
			uni.setStorageSync('mchId', res[0][0].value)
			if(res[0][0].value == 0) {
				this.headline = '森蓝富拉格'
			} else {
				this.headline = res[0][0].text
			}
			this.initialize()
		},
		dateChange(d){
			uni.showToast({
				icon:'none',
				title:d
			})
		},
		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,
				"mchId": uni.getStorageSync('scanQrcodeInfo').mchId
			};
			uni.request({
				url: _this.java_http_url + '/applet/smart_camera/logRecord',
				method: 'POST',
				data: reqData,
				success(res) {}
			})
		},
		handleDisagree() {
			console.log('拒绝隐私授权');
			var _this = this;
			uni.showModal({
				title: '提示',
				content: '拒绝授权部分功能将无法使用，是否退出小程序',
				success: function (res) {
					if (res.confirm) {
						console.log('用户点击确定');
						wx.exitMiniProgram({
							success: (res) => {
							console.log('退出小程序', res)
						}})
					} else if (res.cancel) {
						console.log('用户点击取消');
						_this.getPrivacySetting();
					}
				}
			});
		},
		handleAgree() {
			console.log('同意隐私授权');
			var _this = this;
			uni.showLoading({
				title: '正在加载...',
				mask: true
			});
			_this.getUserInfo();
		},
		getQrcodeInfo(resolve, qrcodeId) {
			var _this = this;
			uni.request({
				url: _this.java_http_url + '/applet/smart_camera/getQrcodeInfo',
				method: 'POST',
				data: {
					id: qrcodeId
				},
				success(res) {
					if(res.data.data) {
						let mchId = res.data.data.mchId;
						_this.headline = res.data.data.mchName;
						uni.setStorageSync('mchId', mchId);
						let scanQrcodeInfo = {
							qrcodeId: qrcodeId,
							mchId: mchId,
							scenicId: 0
						}
						uni.setStorageSync('scanQrcodeInfo', scanQrcodeInfo)
						resolve('ok')
					}
				}
			})
		},
		getUserInfo() {
			var _this = this;
			uni.getUserInfo({
				desc: '用于完善会员资料',
				lang: 'zh_CN',
				success: (user) => {
					// >>当用户同意授权后, 获取到用户信息user
					uni.login({
						provider: 'weixin',
						success: loginRes => {
							let userInfo = JSON.parse(user.rawData);
							userInfo.code = loginRes.code;
							userInfo.appletType = 2;
							uni.getSystemInfo({
								success: function(res) {
									userInfo.model = res.model
									userInfo.edition = res.version
									uni.request({
										url: _this.java_http_url + '/applet/smart_camera/codeGetUserInfo',
										method: "POST",
										data: userInfo,
										success(res) {
											if(res.data.code == 200) {
												userInfo = res.data.data;
												_this.userInfo = userInfo;
												uni.setStorageSync('userInfo', userInfo);
												if(uni.getStorageSync('mchId')) {
													_this.initialize();
												}
											}
										},
										complete() {
											uni.hideLoading();
										}
									})
								},
							})
						}
					})
				},
				fail(err) {
					console.log(err);
					uni.hideLoading();
				}
			})
		},
		getPrivacySetting() {
			var _this = this;
			wx.getPrivacySetting({
				success: res => {
					console.log(res)
					if (res.needAuthorization) {
						// 需要弹出隐私协议
						console.log('需要弹出隐私协议', res)
						_this.$refs.privacy.open(res.privacyContractName);
						uni.hideLoading();
					} else {
						_this.getUserInfo();
					}
				}
		    })
		},
		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(32);
				uni.request({
					url: _this.java_http_url + '/applet/smart_camera/synthesisAiPhoto',
					method: 'POST',
					data: {
						'code': code,
						'templateId': _this.selectTemplateId,
						'photo': res[0],
						'userId': uni.getStorageSync('userInfo').id
					},
					success: (res) => {
						console.log('aiphotoRes', res)
						if(res.data.code == 200) {
							uni.hideLoading();
							_this.$refs.popup.close();
							uni.navigateTo({
								url: "../display/display?code=" + code
							})
						}
					},
					fail(err) {
						console.log('err', err)
					}
				});
			});
		},
		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;
		},
		initialize() {
			uni.showLoading({
				title: '正在加载...',
				mask: true
			});
			var _this = this;
			_this.init = true;
			uni.request({
				url: _this.java_http_url + '/applet/smart_camera/getTemplateSetList',
				method: 'POST',
				data: {
					mchId: uni.getStorageSync('mchId'),
					userId: uni.getStorageSync('userInfo').id
				},
				success(res) {
					console.log('getTemplateSetAll', res)
					if(res.data.code == 200) {
						_this.templateSet = res.data.data;
						uni.setStorageSync('templateSets', _this.templateSet);
						setTimeout(()=> {
							uni.hideLoading();
						}, 500)
					} else {
						uni.hideLoading();
					}
				},
				fail(err) {
					console.log('error', err)
					uni.hideLoading();
				}
			})
		},
		selectImage(data) {
			var _this = this;
			let img = data.item;
			uni.showModal({
				title: '温馨提示',
				content: '是否开始制作',
				confirmColor: '#6b99fb',
				success: function (res) {
					if (res.confirm) {
						console.log('用户点击确定');
						uni.showLoading({
							title: '上传中',
							mask: true
						});
						_this.syntheticImage(img);
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		scroll(e) {
			// console.log(e)
		},
		shareToggle(template, templateSet) {
			uni.navigateTo({
				url: '../selectPhoto/selectPhoto?templateId=' + template.id + '&templateSetId=' + templateSet.id
			})
		},
		goBack() {
			uni.navigateBack({
				delta: 1
			})
		},
	},
};
</script>
<style lang="scss">
@import '@/css/common.css';
@import './index.css';
</style>
