<template>
	<view>
		<view style="color: #fff;">
			<tn-nav-bar backgroundColor="#26B3A0" :bottomShadow="false">绘画记录</tn-nav-bar>
		</view>
		<z-paging ref="paging" refresher-complete-delay="200" v-model="drawList" @query="queryList">
			<view slot="top" class="z_tabs" :style="{ marginTop: tobheight + 'px' }"></view>
			
			<view class="u-flex flex-wrap">
				<block v-for="(item,index) in drawList" :key="index">
				<view  class="draw_view">
					<view v-if="item.imgs_file.length>1" class="sheets">
						{{item.imgs_file.length}}张
					</view>
					<view v-if="item.done == 1&&item.status == 1" class="draw_image u-flex align-center">
						<image @click="preview(index)" :src="item.imgs_file[item.steps]?item.imgs_file[item.steps]:item.origin_url" mode="widthFix"></image>
						<view v-if="item.imgs_file.length>1" class="imgs_arrow u-flex align-center justify-between">
							<view @click.stop="item.steps==0?'':item.steps--" class="arrow"><u-icon name="arrow-left" color="#fff" size="28"></u-icon></view>
							<view @click.stop="item.steps==item.imgs_file.length - 1?'':item.steps++" class="arrow"><u-icon name="arrow-right" color="#fff" size="28"></u-icon></view>
						</view>
					</view>
					
					
 					
					<view v-else class="draw_done u-flex align-center justify-center">
						<block v-if="item.done == 1">
							{{item.status == 0?'图片正在审核中...':item.status == 2?'图片审核不通过':'图片审核通过'}}
						</block>
						<block v-else>
							{{item.done == 0?'图片正在生成中...':item.done == 2?'图片生成失败':'图片生成成功'}}
						</block>
					</view>
					
					<view class="prompt"><u-parse :content="item.prompt" :selectable="true"></u-parse></view>
					<view class="create_time">AI绘画：{{item.engine == 'sd'?'StableDiffusion绘图':'MidJourney绘图'}}</view>
					<view class="create_time">创建时间：{{item.create_time}}</view>
					
					<!-- <view v-if="item.done == 1&&item.status == 1" @click="createPoster(index)" hover-class="hoversubmit" class="onekey">生成海报</view> -->
					<block v-if="item.engine == 'sd'">
						<view v-if="item.done == 1&&item.status == 1" class="tn-flex justify-between operate">
							<view @click="tnproduct(item.id,item.engine)" hover-class="hoversubmit" class="onekey">绘画详情</view>
							<view @click="createPoster(index,item.steps)" hover-class="hoversubmit" class="onekey" style="background: #FFC107;">生成海报</view>
						</view>
					</block>
					<block v-else>
						<view v-if="item.done == 1&&item.status == 1" class="tn-flex justify-between operate">
						<view @click="createPoster(index,item.steps)" hover-class="hoversubmit" class="onekey" style="background: #FFC107;width: 100%;">生成海报</view>
						</view>
					</block>
					
					<view v-if="item.done > 0&&item.status > 0" class="circle" @click.stop="gallerydel(index)">
						<u-icon name="close-circle-fill" color="#e83a30" size="24"></u-icon>
					</view>
				</view>
				</block>
			</view>
			
		</z-paging>
		<wike-loading-page :isLoading="isLoading"></wike-loading-page>
		<u-popup :show="showPoster" mode="bottom" @close="showPoster = false">
			<scroll-view scroll-y="true" :style="{maxHeight: (posterheight) +'px'}">
				<wike-painter  :board="posterObj" @done="posterSuccess" ref="painter"></wike-painter>
				<view style="height: 78px;"></view>
				<view class="dygbhg" >
					<view class="whole" @click="showPoster = false">取消</view>
					<view class="distinguish" @click="toSave">保存/分享</view>
				</view>
			</scroll-view>
		</u-popup>
	</view>
</template>

<script>
	import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
	export default {
		data() {
			return {
				tobheight: 45,
				platform: this.$platform.get(),
				isLoading: true,
				drawList:[],
				showPoster:false,
				posterheight:'',
				qrcode:'',
				posterObj:{},
				subsectionlist: ['第1张图片', '第2张图片', '第3张图片'],
				current:0
			}
		},
		computed: {
			...mapGetters(['appInfo', 'userInfo', 'isLogin'])
		},
		onLoad() {
			const that = this;
			if (this.platform == 'wxMiniProgram') {
				var menumtop = uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight;
				var paddingtop = uni.getSystemInfoSync().statusBarHeight + menumtop;
				this.tobheight = menumtop + paddingtop + uni.getMenuButtonBoundingClientRect().height;
			}
			this.posterheight = uni.$u.sys().windowHeight-this.tobheight
			this.commonqrcodePath();
		},
		methods: {
			queryList(pageNo, pageSize) {
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				const params = {
					page: pageNo,
					limit: pageSize
				};
				this.$http('gallery.list', params).then(res => {
					if (res.code == 0) {
						uni.setNavigationBarTitle({
							title: this.appInfo.site_name
						});
						this.$refs.paging.complete(res.data.data);
						this.isLoading = false;
					}
				});
			},
			commonqrcodePath() {
				let spm = this.userInfo.id+'.1.0.'+this.spmplatform+'.1';
				this.$http('common.qrcodePath',{spm:spm}).then(res => {
					if (res.code == 0) {
						this.qrcode = res.data;
					}
				});
			},
			getdownload(e,type){
				return new Promise((resolve, reject) => {
				// uni.getImageInfo({
				// 	src: e,
				// 	success: res => {
				// 		uni.downloadFile({
				// 			url: e,
				// 			success: (res) => {
				// 				if (res.statusCode === 200) {
				// 					resolve(res.tempFilePath);
				// 				}
				// 				if(res.statusCode === 404){
				// 					let head = '/static/images/head.jpg',open = '/static/images/open.png';
				// 					if(type == 1){
				// 						resolve(head);
				// 					}else{
				// 						resolve(open);
				// 					}
				// 				}
				// 			}
				// 		});
				// 	},
				// 	fail: err => {
				// 		let head = '/static/images/head.jpg',open = '/static/images/open.png';
				// 		if(type == 1){
				// 			resolve(head);
				// 		}else{
				// 			resolve(open);
				// 		}
				// 	}
				// })
				uni.request({
				                        url: e,
				                        method:'GET',
				                        responseType:'arraybuffer',
				                        success: ress => {
				                            let base64 = wx.arrayBufferToBase64(ress.data); 
				                            base64 = 'data:image/jpeg;base64,' + base64
											resolve(base64);
				                        },
										fail: (e) => {
				                            let head = '/static/images/head.jpg',open = '/static/images/open.png';
				                            if(type == 1){
				                            	resolve(head);
				                            }else{
				                            	resolve(open);
				                            }
				                        }
				                    })
				});
			},
			toSave() {
				uni.showLoading({
					title: '海报生成中'
				});
				this.$refs.painter.canvasToTempFilePathSync({
					// 在nvue里是jpeg
					fileType: 'jpg',
					quality: 1,
					success: res => {
						// this.path = res.tempFilePath;
						// this.$refs.posterImg.open();
						// this.show_poster = true;
			
						// console.log(res.tempFilePath);
						// 非H5 保存到相册
						// H5 提示用户长按图另存
						// #ifdef MP-WEIXIN
						// uni.saveImageToPhotosAlbum({
						// 	filePath: res.tempFilePath,
						// 	success: function() {
						// 		uni.showToast({
						// 			title: '保存成功'
						// 		});
						// 		that.showPoster = false;
						// 	}
						// });
			
						wx.showShareImageMenu({
							path: res.tempFilePath
						})
						this.showPoster = false;
						uni.hideLoading();
						// #endif
						// #ifdef H5
						this.showPoster = false;
						uni.hideLoading();
						uni.showModal({
							confirmColor: '#26B3A0',
							confirmText: '查看图片',
							title: '提示',
							content: '查看图片后长按图片即可保存或分享',
							success(src) {
								if (src.confirm) {
									uni.previewImage({
										urls: [res.tempFilePath]
									});
								} else if (src.cancel) {
									this.showPoster = true;
								}
							}
						});
						// #endif
					}
				});
			},
			posterSuccess(){
				uni.hideLoading();
			},
			tnproduct(id,engine){
				uni.navigateTo({
					url:engine=='sd'?'/pages/painting/details?urls='+id:'/pages/painting/generate?urls='+id
				})
			},
			async createPoster(e,steps) {
				let that = this;
				let stays = '';
				let site_logo = '';
				uni.showLoading({
					title: '海报渲染中'
				});
				let mode = that.drawList[e].engine == 'sd'?'StableDiffusion绘图':'MidJourney绘图';
				let avatar_logo = that.userInfo.avatar ? await this.getdownload(that.userInfo.avatar,1):'/static/images/head.jpg';
				if(that.appInfo.site_logo_path.indexOf("https") < 0){
					site_logo = that.appInfo.site_logo_path ? await that.getdownload(that.appInfo.site_logo_path.replace("http:", "https:"),2):'/static/images/open.png';
				}else{
					site_logo = that.appInfo.site_logo_path ? await that.getdownload(that.appInfo.site_logo_path,2):'/static/images/open.png';
				}
				// console.log(that.drawList[e].imgs_file[steps]);
				if(that.drawList[e].imgs_file){
					if(that.drawList[e].imgs_file[steps].indexOf("https") < 0){
						stays = await that.getdownload(that.drawList[e].imgs_file[steps].replace("http:", "https:"),2);
					}else{
						stays = await that.getdownload(that.drawList[e].imgs_file[steps],2);
					}
				}else{
					if(that.drawList[e].origin_url.indexOf("https") < 0){
						stays = await that.getdownload(that.drawList[e].origin_url.replace("http:", "https:"),2);
					}else{
						stays = await that.getdownload(that.drawList[e].origin_url,2);
					}
				}
				
				if(stays == '/static/images/open.png'){
					uni.hideLoading();
					uni.showToast({
						title:'生成失败',
						icon:'none'
					})
					return;
				}
				(that.posterObj = {
					width: uni.$u.sys().windowWidth+ 'px',
					background: 'linear-gradient(to right, #00ca88 0%, #00BCD4 100%)',
					css: {
						// 根节点若无尺寸，自动获取父级节点
						width: uni.$u.sys().windowWidth+ 'px'
					},
					views: [
						{
							type: 'view',
							css: {
								marginTop: '20rpx',
								paddingLeft: '10rpx',
								display: 'flex'
							},
							views: [
								{
									type: 'image',
									src: avatar_logo,
									css: {
										marginTop: '10rpx',
										marginLeft: '20rpx',
										borderRadius: '16rpx',
										width: '80rpx',
										height: '80rpx',
										border: '2rpx solid #fff',
										objectFit: 'cover'
									}
								},
								{
									type: 'view',
									css: {
										marginTop: '10rpx',
										marginLeft: '20rpx'
									},
									views: [
										{
											type: 'view',
											views: [
												{
													type: 'text',
													text: this.userInfo.nickname?this.userInfo.nickname:'提问者',
													css: {
														marginTop: '10rpx',
														fontSize: '28rpx',
														fontWeight: 'bold',
														color: '#32324A',
														lineHeight: '28rpx'
													}
												}
											]
										},
										{
											type: 'view',
											views: [
												{
													type: 'text',
													text: '绘图描述词📝',
													css: {
														marginTop: '15rpx',
														fontSize: '20rpx',
														
														color: '#fff',
														lineHeight: '25rpx',
													}
												}
											]
										}
									]
								}
							]
						},
						{
							type: 'view',
							css: {
								marginTop: '20rpx',
								width: (uni.$u.sys().windowWidth - 48) + 'px',
								padding: '15rpx',
								background: '#fff',
								borderRadius: '16rpx',
								marginLeft: '30rpx',
							},
							views: [
								{
									type: 'text',
									text: that.drawList[e].prompt,
									css: {
										fontSize: '28rpx',
										color: '#000',
										// lineHeight: '45rpx',
										// lineClamp: 2,
										width: (uni.$u.sys().windowWidth - 48) + 'px'
									}
								}
							]
						},
						{
							type: 'view',
							css: {
								marginTop: '20rpx',
								paddingLeft: '10rpx',
								display: 'flex'
							},
							views: [
								{
									type: 'image',
									src: site_logo,
									css: {
										marginTop: '10rpx',
										marginLeft: '20rpx',
										borderRadius: '16rpx',
										width: '80rpx',
										height: '80rpx',
										border: '2rpx solid #fff',
										objectFit: 'cover'
									}
								},
								{
									type: 'view',
									css: {
										marginTop: '10rpx',
										marginLeft: '20rpx'
									},
									views: [
										{
											type: 'view',
											views: [
												{
													type: 'text',
													text: this.appInfo.site_name?this.appInfo.site_name:'AI智能问答机器人',
													css: {
														marginTop: '10rpx',
														fontSize: '28rpx',
														fontWeight: 'bold',
														color: '#32324A',
														lineHeight: '28rpx'
													}
												}
											]
										},
										{
											type: 'view',
											views: [
												{
													type: 'text',
													text: mode+'结果📝',
													css: {
														marginTop: '15rpx',
														fontSize: '20rpx',
														
														color: '#fff',
														lineHeight: '25rpx',
														
													}
												}
											]
										}
									]
								}
							]
						},
						{
							type: 'image',
							src: stays,
							css: {
								marginTop: '20rpx',
								width: (uni.$u.sys().windowWidth - 32) + 'px',
								objectFit: 'contain',
								borderRadius: '16rpx',
								marginLeft: '30rpx',
							}
						},
						{
							type: 'view',
							css: {
								marginTop: '30rpx',
								width: '100%',
								textAlign: 'center',
								
							},
							// #ifdef H5
							views: [
								{
									type: 'qrcode',
									text: this.qrcode,
									css: {
										width: '200rpx',
										height: '200rpx',
										borderRadius: '16rpx',
									}
								}
							],
							// #endif
							// #ifdef MP-WEIXIN
							views: [
								{
									type: 'image',
									src: this.qrcode,
									css: {
										width: '200rpx',
										height: '200rpx',
										borderRadius: '16rpx',
									}
								}
							]
							// #endif
						},
						{
							type: 'text',
							text: '————  ' + '长按识别 | 欢迎使用' + '  ————',
							css: {
								marginTop: '20rpx',
								marginBottom: '20rpx',
								width: '100%',
								textAlign: 'center',
								fontSize: '24rpx',
								color: '#fff',
								lineHeight: '33rpx'
							}
						}
					]
				}),
				(this.showPoster = true);
			},
			preview(e){
				if(this.drawList[e].done == 1&&this.drawList[e].status == 1){
					
					uni.previewImage({
						urls: this.drawList[e].imgs_file?this.drawList[e].imgs_file:[this.drawList[e].origin_url],
						current:0
					});
				}
				
			},
			gallerydel(e){
				var that = this;
				uni.showModal({
					confirmText: '删除',
					content: '是否删除此绘画记录',
					title: '提示',
					confirmColor: '#26B3A0',
					success(res) {
						// console.log(res);
						if (res.confirm) {
							that.$http('gallery.del', {id:that.drawList[e].id}).then(res => {
								if (res.code == 0) {
									uni.showToast({
										title:'删除成功'
									})
									// that.drawList = []
									that.$refs.paging.reload(true);
								}else{
									uni.showToast({
										title:'删除失败',
										icon:'none'
									})
								}
							});
						}
					}
				})
				
			}
		}
	}
</script>

<style lang="scss">
	page {
	    background: #f6f7fb;
	}
.draw_view{
	margin: 30rpx;
	width: 100%;
	background: #fff;
	border-radius: 20rpx;
	// padding: 30rpx;
	position: relative;
	
	.draw_image{
		position: relative;
		image{
			width: 100%;
			height: 280rpx;
			border-radius: 20rpx 20rpx 0 0;
		}
	}
	.sheets{
		    position: absolute;
		    z-index: 9;
		    padding: 4px 12px;
		    background: #0000007d;
		    color: #fff;
		    top: 15px;
		    left: 15px;
		    border-radius: 48px;
		    font-size: 13px;
	}
	.draw_done{
		height: 280rpx;
		font-size: 30px;
		    border-radius: 11px 11px 0 0;
		    background: #000;
		    color: #fff;
	}
	.prompt{
		padding: 20rpx 30rpx 30rpx;
	}
	.create_time{
		font-size: 26rpx;
		color: #9e9e9e;
		padding: 0rpx 30rpx 30rpx;
	}
	// .onekey {
	// 	background: linear-gradient(to right, #00ca88, #00BCD4);
	// 	color: #fff;
	// 	padding: 15rpx 0;
		
	// 	text-align: center;
	// 	font-size: 24rpx;
	// 	border-radius: 0 0 22rpx 22rpx;
		
	// }
	.operate{
		padding: 0px 16px 16px;
	}
	.onekey {
		background: linear-gradient(to right, #00ca88, #00BCD4);
		color: #fff;
		padding: 15rpx;
		// font-weight: bold;
		border-radius: 10rpx;
		text-align: center;
		font-size: 24rpx;
		width: 48%;
	}
	
	.hoversubmit {
		background: #f7f7f7;
		color: #acacb3;
	}
	.circle{
		position: absolute;
		right: -14rpx;
		top: -14rpx;
		background: #fff;
		border-radius: 50%;
	}
	.imgs_arrow{
		position: absolute;
		// top: 300rpx;
		width: 92%;
		margin: 0 30rpx;
		.arrow{
			background: #0000007d;
			border-radius: 50%;
			padding: 10rpx;
		}
	}
}

.dygbhg {
			background: #ffffff;
			border-radius: 15rpx 15rpx 0 0;
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			box-shadow: 0px 0px 10px #00000024;
			display: flex;
			align-items: center;
			justify-content: space-evenly;
		}
		.whole{
			width: 45%;
			height: 88rpx;
			display: flex;
			color: #ffffff;
			align-items: center;
			justify-content: center;
			background: #f3f3f3;
			font-weight: bold;
			border-radius: 60rpx;
			color: #3d7eff;
		}
		.distinguish {
			width: 45%;
			height: 88rpx;
			display: flex;
			color: #ffffff;
			align-items: center;
			justify-content: center;
			background: #3d7eff;
			font-weight: bold;
			border-radius: 60rpx;
			margin: 38rpx 0;
			margin-left: 4%;
		}
		
		/* 全屏轮播  start*/
		.card-swiper {
			height: 100vh !important;
		}
		
		.card-swiper swiper-item {
			width: 750rpx !important;
			left: 0rpx;
			box-sizing: border-box;
			overflow: initial;
			background: #000;
		}
		
		.card-swiper swiper-item .swiper-item {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100%;
			background: #000;
		}
		
		.card-swiper swiper-item.cur .swiper-item {
			transform: scale(1);
			transition: all 0.2s ease-in 0s;
			will-change: transform;
		}
</style>
