<template>
	<view class="container" :style="{backgroundColor: 'black',width: 100 + '%',height: 100 + '%'}">
		<!-- 图片绘制区域 -->
		<view class="paint">
			<view class="cover" v-if="successFlag === false">
				<view class="plate">
					<view class="loading-icon">
						<uni-icons type="spinner-cycle" size="40"></uni-icons>
					</view>
					<view class="loading-tips">    
						Ai正在拼命绘制中.....
					</view>
				</view>
			</view>
			<!-- 绘制好的图替换默认图展示 -->
			<view class="successCover" @click="onPreviewImage" v-if="successFlag === true">
				<image :src="transImg" mode="aspectFill" class="img"></image>
			</view>
		</view>
		
		<!-- <view class="complete" :style="{backgroundImage: 'url(' + transImg + ')'}"> -->
		<view class="complete">
		<!-- 	prompt关键词 -->
			<view class="keywords">
				<view>
					<view class="promptTitle">关键词</view>
				</view>
				<view class="content">
					<text>{{prompt}}</text>
				</view>
			</view>
			
			<!-- 图画详细参数 -->
			<view class="label">
			<!-- 	<view class="style">
					<view class="i">关键词</view>
					<view class="text">{{ prompt }}</view>
				</view> -->
				<view class="style">
					<view class="i">画布:</view>
					<view class="text">{{ imgWidth }}x{{ imgHeight }}</view>
				</view>
				<view class="style">
					<view class="i">创作风格:</view>
					<view class="text">{{styleName}}</view>
				</view>
				<view class="style" v-if="successFlag === true">
					<view class="i">作品编号:</view>
					<view class="text">{{paintId}}</view>
				</view>
				<view class="style" v-if="successFlag === true">
					<view class="i">创作时间:</view>
					<view class="text">{{paintTime}}</view>
				</view>
			</view>
			
		<!-- 	底部操作栏(绘制成功替换，告知图片保存在用户画册里) -->
			<view class="action" v-if="successFlag === true">
				<view class="action-group">
					<view class="actionBtn">
						<view class="grid" @click="onCopyPrompt">
							<uni-icons type="paperplane-filled" size="30"></uni-icons>
							<text class="grid-text">复制关键词</text>
						</view>
					</view>
					<view class="actionBtn">
						<view class="grid" @click="onSaveImage(transImg)">
							<uni-icons type="cloud-download-filled" size="30"></uni-icons>
							<text class="grid-text">保存作品</text>
						</view>
					</view>
					<view class="actionBtn">
						<view class="grid" @click="onShareImage">
							<uni-icons type="pyq" size="30"></uni-icons>
							<button open-type="share" size="mini" plain="true" type="default">分享好友</button>
						</view>
					</view>
				</view>
			</view>
			
		</view>
	</view>
	
</template>

<script>
	import base64ToImg from '@/utils/base64Utils';
	import { textToImg} from '@/api/paint.js';
	import {loginTiktok} from '@/api/auth.js'
	export default {
		data() {
			return {
				//广告加载状态
				adStatus: false,
				imgHeight: undefined,
				imgWidth: undefined,
				transImg: undefined,
				prompt: undefined,
				successFlag: false,
				paintId: undefined,
				paintTime: undefined,
				styleName: undefined,
				//imgHeight: 512,
				//imgWidth: 512,
			}	
		},
		onLoad(options) {
			//接收上一个页面传来的绘画参数
			const paintData = JSON.parse(options.data);
			console.log('paintData',paintData);
			this.imgHeight = paintData.height;
			this.imgWidth = paintData.width;
			this.prompt = paintData.prompt;
			this.styleName = paintData.styleName;
			textToImg(paintData).then(res =>{
				if(res.data.code === 200){
					uni.hideLoading();
					console.log('res',res);
					this.base64ToPath(res.data.data.images);
					this.successFlag = true;
					this.paintTime = res.data.data.paintTime;
					this.paintId = res.data.data.paintId;
			 	}
				
			 });
			 
			 //加载广告
			 //initReward();
			 
		},
		onShareTimeline() {
			let _this = this
			let referee_id = ''
			if (_this.userInfo.user_id) {
				referee_id = _this.userInfo.user_id
			}
			return {
				imageUrl: _this.share.share.image_url,
				title: _this.share.share.title,
				path: '/pages/main/draw/index?referee_id=' + referee_id
			}
		},
		onShareAppMessage() {
			console.log('惦记了分享')
			// let _this = this
			// let referee_id = ''
			// if (_this.userInfo.user_id) {
			// 	referee_id = _this.userInfo.user_id
			// }
			// return {
			// 	imageUrl: _this.share.share.image_url,
			// 	desc: _this.share.share.desc,
			// 	title: '@'+_this.share.share.title,
			// 	path: '/pages/main/draw/index?referee_id=' + referee_id
			// }
		},
		methods: {
			
			//加载广告实例
			// initReward(){
			// 	let that = this;
			// 	rewarded.load(that.spool.reward.id, () => {
			// 		uni.setClipboardData({
			// 			data: that.draw.draw_text
			// 		}) 
			// 	})
			// },
			
			//调用登录接口
			async loginFunc(res, userInfo, callBack) {
			  const params = {
			    code: res.code,
			    encryptedData: userInfo.encryptedData,
			    iv: userInfo.iv
			  }
			  // 用户授权登录
			  await loginTiktok(params).then(res => {
			    if (res.data.code === 200) {
			      uni.setStorage({
			        key: 'userInfo',
			        data: res.data.data.userInfo,
			      })
			      this.userInfo = res.data.data.userInfo;
						console.log('this.userInfo',this.userInfo)
			      uni.setStorage({
			        key: 'token',
			        data: res.data.data.access_token
			      })
						let headers = {
							TiktokAuthorization: res.data.data.access_token
						}
						callBack && callBack(headers)
			    } else {
			      uni.showToast({
			        title: res.data.msg,
			        icon: 'none'
			      })
			    }
			  }).catch(res => {})
			},
			
			// 获取用户信息
			async getUserInfoLogin(callBack) {
			  uni.getSetting({
			    success: (settingObj) => {
			      if (settingObj.authSetting['scope.userInfo'] === undefined || settingObj.authSetting['scope.userInfo']) {
			        uni.login({
			          force: true,
			          success: (res) => {
			            uni.getUserInfo({
			              withCredentials: true,
			              success: async (userInfo) => {
			                await this.loginFunc(res, userInfo, callBack)
			              },
			            })
			          },
			        })
			      } else {
			        uni.showModal({
			          title: '您已拒绝授权用户信息',
			          content: '是否进入权限管理，调整授权？',
			          success: function (res) {
			            if (res.confirm) {
			              uni.openSetting({
			                success: (settingRes) => {
			                  if (settingRes.authSetting['scope.userInfo']) {
			                    uni.login({
			                      force: true,
			                      success: (res) => {
			                        uni.getUserInfo({
			                          withCredentials: true,
			                          success: async (userInfo) => {
			                            await this.loginFunc(res, userInfo, callBack)
			                          },
			                        })
			                      },
			                    })
			                  }
			                },
			              })
			            } else if (res.cancel) {
			              console.log('用户点击取消');
			            }
			          }
			        });
			      }
			    }
			  })
			},
			
			//保存图片
			onSaveImage(url){
				let that = this;
				console.log('点击了保存图片事件')
				that.download(url)
			},
			
			// 下载
			download(url) {
				let that = this;
				//console.log('即将下载的图片为',that.transImg)
					uni.showLoading({
						title: '正在保存图片...'
					});
					//获取用户的当前设置。获取相册权限
					uni.getSetting({
						success: (res) => {
							//如果没有相册权限
							if (!res.authSetting["scope.album"]) {
								//向用户发起授权请求
								uni.authorize({
									scope: "scope.album",
									success: () => {
										uni.saveImageToPhotosAlbum({
											//图片路径，不支持网络图片路径
											filePath: url,
											success: (res) => {
												
											},
											fail: (res) => {
												return uni.showToast({
														title: res.errMsg,
														icon: 'none'
													});
											},
											complete: (res) => {
												uni.hideLoading();
												if (res.errMsg !== "saveImageToPhotosAlbum:ok") {
													return uni.showToast({
															title: "下载失败！",
															icon: 'none'
														});
												} else {
													return uni.showToast({
															title: "保存成功！",
															icon: 'none',
															success() {
																
															}
														});
												}
											},
										});
									},
									//授权失败
									fail: () => {
										uni.hideLoading();
										uni.showModal({
											title: "您已拒绝获取相册权限",
											content: "是否进入权限管理，调整授权？",
											success: (res) => {
												if (res.confirm) {
													//调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
													uni.openSetting({
														success: (res) => {
			
														},
													});
												} else if (res.cancel) {
													return uni.showToast({
														title: "已取消！",
														icon: 'none'
													});
												}
											},
										});
									},
								});
							} else {
								//如果已有相册权限，直接保存图片到系统相册
								uni.saveImageToPhotosAlbum({
									filePath: url,
									success: (res) => {
										console.log('有权限下载图片结果为',res)
										uni.hideLoading();
										console.log('333333')
										if(res.errMsg === "saveImageToPhotosAlbum:ok"){
											console.log('44444')
											return uni.showToast({
												title: "保存成功！",
												duration: 2000,
												icon: 'none'
											});
										}
									},
									fail: (res) => {
										uni.hideLoading();
										return uni.showToast({
											title: res.errMsg,
											icon: 'none'
										});
									},
									//无论成功失败都走的回调
									complete: (res) => {
										uni.hideLoading();
									},
								});
							}
						},
						fail: (res) => {},
					});
			},
			
			//复制关键词
			onCopyPrompt(){
				let that = this;
				//console.log('点击复制关键词事件')
				uni.setClipboardData({
					data: that.prompt,
					success() {
						uni.showToast({
							title: '复制关键词成功!'
						});
						
					}
				})
			},
			
			//分享
			onShareImage(){
				console.log('点击分享事件')
			},
			
			//查看大图
			onPreviewImage(){
				console.log('点击查看大图事件')
			},
			
			
			//转义base64图片
			base64ToPath(url){
				let str = "data:image/png;base64,"+url;
				base64ToImg(str,res =>{
					console.log('解析出的图片路径为:',res)
					this.transImg = res;
					//将complate的css底图改成此
				});
			},
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #f4f4f4;
		height: 100%;
	}
	
	
	@keyframes xing {
		0% {
			transform: scale(1);
		}
	
		25% {
			transform: scale(1.2);
		}
	
		50% {
			transform: scale(1);
		}
	
		75% {
			transform: scale(1.2);
		}
	}
	
	@keyframes fadenum {
		100% {
			transform: rotate(360deg);
		}
	}
	
	.ad {
		margin-top: 30rpx;
	}
	
	.complete {
		.action {
			width: 100%;
			position: fixed;
			bottom: 0rpx;
			left: 0rpx;
			background-color: #fff;
			padding: 30rpx 10rpx;
	
			.action-group {
				width: 90%;
				margin: 0 auto;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
	
				.actionBtn{
					width: 50%;
					display: flex;
					flex-direction: row;
					justify-content: center;
					//margin:0rpx 25rpx 0rpx 25rpx;
	
					.grid {
						display: flex;
						flex-direction: column;
						align-items: center;
						
						.grid-text {
							font-size: 30rpx;
							margin-top: 10rpx;
						}
						
						button {
							background-color: transparent;
							border: 0;
							outline: 0;
							font-size: 30rpx;
						}
						
						button::after{
							border: none;
							outline: 0;
						}
					}
				}
			}
		}
		
		.label {
			width: 92%;
			margin: 0 auto;
			display: flex;
			flex-direction: column;
			justify-content: left;
			align-items: flex-start;
			margin-top: 15rpx;
		
	
			.style {
				display: flex;
				flex-direction: row;
				align-items: flex-start;
				margin-top: 30rpx;
				color:#fff;
				font-weight: bolder;
	
				.i {
					//background-color: #fff;
					color: #1A96DB;
					padding: 5rpx 10rpx;
					border-radius: 5rpx;
					margin-right: 15rpx;
				}
	
				.text {
					font-size: 40rpx;
					font-weight: bolder;
					color: #fff;  
					background-color: #1A94BC1A;
				}
			}
		}
		
		.promptTitle{
			text-align: center;
			font-weight: bolder;
			font-size: 40rpx;
			color: #1A96DB;
		}
		
		.keywords {
			width: 90%;
			margin: 0 auto;
			//background-color: #1A94BC1A;
			padding: 15rpx;
			border-radius: 10rpx;
			margin-top: 15rpx;
			font-weight: bolder;
			
			.content {
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				/*这里设置几行*/
				overflow: hidden;
				color: #fff;
			}
		}
	}
	
	.paint {
		.cover {
			width: 100%;
			height: 720rpx;
			border-radius: 10rpx;
			background-image: url('https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/63889c845a7e3f0310de5223/6398219cd109e60012196b2c/16715997158982711362.png');
			background-size: 100% 100%;
			background-repeat: no-repeat;
	
			.plate {
				width: 100%;
				height: 720rpx;
				backdrop-filter: blur(25rpx);
				background: rgba(255, 255, 255, .3);
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
	
				.loading-icon {
					animation: fadenum 5s infinite;
				}
	
				.loading-tips {
					margin-top: 30rpx;
					color: #fff;
				}
			}
		}
		
		.successCover {
			width: 100%;
			height: 720rpx;
			border-radius: 10rpx;
			
			.img{
				width: 100%;
				height: 720rpx;
				border-radius: 10rpx;
			}
		}
	}
</style>
