<template>
	<view class="uni-column">
		<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" :isShare="true"
					@fullscreen="handleFullscreen"></message-show>
				</view>
			</scroll-view>
		</view>
		<view class="chat-enter" >
			<button class="start-btn" type="primary" plain="true" @click="gotoDraw">我也来试试</button>
		</view>
	</view>
</template>

<script>
	
	import messageShow from '../components/messageshow.vue';
	// import { Client } from '@stomp/stompjs
	import { DRAW_STATUS } from '@/common/enum.js'
	import { orderBy } from 'lodash'
	import { getGrawHistory } from '@/api/draw.js'
	import { curVersion, drawDefaultMsg } from '@/common/config.js'
	import { CHAT_TYPE } from '@/common/enum.js'
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	let stompClient = ''

	var app = getApp();
	export default {
		data() {
			return {
				timer: null,
				chatStatus: 0,
				curSessionId: 0,
				showBtn: false,
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				messages: [],
				fromUserId: '',
				mdcontent: '',
				fpcontent: ''
			}
		},
		computed: {
			...mapState(['userId', 'chatToken', 'settings', 'version'])
		},	
		components: {
			messageShow
		},
		onLoad(option) {
			console.log('option', option.uid, option.sid);
			if (option.uid && option.uid != 'undefined') {
				this.setShareId(option.uid)
			}
			this.curSessionId = option.sid
			if (!this.chatToken || curVersion !== this.version) {
				this.$store.dispatch('login').then(rst => {
					this.getGrawHistory()
				})
			} else {
				this.getGrawHistory()
			}
		},
		created: function () { 
			const res = app.globalData.systemInfo;
			this.style.pageHeight = res.windowHeight;
			
			wx.showShareMenu({
				withShareTicket: true,
				//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus: ["shareAppMessage", "shareTimeline"]
			})
		},
		mounted() {
		},
		methods: {
			...mapMutations(['setShareId', 'setVersion', 'setChatType']),

			async gotoDraw() {
				this.setChatType(CHAT_TYPE.DRAW)
				uni.navigateTo({
					url: '/pages/ai/draw/draw'
				});
			},
			startToScroll(time = 1000) {
				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
					console.log(res[0].height, res[1].height );
					if (that.style.mitemHeight > scrollHeight) {
						that.scrollTop = that.style.mitemHeight - scrollHeight;
					}
				});
			},
			addQuestion (desc) {
				this.messages.push({
					user: 'customer',
					content: desc
				});
			},
			addImageInfo(src, id) {
				const temp = {
					user: 'ai',
					id,
					content: src,
					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()
			},
			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 = 'WAITING'
						}
						if (isSensitive) {
							content = 'AI的回答内容涉及敏感词汇，无法显示，敬请谅解。'
						}
						let ans = {
							user: 'ai',
							content, type, status, id, description, liked
						}
						temps.push(que)
						temps.push(ans)
					})
					list.length && (this.curDrawId = list[list.length - 1].id)
					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 };
			},
		}
	}
</script>

<style lang="less" scoped>
	.uni-column {
		height: 100%;
		background-color: #33373f;
		display: flex;
		flex-direction: column;
	
		.content {
			height: 100%;
			display: flex;
			flex: 1;
			padding-bottom: 170rpx;
			box-sizing: border-box;
			#scrollview {
				height: 100%;
					
				#allmsgview {
					padding-bottom: 40rpx;
				}
			}
		}
		.chat-enter {
			position: fixed;
			width: 100%;
			padding-top: 20rpx;
			bottom: 60rpx;
			color: #FFF;
			font-size: 28rpx;
			text-align: center;
			box-sizing: border-box;
			.chat-desc {
				padding-bottom: 20rpx;
			}
			.start-btn {
				border-color: @mainColor;
				background-color: @mainColor;
				color: #FFF;
				width: 320rpx;
				padding: 6rpx 0;
				font-size: 30rpx;
				border-radius: 10rpx;
			}
		}
		.uni-popup .uni-popup__wrapper.center {
			width: 100%;
			.fullscreen {
				height: 100vh;
				width: 100%;
				padding: 0 0rpx 80rpx;
				background-color: @mainBg;
				overflow: auto;
				position: relative;
				box-sizing: border-box;
				.btn-view {
					position: fixed;
					bottom: 0;
					height: 80rpx;
					width: 100%;
					display: flex;
					justify-content: space-around;
					align-items: center;
					background-color: darken(@mainBg, 5%);
					.btn {
						color: #ededed;
						width: 180rpx;
						line-height: 60rpx;
						&:active {
							color: @mainColor;
						}
					}
				}
				
			}
		}
	}
</style>
