<template>
	<view>
		<view style="color: #fff;">
			<tn-nav-bar :isBack="isBack" backgroundColor="#26b3a0" :bottomShadow="false">MidJourney绘图</tn-nav-bar>
			<view :style="{ height: tobheight + 'px' }"></view>
		</view>
		<view v-if="showdrawing" class="template-details">
			<u-notice-bar
					:text="noticebar" step></u-notice-bar>
			<view  class="lazy-loading tn-flex justify-center align-center flex-wrap">
				<view class="preloader_1">
					<view></view>
					<view></view>
					<view></view>
					<view></view>
					<view></view>
				</view>
				<view class="drawing">
					{{drawingtitle}}
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<view v-if="showprogress" class="progress">
					<u-line-progress :percentage="percentage" activeColor="#9b59b6" height="18"></u-line-progress>
				</view>
				<!-- #endif -->
				
			</view>
		</view>
		
		<view v-if="mjurl" class="displaypage" >
			    
				<view class="generategraph">
					<!-- <u--image @load="previewload" @error="previewerror" @click="preview(mjurl)"  width="100%" height="100%" :src="mjurl" mode="widthFix" radius="8" >
						<template v-slot:loading>
						    <u-loading-icon color="#3c9cff" size="36" text="图片渲染中" textSize="18" :vertical="true"></u-loading-icon>
							
						  </template>
						<view slot="error" style="font-size: 32rpx;text-align: center;">
							图片加载失败
						</view>
					</u--image> -->
					<image @click="preview(mjurl)" show-menu-by-longpress webp :src="mjurl" @load="previewload" @error="previewerror" mode="widthFix"></image>
				</view>
				
			<block v-if="done">
				<u-subsection v-if="radiolist7.length == 2" :list="subsectionlist" mode="subsection" fontSize="15" :current="current" @change="tapsubsection"></u-subsection>
				<view class="u-demo-block">
					<view style="margin-top: 30rpx;">
						<view class="u-page__radio-item">
							<u-radio-group v-model="radiovalue7" :borderBottom="true" placement="column" 
								iconPlacement="right" @change="groupChange">
								<u-radio labelSize="18" size="22" iconSize="16" :customStyle="{marginBottom: '16px'}" v-for="(item, index) in radiolist7"
									:key="index" :label="item.name" :name="item.name">
								</u-radio>
							</u-radio-group>
						</view>
					</view>
				</view>
			</block>
			<block v-else>
				<view class="drawingdone">
					{{drawingtitle}}
				</view>
				<!-- <u-line-progress :percentage="percentage" activeColor="#3c9cff" height="18"></u-line-progress> -->
				<view class="u-flex align-center justify-center">
					<tn-circle-progress :percent="percentage" :borderWidth="18" activeColor="#3c9cff" :showPercent="true"></tn-circle-progress>
				</view>
				
			</block>	
			
			<view style="height: 100px;"></view>
		</view>
		
     <!-- 底部tabbar start-->
     <view class="tabbar footerfixed dd-glass tn-color-white" style="border-radius: 16rpx;">
     	<view class="action" @click="getisback">
     		<view class="bar-icon">
     			<view class="tn-icon-left-circle">
     			</view>
     			
     		</view>
     		<view class="">立即退出</view>
     	</view>
     	<view class="action" @click="getdownload">
     		<view class="bar-icon">
     			<view class="tn-icon-download">
     			</view>
     			
     		</view>
     		<view class="">下载/分享</view>
     	</view>
     	<view class="action" @click="parameters">
     	
     		<view class="bar-icon">
     			<view class="tn-icon-creative">
     			</view>
     			
     		</view>
     		<view class="">绘画口令</view>
     	</view>
     	<view class="action" @click="setOpen">
     		<view class="tn-flex-direction-column tn-flex-row-center tn-flex-col-center tn-button--clear-style">
     			<view class="bar-icon">
     				<view class="tn-icon-up-circle">
     				</view>
     				
     			</view>
     			<view class="">{{showopen?'已公开':'公开作品'}}</view>
     		</view>
     	</view>
		
		<view class="action" @click="createnow" style="color: #fff420;">
			<view class="bar-icon">
				<view class="tn-icon-write">
				</view>
			</view>
			<view >再次创作</view>
		</view>
     </view>
	 <wike-model v-if="signShow"
	 :authorize="false" 
	 :title="signTitle"
	 btnText="立即获取" 
	 @save="signSign"
	 @close="signShow = false"
	 ></wike-model>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import {
		API_STEROOT,
	} from '@/common/request/request';
	let asynchronous;
	export default {
		data() {
			return {
				signShow:false,
				signTitle:'',
				noticebar:[
					'精美图片需要时间打磨，预计1-2分钟左右出图',
					
					
				],
				fronid:'',
				mj_id:'',
				mj_hash:'',
				mjurl:'',
				// https://img0.baidu.com/it/u=489552572,2707768722&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500
				customButtonGroups: [{
				        text: '保存/分享',
				        backgroundColor: 'tn-cool-bg-color-8',
				        color: '#FFFFFF'
				      }, {
				        text: '立即创作',
				        backgroundColor: 'tn-cool-bg-color-8--reverse',
				        color: '#FFFFFF'
				      }],
				tobheight: 45,
				platform: this.$platform.get(),
				  subsectionlist: ['对第1张图片', '对第2张图片', '对第3张图片','对第4张图片'],
								// 或者如下，也可以配置keyName参数修改对象键名
								// list: [{name: '未付款'}, {name: '待评价'}, {name: '已付款'}],
								current: 0,
				//横向两端排列形式数据
				radiolist7: [
					
					{
						name: '进行放大使用',
						disabled: false
					},
					{
						name: '变换生成四张类似的图片',
						disabled: false
					},
				],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				radiovalue7: '进行放大使用',
				prompt:'',
				showdrawing:true,
				drawingtitle:'',
				showprogress:true,
				percentage:0,
				instruction:'进行放大使用',
				model_id:'mj',
				version:'-- v5',
				action:'',
				showopen:false,
				needCoin:0,
				done:false,
				isBack:false,
				plan:{}
			}
		},
		computed: {
			...mapGetters(['appInfo', 'userInfo','isLogin','userData'])
		},
		onUnload() {
			clearTimeout(asynchronous);
		},
		onLoad() {
			var that = this;
			if (that.platform == 'wxMiniProgram') {
				var menumtop = uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight;
				var paddingtop = uni.getSystemInfoSync().statusBarHeight + menumtop;
				that.tobheight = menumtop + paddingtop + uni.getMenuButtonBoundingClientRect().height;
			}
			// #ifdef H5
			that.noticebar.push('图片生成中请不要退出此页面，否则可能会无法生成')
			that.drawingtitle = '正在提交任务，请不要退出'
			// #endif
			// #ifdef MP-WEIXIN
			// that.noticebar.push('长时间未出图？可稍后在 我的-绘画记录 里查看')
			that.drawingtitle = '正在努力绘制中...'
			// #endif
			if (that.$Route.query.urls) {
				this.showprogress = false
				this.drawingtitle = '图片正在加载中...'
				// that.getModels()
				that.gallerydetail(that.$Route.query.urls)
			}
			if(that.$Route.query.prompt){
			that.prompt = that.$Route.query.prompt
			that.model_id = that.$Route.query.model_id
			that.version = that.$Route.query.version
			that.needCoin = that.$Route.query.needCoin
			that.action = 'imagine'
			// console.log(that.prompt);
			// #ifdef MP-WEIXIN
			that.galleryimagine()
			// #endif
			// #ifdef H5
			this.gettest()
			console.log('this.gettest()------');
			// #endif
			
			}
			that.getPlan()
			
		},
		onShow() {
			if (this.isLogin) {
				this.getUserData();
			}
		},
		methods: {
			...mapActions(['appInit', 'logout', 'getUserInfo', 'getUserData']),
			getisback(){
				if(!this.done){
					uni.showModal({
						confirmColor: '#26B3A0',
						confirmText: '立即退出',
						title: '提示',
						content: '图片生成中，退出此页面后可能无法生成',
						success(src) {
							if (src.confirm) {
								uni.navigateBack()
							}
					}
				})
				}else{
					uni.navigateBack()
				}
			},
			getModels(){
				let that = this;
				this.$http('gallery.getModels',{engine: 'mj'}).then(res => {
					if (res.code == 0) {
						
						console.log(res.data);
					}
				});
			},
			gallerydetail(id){
				let that = this;
				this.$http('gallery.detail',{id:id}).then(res => {
					if (res.code == 0) {
						this.showdrawing = false
						this.parameter = res.data
						this.prompt = res.data.prompt
						this.fronid = res.data.id
						this.mjurl = res.data.imgs_file[0]?res.data.imgs_file[0]:res.data.origin_url
						this.mj_id = res.data.mj_id
						this.mj_hash = res.data.mj_hash
						this.done = true
						this.isBack = true
						if(res.data.mj_action == 'upscale'){
							this.radiolist7.splice(0,1)
							this.radiovalue7 = '变换生成四张类似的图片'
							this.instruction = '变换生成四张类似的图片'
						}
					}else{
						
					}
				});
			},
			parameters(){
				var that = this;
				uni.showModal({
					showCancel:false,
					title:'绘画描述',
					content: that.prompt,
					confirmColor:'#26b3a0',
					confirmText:'关闭'
				})
			},
			signSign(){
				uni.navigateTo({
					url:'/pages/user/member/member'
				})
				this.signShow = false
			},
			setOpen(){
				var that = this;
				// #ifdef H5
				if(!that.done){
					uni.showToast({
						title:'图片生成中',
						icon:'none'
					})
					return;
				}
				// #endif
				// #ifdef MP-WEIXIN
				if(that.showdrawing ){
					uni.showToast({
						title:'图片生成中',
						icon:'none'
					})
					return;
				}
				// #endif
				if(that.showopen){
					uni.showToast({
						title:'图片已公开',
						icon:'none'
					})
					return;
				}
				uni.showModal({
					confirmColor: '#26B3A0',
					confirmText: '确认公开',
					title: '提示',
					content: '是否确认公开此绘画作品',
					success(src) {
						if (src.confirm) {
							that.$http('gallery.setOpen',{id:that.fronid}).then(res => {
								if (res.code == 0) {
									uni.showToast({
										title:'提交成功,等待审核'
									})
									that.showopen = true
								}
							});
						}
					}
				});
			},
			groupChange(n){
				this.radiovalue7 = n
				this.instruction = n
			},
			createnow(){
				var that = this;
				var alias = this.appInfo.number_alias ? this.appInfo.number_alias : '点数';
				var tst = '再次创作需要消耗'+that.needCoin+alias+'或消耗一次会员套餐次数';
				// #ifdef H5
				if(!that.done){
					uni.showToast({
						title:'图片生成中',
						icon:'none'
					})
					return;
				}
				// #endif
				// #ifdef MP-WEIXIN
				if(that.showdrawing){
					uni.showToast({
						title:'图片生成中',
						icon:'none'
					})
					return;
				}
				// #endif
				if (that.appInfo.time_member && that.appInfo.time_member == 1) {
					if (that.userData.vip_info && that.userData.is_validity > 0 && that.userData.vip_info.mj_used ==
						that.userData.vip_info.mj_times && this.userData.coin < that.needCoin) {
						var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
						// this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>您的绘画<span>" + alias +
						// 	"</span>不足或会员套餐内剩余绘画次数不足，无法生成绘画</p>"
						this.signTitle =
							"<p style='font-weight: 550;font-size: 16px;'>绘画需要<span style='color: #26b3a0;padding: 0 4px;'>" +
							that.needCoin + "</span><span>" + alias +
							"</span></p><p style='padding-top: 10px;'>您的绘画<span>" + alias +"</span>不足或会员套餐内剩余次数不足，无法生成绘画</p>"
						this.signShow = true
						return;
					}
					if (that.userData.is_validity == 0&&this.userData.coin < that.needCoin) {
						var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
						this.signTitle =
							"<p style='font-weight: 550;font-size: 16px;'>绘画需要<span style='color: #26b3a0;padding: 0 4px;'>" +
							that.needCoin + "</span><span>" + alias +
							"</span></p><p style='padding-top: 10px;'>您的绘画<span>" + alias +"</span>不足或会员套餐内剩余次数不足，无法生成绘画</p>"
						this.signShow = true
						return;
					}
				}else{
					if( that.userData.coin<that.needCoin){
						this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>再次创作需要<span style='color: #26b3a0;padding: 0 4px;'>"+that.needCoin+"</span><span>"+alias+"</span></p><p style='padding-top: 10px;'>您当前有<span style='color: #26b3a0;padding: 0 4px;'>"+this.userData.coin+"</span><span>"+alias+"</span>，无法生成，快去获取<span>"+alias+"</span>吧</p>"
						this.signShow = true
						return;
					}
				}
				
				
				uni.showModal({
					confirmColor: '#26B3A0',
					confirmText: '确认创作',
					title: '提示',
					content: tst,
					success(src) {
						if (src.confirm) {
							that.mjurl = ''
							that.done = false
							that.creation()
						}
					}
				});
				
			},
			creation(){
				this.percentage = 0
				this.showdrawing = true
				this.progressbar()
				if(this.instruction == '进行放大使用'){
					if(this.radiolist7.length == 2){
						this.radiolist7.splice(0,1)
					}
					this.radiovalue7 = '变换生成四张类似的图片'
					this.instruction = '变换生成四张类似的图片'
					this.action = 'upscale'
					// this.current = 0
					// #ifdef MP-WEIXIN
					// this.upscale()
					this.galleryimagine()
					this.showprogress = true
					// #endif
					// #ifdef H5
					
					this.gettest()
					// #endif
					
				}else{
					let s = {
						name: '进行放大使用',
						disabled: false
					}
					if(this.radiolist7.length == 1){
						this.radiolist7.splice(0,0,s)
					}
					// this.current = 0
					this.radiovalue7 = '进行放大使用'
					this.instruction = '进行放大使用'
					this.action = 'variation'
					// #ifdef MP-WEIXIN
					// this.variation()
					this.galleryimagine()
					this.showprogress = true
					// #endif
					// #ifdef H5
					
					this.gettest()
					// #endif
				}
				// console.log(this.current,this.mj_hash,this.mj_id,this.fronid);
			},
			// upscale(){
			// 	this.$http('gallery.upscale', {index: this.current + 1,hash: this.mj_hash,id: this.mj_id,pid: this.fronid}).then(res => {
			// 		if (res.code == 0) {
			// 			this.getAsyncResult(res.data)
			// 		}
			// 	});
			// },
			// variation(){
			// 	this.$http('gallery.variation', {index: this.current + 1,hash: this.mj_hash,id: this.mj_id,pid: this.fronid}).then(res => {
			// 		if (res.code == 0) {
			// 			this.getAsyncResult(res.data)
			// 		}
			// 	});
			// },
			
			// 绘制MJ最终调用的接口
			gettest(){
				var that = this;
				let uniacid = uni.getStorageSync("uniacid") || "";
				var chatgpturl = API_STEROOT + 'api.gallery/imagine?uniacid=' + uniacid;
				let param = {
					 prompt: that.prompt,
					 action: that.action,
					 model_id: that.model_id,
					 version: that.version,
					 id: that.mj_id,
					 index: this.current + 1,
					 // id:''
				}
				let headers = {
					'token': uni.getStorageSync("token") || "",
					'platform': this.platform,
					'Content-Type': 'application/json',
				}
				
				console.log('headers',headers);
				
				console.log('绘制MJ传递的参数：',param);
				fetch(chatgpturl, {method: 'POST',headers:headers,body: JSON.stringify(param)})
					.then(x => {
						if (x.status === 404) {
							uni.showToast({
								title:'绘制失败,请重试',
								icon:'none'
							})
							return;
						}
						if (x.status === 200) return x.body;
						throw x;
					})
					.then(x => {
						const k = x.getReader();
						return new ReadableStream({
							start(V) {
								function F() {
									k.read().then(({
										done: E,
										value: U
									}) => {
										if (E) {
											
											return;
										}
										V.enqueue(U);
										const L = new TextDecoder().decode(U);
										// console.log(L);
										// const N = JSON.parse(L)
										try {
										  const N = JSON.parse(L)
										  
										  console.log('fetch(chatgpturl）方法返回值：',N);
										  if(N.code){
										  	uni.showModal({
										  		showCancel:false,
										  		title:'提示',
										  		confirmText:'退出',
										  		content:N.detail,
										  		confirmColor:'#26b3a0',
										  		success(tay) {
										  			if(tay.confirm){
										  				uni.navigateBack()
										  			}
										  		}
										  	})
										  	return;
										  }
										  that.mjurl = N.image_url
										  if(N.progress==100){
										  	that.mj_id = N.image_id
										  	that.done = true
										  	that.percentage = 0
										  	// that.drawingtitle = '正在提交任务，请不要退出'
										  	that.isBack = true
										  	that.current = 0
										  	
										  }
										  that.percentage = N.progress
										} catch(err) {
										  console.log('JSON.parse 出错了：' + err);
										  // uni.showModal({
										  // 	confirmText:'退出',
										  // 	showCancel:false,
										  // 	confirmColor:'#26b3a0',
										  // 	title:'提示',
										  // 	content:err,
										  // 	success(tit) {
										  // 		if(tit.confirm){
										  // 			uni.navigateBack()
										  // 		}
										  // 	}
										  // })
										}
										F();
									})
									}
									F();
									}
						})
						})
						.then(x =>
							new Response(x, {
								headers: {
									'Content-Type': 'application/json'
								}
							}).text()
						);
			},
			getPlan() {
				this.$http('conf.getGroupConf', {
					group: 'system.plan'
				}).then(res => {
					if (res.code == 0) {
						this.needCoin = res.data.unlock_mj_aipainting
						this.plan = res.data;
						uni.setNavigationBarTitle({
							title: this.appInfo.site_name
						});
						// console.log(this.plan);
					}
				});
			},
			galleryimagine(){
				let that = this;
				this.progressbar()
				this.$http('gallery.imagine', {prompt: that.prompt,model_id:that.model_id,version: that.version,id: that.mj_id,
					 index: this.current + 1,action: that.action}).then(res => {
					if (res.code == 0) {
						this.getAsyncResult(res.data)
						
					}else{
						uni.showToast({
							icon:'error',
							title:res.msg
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500);
					}
				});
			},
			getAsyncResult(id){
				let that = this;
				this.$http('gallery.getAsyncResult', {
					uuid: id
				}).then(res => {
					if (res.code == 0) {
						if(res.data.done == 1){
							
							this.drawingtitle = '图片正在渲染中...'
							this.fronid = res.data.id
							this.mj_id = res.data.mj_id
							this.mj_hash = res.data.mj_hash
							this.mjurl = res.data.imgs_file[0]
							this.current = 0
							this.done = true
							this.percentage = 0
							this.isBack = true
							clearTimeout(asynchronous);
							this.getUserData();
						}else{
								asynchronous = setTimeout(() => {
									that.getAsyncResult(id)
								}, 5000);
								return;
						}
					}else{
						uni.showToast({
							icon:'error',
							title:res.msg
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500);
					}
				})
			},
			previewload(){
					this.showdrawing = false
					this.drawingtitle = '正在努力绘制中,请不要退出'
					// this.percentage = 0
				},
				previewerror(){
					this.showdrawing = false
					this.drawingtitle = '正在提交任务，请不要退出'
					// this.percentage = 0
				},
			preview(e){
				if(this.done){
					uni.previewImage({
						urls:[e]
					})
				}
			},
            tapsubsection(index){
				this.current = index
			},
			progressbar(){
				var that = this;
				if(that.percentage < 99){
					setTimeout(() => {
						that.percentage = uni.$u.range(0, 99, that.percentage + 1)
						that.progressbar()
					}, 800);
				}
			},
			//下载分享
			getdownload(){
				
				uni.showModal({
					showCancel:false,
					title:'提示',
					content:'长按图片下载/分享',
					confirmColor:'#26b3a0'
				})
			
			},
		}
	}
</script>

<style lang="scss" scoped>
	.displaypage{
		margin: 30rpx;
	}
	.generategraph {
		// width: 100%;
		// border-radius: 16rpx;
		margin-bottom: 36rpx;
		image{
			width: 100%;
			border-radius: 16rpx;
			will-change: transform;
		}
	}

	.u_radio {
		flex-direction: column;
	}
	
	/* 底部tabbar start*/
	/* 毛玻璃*/
	.dd-glass {
		width: 100%;
		backdrop-filter: blur(20rpx);
		-webkit-backdrop-filter: blur(20rpx);
	}
	
	.footerfixed {
		position: fixed;
		// margin: 20rpx;
		
		margin: 40rpx 30rpx;
		width: 92%;
		bottom: calc(env(safe-area-inset-bottom) / 2);
		;
		z-index: 999;
		// background-color: rgba(0, 0, 0, 0.15);
		background: linear-gradient(to right,#00BCD4,#00ca88);
		box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.07);
	}
	
	.tabbar {
		display: flex;
		align-items: center;
		min-height: 110rpx;
		justify-content: space-between;
		padding: 0;
		height: calc(110rpx + env(safe-area-inset-bottom) / 2);
		// padding-bottom: calc(env(safe-area-inset-bottom) / 2);
	}
	
	.tabbar .action {
		font-size: 22rpx;
		position: relative;
		flex: 1;
		text-align: center;
		padding: 0;
		display: block;
		height: auto;
		line-height: 1;
		margin: 0;
		overflow: initial;
	}
	
	.tabbar .action .bar-icon {
		width: 100rpx;
		position: relative;
		display: block;
		height: auto;
		margin: 0 auto 10rpx;
		text-align: center;
		font-size: 42rpx;
	}
	
	.tabbar .action .bar-icon image {
		width: 50rpx;
		height: 50rpx;
		display: inline-block;
	}
	
	.template-details {
		margin: 0;
		width: 100%;
		height: 100vh;
		color: #fff;
		overflow: hidden;
	}
	.lazy-loading{
		// background: #000;
		height: 100%;
	}
	.drawing{
		position: absolute;
		top: 46%;
		color: #000;
		// color: #606266;
		font-size: 18px;
	}
	.drawingdone{
		margin: 35rpx 0;
		text-align: center;
		color: #606266;
		font-size: 18px;
	}
	.progress{
		position: absolute;
		top: 52%;
		width: 60%;
	}
	.preloader_1{
	    position:absolute;
		margin-right: 65px;
		top: 42%;
		// right: 8%;
		// bottom: 18%;
		// position: fixed;
		//     right: 58%;
		//     top: 42%;
	}
	.preloader_1 view{
	    display:block;
	    bottom:0px;
	    width: 9px;
	    height: 5px;
	    background:#9b59b6;
	    position:absolute;
	    animation: preloader_1 1.5s  infinite ease-in-out;
	}  
	.preloader_1 view:nth-child(2){
	    left:11px;
	    animation-delay: .2s;  
	}
	.preloader_1 view:nth-child(3){
	    left:22px;
	    animation-delay: .4s;
	}
	.preloader_1 view:nth-child(4){
	    left:33px;
	    animation-delay: .6s;
	}
	.preloader_1 view:nth-child(5){
	    left:44px;
	    animation-delay: .8s;
	}
	@keyframes preloader_1 {
	    0% {height:5px;transform:translateY(0px);background:#9b59b6;}
	    25% {height:30px;transform:translateY(15px);background:#3498db;}
	    50% {height:5px;transform:translateY(0px);background:#9b59b6;}
	    100% {height:5px;transform:translateY(0px);background:#9b59b6;}
	}
</style>