<template>
	<view class="draw-container">
		<view class="content" id="content" >
			<scroll-view id="scrollview" scroll-y="true" :scroll-with-animation="true"
			    :scroll-top="scrollTop">
				<view id="allmsgview">
					<message-show :msgType="'draw'" v-for="(message,index) in messages" :key="index" v-bind:message="message" :msgid="index" 
						@handleAd="handleAd" @redraw="handleRedraw" @handleShareImage="handleShareImage"></message-show>
				</view>
			</scroll-view>
		</view>
		<view class="foot">
			<view class="session-view">
				<!-- <view class="new" @click="handleCreateSession">
					换个话题
				</view> -->
				<button class="all" @click="handleShowAll">
					我的图库
				</button>
				|
				<button class="new" @click="handleDelAll">
					重新画图
				</button>
				|<!-- open-type="share" @click="handleShareSession"-->
				<button id="shareSessionBtn" class="shareSession" open-type="share" >
					分享
				</button>
			</view>
			<chat-input :disabled="chatStatus === 1" @send-message="getInputMessage" :placeholder='placeholder' ></chat-input>
		</view> 
		<session-list ref="sessionlist" :allsessions="allsessions" :sessionOver="sessionOver"
			@loadMoreSession="loadMoreSession" 
			@handleDelAll="handleDelAll"
			@handleDelSesstion="handleDelSesstion"
			@changeSession="changeSession"
		></session-list>
		<canvas-popup ref="imgpopup" :imgsrc="shareimgurl" :message="imgQuestion"></canvas-popup>
	</view>
</template>

<script>
	
	import chatInput from '../components/chatinput.vue';
	import messageShow from '../components/messageshow.vue';
	import sessionList from '../components/sessionlist.vue'
	import canvasPopup from '../components/canvaspopup.vue'
	import { DRAW_STATUS } from '@/common/enum.js'
	import { orderBy } from 'lodash'
	import { chatSessionList, createChatSession, delChatSession, adSuccess } from '@/api/index.js'
	import { draw, redraw, getGrawHistory, getGrawResult, drawLike, drawDislike } from '@/api/draw.js'
	import { drawDefaultMsg, msgOver, msgSensitive } from "@/common/config.js"
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'

	var app = getApp();
	export default {
		data() {
			return {
				placeholder: '请输入绘画意图！',
				messages: [drawDefaultMsg],
				chatStatus: 0,
				timer: null,
				allsessions: [],
				curSessionId: 0,
				page: 1,
				sessionOver: false,
				scrollTop: 0,
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				videoAd: null,
				shareimgurl: '',
				imgQuestion: ''
			};
		},
		computed: {
			...mapState(['userId', 'settings', 'chatType'])
		},	
		components: {
			chatInput,
			messageShow,
			sessionList,
			canvasPopup
		},
		onLoad(option) {
			clearTimeout(this.timer)
			this.getSessionList()
			wx.showShareMenu({
				withShareTicket: true,
				//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus: ["shareAppMessage", "shareTimeline"]
			})
			// test 区域
			// this.getGrawList()
			// this.getGrawProgress(13)
			// this.addMessage('AI正在绘图，请稍候', 'WAITING', false, '前面3人排队，预计3分钟')
			
			const that = this
			// 在页面onLoad回调事件中创建激励视频广告实例
			if (wx.createRewardedVideoAd) {
				let videoAd = wx.createRewardedVideoAd({
					adUnitId: 'adunit-25c0b601b55de917'
				})
				this.videoAd = videoAd
				videoAd.onLoad(() => {})
				videoAd.onError((err) => {})
				videoAd.onClose((res) => {
					console.log('广告播放结束', res);
					if (res && res.isEnded) {
						// 正常播放结束，可以下发游戏奖励
						adSuccess().then((rst) => {
							if (rst.data && rst.data.timesByDay <= that.settings.ad.limitTimesByDay) {
								wx.showToast({
									title: `恭喜您，获得${that.settings.ad.addTimes}点算力`,
									icon: 'none',
									duration: 2000
								})
							}
						})
					} else {
						// 播放中途退出，不下发游戏奖励
					}
				})
			}
		},
		methods: {
			startToScroll(time = 600) {
				setTimeout(() => {
					this.scrollToBottom();
				}, time)
			},
			scrollToBottom: function () {
				var that = this;
				var query = uni.createSelectorQuery().in(this);;
			    query.select('#allmsgview').boundingClientRect();
				query.select('#scrollview').boundingClientRect();
			
				query.exec(function (res) {
					that.style.mitemHeight = 0;
					that.style.mitemHeight = res[0].height
					const scrollHeight = res[1].height
					if (that.style.mitemHeight > scrollHeight) {
						that.scrollTop = that.style.mitemHeight - scrollHeight;
					}
				});
			},
			handleAd() {
				// 用户触发广告后，显示激励视频广告
				this.videoAd.show().catch(() => {
				    // 失败重试
				    this.videoAd.load()
						.then(() => this.videoAd.show())
						.catch(err => {
							console.log('激励视频 广告显示失败')
						})
				})
			},
			handleShareImage(message) {
				console.log('message', message)
				this.shareimgurl = message.content
				this.imgQuestion = message.description
				this.$refs.imgpopup.showPopup()
			},
			getSessionList: async function() {
				wx.showLoading()
				const res = await chatSessionList(this.page, 20, this.chatType)
				wx.hideLoading()
				if (res.code === 0 && res.data) {
					this.sessionOver = res.data.list.length < 20
					this.allsessions = this.allsessions.concat(res.data.list)
					if (this.allsessions.length) {
						if (this.messages.length === 1 && this.page === 1) {
							this.curSessionId = res.data.list[0].id
							await this.getGrawHistory(this.curSessionId)
						}
					} else {
						// 若为空，则新建一个话题
						await this.createNewSession(false);
					} 
				} 
			},
			loadMoreSession() {
				this.page++
				this.getSessionList()
			},
			changeSession(item) {
				this.curSessionId = item.id;
				this.getGrawHistory()
				// this.$refs.popup.close()
				this.$refs.sessionlist.handleClose()
			},
			handleDelSesstion(item) {
				const that = this
				wx.showModal({
					title: '提示',
					content: '确定删除该会话吗？',
					success (res) {
					    if (res.confirm) {
					       that.deleteSession(item.id)
					    }
					}
				})
			},
			// 新开启一个会话
			handleDelAll: function() {
				if (this.chatStatus === 1) {
					wx.showToast({
						icon: 'none',
						title: 'AI绘图过程中, 请勿重新画图!',
						duration: 2000
					})
					return
				}
				
				// this.messages = [{
				// 	user: 'ai',
				// 	content: '欢迎加入AI降临派，有什么我可以帮助你的吗？'
				// }];
				this.messages = [drawDefaultMsg]
				this.chatStatus = 0
				this.createNewSession(true)
			},
			handleShowAll() {
				this.$refs.sessionlist.handleShowAll()
			},
			handleShareSession() {
				wx.showToast({
					// icon: 'success',
					title: '功能建设中!',
					duration: 1500
				})
			},
			async createNewSession (showToash = true) {
				const res = await createChatSession(this.chatType)
				if (res.code === 0) {
					this.curSessionId = res.data.id
					this.allsessions.unshift(res.data)
					showToash && wx.showToast({
						icon: 'success',
						title: '好的,请提问!',
						duration: 1500
					})
				}
			},
			// 删除会话
			async deleteSession (id) {
				const res = await delChatSession(id)
				if (res.code === 0) {
					const index = this.allsessions.findIndex(m => m.id === id)
					this.allsessions.splice(index, 1)
					// 删除的是当前的会话，重新拉取会话历史
					if (this.curSessionId === id) {
						this.curSessionId = this.allsessions[0].id
						// this.getChatHistory()
					}
				}
			},
			getInputMessage (message) { //获取子组件的输入数据
				this.addQuestion(message.content);
				this.toDraw(message.content);
			},
			addQuestion (desc) {
				this.messages.push({
					user: 'customer',
					content: desc
				});
			},
			/**
			 * TODO 参数改为 message
			 */
			addImageInfo(src, id, description) {
				const temp = {
					user: 'ai',
					id,
					content: src,
					description,
					status: 'FINISHED',
					type: 'image'
				}
				this.messages.splice(this.messages.length -1, 1, temp);
				
				this.startToScroll()
			},
			addMessage (msg, status = 'WAITING', replace = false, content2 = '') {
				const temp = {
					user: 'ai',
					content: msg,
					content2,
					status
				}
				if (replace) {
					this.messages.splice(this.messages.length -1, 1, temp);
				} else {
					this.messages.push(temp);
				}
				this.startToScroll()
			},
			handleRedraw(id) {
				this.reDraw(id)
			},
			async toDraw(desc) {
				this.chatStatus = 1
				this.addMessage(`AI连接中`, 'WAITING')
				
				const res = await draw(this.curSessionId, desc)
				
				this.dealDrawResult(res)
			},
			async reDraw(id) {
				if (this.chatStatus === 1) {
					wx.showToast({
						icon: 'none',
						title: '绘图过程中, 请稍候重新生成!',
						duration: 1500
					})
					return
				}
				
				this.chatStatus = 1
				this.addMessage(`AI连接中`, 'WAITING')
				const res = await redraw(id)
				this.dealDrawResult(res)
			},
			/**
			 * 处理绘图或者重绘的结果
			 * @param {Object} res 绘图或者重绘的返回结果
			 */
			dealDrawResult(res) {
				if (res.code === 0) {
					this.getGrawProgress(res.data.id)
				} else if (res.code == 30004) {
					this.chatStatus = 0
					this.addMessage(msgOver, 'OVER', true);
				} else if (res.code == 30005) {
					this.chatStatus = 0
					this.addMessage(msgSensitive, 'DEFAULT', true);
				} else if (res.code === 30007){
					this.chatStatus = 0
					this.addMessage(`正在有其他绘画任务进行中，请稍候再试`, 'DEFAULT', true)
				} else {
					// 其他状态处理
					this.chatStatus = 0
					this.addMessage(`网络异常，${res.code}`, 'DEFAULT', true)
				}
			},
			async getGrawProgress(id) {
				// description: "一个在海边的捡海螺的小男孩"
				// id: 12
				// imageUrl: null
				// progress: {ahead: 1, time: 9146}
				// status: "PROMPTING"
				// type: "NORMAL" // 类型，NORMAL：普通，REGEN：重绘，VIP：会员绘制，VIP_REGEN：会员重绘
				const res = await getGrawResult(id)
				if (res.code === 0) {
					const status = res.data.status
					if (status === DRAW_STATUS.FINISHED) {
						// 绘制完成
						this.chatStatus = 0
						const isSensitive = res.data.isSensitive
						if (isSensitive) {
							this.addMessage(`AI的回答内容涉及敏感词汇，无法显示，敬请谅解。`, 'FINISHED', true)
						} else {
							this.addImageInfo(res.data.imageUrl, res.data.id, res.data.description)
						}
					} else if (status === DRAW_STATUS.CANCELED) {
						// 绘制取消
						this.chatStatus = 0
						this.addMessage('服务异常！', 'CANCELED', true)
					} else if (status === DRAW_STATUS.PROMPTING) {
						// 等待绘制 (status === DRAW_STATUS.DRAWING || )
						const progress = res.data.progress
						const content2 = `前面还有${progress.ahead}人等待，预计时间${ Math.ceil(progress.time/1000)}秒`
						this.addMessage(`AI正在绘图，请稍候`, 'PROMPTING', true, content2)
						this.setRequery(id, progress.time)
						// 根据剩余时间，设置setTimeout
					} else {
						// 等待绘制 (status === DRAW_STATUS.DRAWING || status === DRAW_STATUS.VALIDATING)
						const progress = res.data.progress
						this.addMessage(`AI绘图完成，图片生成中，请稍候`, 'WAITING', true)
						this.setRequery(id, progress.time)
						// 根据剩余时间，设置setTimeout
					}
				}
			},
			/**
			 * 设置一段时间后重新查询 
			 */ 
			setRequery(id, time) {
				if (this.timer) {
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					this.getGrawProgress(id)
				}, time + 2000)
			},
			async getGrawHistory() {
				const res = await getGrawHistory(this.curSessionId)
				if (res.code === 0) {
					const temps = [drawDefaultMsg]
					const list = orderBy(res.data.list, ['id'])
					// "id": 2, // 绘画ID
					// "description": "一个在海边的捡海螺的小男孩", // 描述
					// "status": "PROMPTING", // 状态，PROMPTING：正在生成prompt，DRAWING：正在绘制，FINISHED：完成，CANCELED：中断
					// "type": "NORMAL", // 类型，NORMAL：普通，REGEN：重绘，VIP：会员绘制，VIP_REGEN：会员重绘
					// "imageUrl": "https://xxxxxxx" // 图片地址
					// isSensitive: false
					list.map(m => {
						let { id, description, imageUrl, status, liked, isSensitive } = m
						const que = {
							user: 'customer',
							content: description
						}
						let content = ''
						let type = 'common'
						if (status === DRAW_STATUS.CANCELED) {
							content = '请求异常'
						} else if (status === DRAW_STATUS.FINISHED) {
							content = imageUrl
							type = 'image'
						} else {
							// DRAW_STATUS.DRAWING || DRAW_STATUS.PROMPTING || DRAW_STATUS.VALIDATING
							content = 'AI还在绘制中, 请稍候再来' 
							status = 'DEFAULT'
						}
						if (isSensitive) {
							content = 'AI的回答内容涉及敏感词汇，无法显示，敬请谅解。'
						}
						let ans = {
							user: 'ai',
							content, type, status, id, description, liked
						}
						temps.push(que)
						temps.push(ans)
					})
					this.messages = temps
					this.startToScroll()
				}
			},
			onShareAppMessage (obj) {
				let	title = '我刚用AI画了一张画, 你们也来看看'
				let	path = `/pages/ai/share/drawshare?uid=${this.userId}&sid=${this.curSessionId}`;
				console.log('path', path);
				return { title,	path };
			},
		},
		onHide() {
			clearTimeout(this.timer)
		},
		onUnload() {
			clearTimeout(this.timer)
		}
	}
</script>

<style lang="less" scoped>
.draw-container {
	background-color: @mainBg;
	height: 100%;
	.content {
		height: 100%;
		display: flex;
		flex: 1;
		padding-bottom: 170rpx;
		box-sizing: border-box;
		#scrollview {
			height: 100%;
				
			#allmsgview {
				padding-bottom: 40rpx;
			}
		}
	}
	.foot {
		position: fixed;
		width: 100%;
		height: 170rpx;
		min-height: 170rpx;
		left: 0px;
		bottom: 0px;
		overflow: hidden;
		background-color: #33373f;
		padding: 4px 20rpx 20rpx;
		box-sizing: border-box;
		.session-view {
			height: 40rpx;
			padding: 0rpx 0rpx 16rpx;
			display: flex;
			justify-content: center;
			color: #efefef;
			button {
				border-radius: 4rpx;
				padding: 0 8rpx;
				background: none;
				color: #FFF;
				font-size: 14px;
				line-height: 1.5;
				border: none;
				text-align: right;
				display: block;
				display: flex;
				margin: inherit;
				&::after {
					content: none;
				}
				
				&:active {
					color: @mainColor;
				}
			}
			.new {
				padding-right: 24rpx;
				padding-left: 24rpx;
				// border-left: 1px solid;
			}
			.all {
				padding-right: 24rpx;
				padding-left: 24rpx;
			}
			.shareSession {
				padding-right: 24rpx;
				padding-left: 24rpx;
				// border-left: 1px solid;
			}
		}
	}
}
</style>
