<template>
	<view class="">
		<uni-drawer ref="drawerLeft" mode="left">
			<view class="menuTop" :style="[heightStyle]">
				<view :style="[heightStyle]" style="background:white;"></view>
				<view class="newChat">
					
					<view class="newChatBtn" @click="createNewChat">
						+ 新的聊天
					</view>
				</view>
			</view>
			<scroll-view class="menuScroll" scroll-y="true" :style="[topStyle]">
				<view class="menuItem" v-for="item in allChatList" :key="item.date" :class="item.active?'active':''" @click="() => checkChatList(item)">
					<view class="text"><uni-icons :color="item.active?'#007aff':'rgb(51,51,51)'" type="chat" size="16"></uni-icons>
					{{ item.title }}</view>
					<view @click.stop="() => removeChat(item)">
						<uni-icons v-if="allChatList.length > 1" :color="item.active?'#007aff':'rgb(51,51,51)'" type="closeempty" size="16"></uni-icons>
					</view>
				</view>
			</scroll-view>
			<view class="menuBottom">
				<view class="clearAllChat" @click="clearAllChat">
					清空所有聊天
				</view>
			</view>
		</uni-drawer>
		<view class="container">
			<view :style="[heightStyle]" style="background:white;"></view>
			<uni-nav-bar fixed :border="false" left-icon="bars" title="AIxiu" @clickLeft="showDrawer"/>
			<scroll-view 
				:scroll-with-animation="true"
				class="scorllView"
				scroll-y="true" 
				:scroll-into-view="scrollIntoView"
			>
				<view v-for="(item, index) in curChat.chatList" :key="item.time" class="chatItem" :class="item.type=='gpt'?'gpt':'user'" :id="`item${index}`">
					<view class="head" v-if="item.type == 'gpt'">
						G
					</view>
					<view class="content">
						<view class="time">{{ item.time }}</view>
						<zero-markdown-view class="markdownView" :markdown="item.data.message"></zero-markdown-view>
					</view>
					<view class="head" v-if="item.type == 'user'">
						U
					</view>
				</view>
				<view class="chatItem" v-if="loading">
					<view style="position: relative;width:100%">
						<zero-loading type="pulse" position="absolute"></zero-loading>
					</view>
				</view>
				
			</scroll-view>
			<view class="bottom">
				<textarea class="inputArea" v-model="message" disable-default-padding :always-embed="true" :adjust-position="true" cursor-spacing="60" :style="[inputArea]" placeholder="输入内容" @input="onInput" @focus="onFocus" @blur="onBlur" @linechange="onLineChange"/>
				<button class="button" :disabled="disabled" plain="true" @click="sendMessage" :style="[btnBorderColor]">
					<uni-icons type="paperplane" size="30" :color="color"></uni-icons>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { dateTimeStr } from '@/utils/index.js'; 
	export default {
		data() {
			return {
				drawerLeft: null,
				message: '',
				borderColor: '',
				textAreaHeight: 40,
				loading: false,
				scrollIntoView: '',
				statusBarHeight: 0,
				allChatList: [
					{
						id: new Date().getTime(),
						title: '新的聊天',
						active: true,
						chatList: []
					}
				]
			}
		},
		computed: {
			curChat() {
				return this.allChatList.find(item => item.active)
			},
			disabled() {
				return this.message.length <= 0
			},
			color() {
				return this.disabled?"rgba(0, 0, 0, 0.2)":"#007aff"
			},
			heightStyle() {
				return { "height": `${this.statusBarHeight}px`}
			},
			topStyle() {
				return { "top": `${this.statusBarHeight + 60}px`}
			},
			inputArea() {
				return { "border-color":`${this.borderColor}`,"height": `${this.textAreaHeight}px` }
			},
			btnBorderColor() {
				return {"border-color": `${this.color}`}
			},
		},
		onLoad(){
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight; 
			// 开启小程序原生右上角分享按钮
			uni.showShareMenu({
			  // https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share.html
			  withShareTicket: true,
			  menus: ['shareAppMessage', 'shareTimeline'],//开启转发好友和转发朋友圈按钮
			});
		},
		
		mounted(){
			this.getAllChatList()
			let that = this
			setTimeout(()=>{
				that.scrollIntoView = `item${that.curChat.chatList.length - 1}`
			},500)
			
		},
		methods: {
			// 自定义此页面的转发给好友(已经有全局的分享方法，此处会覆盖全局)
			onShareAppMessage(res) {
			  return {
			    title: 'AIxiu-做您专属的问答助手',
			    imageUrl: '/static/logo4.png'
			  }
			},
			createNewChat() {
				this.allChatList.map(i => {
					i.active = false
				})
				this.allChatList.unshift(
					{
						id: new Date().getTime(),
						title: '新的聊天',
						active: true,
						chatList: []
					}
				)
			},
			clearAllChat() {
				let that = this
				uni.showModal({
					title: '提示',
					content: '确认清空所有记录吗？',
					success: function (res) {
						if (res.confirm) {
							that.allChatList = [{
								id: new Date().getTime(),
								title: '新的聊天',
								active: true,
								chatList: []
							}]
							that.saveLocalStorage()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			removeChat(item) {
				if(this.allChatList.length <= 1) return false
				let that = this
				uni.showModal({
					title: '提示',
					content: '确认删除吗？',
					success: function (res) {
						if (res.confirm) {
							let splingsChat = that.allChatList.filter(i => i.id != item.id)
							splingsChat[0].active = true
							that.allChatList = splingsChat
							that.saveLocalStorage()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			getAllChatList() {
				let historyList = uni.getStorageSync('allChatList')
				if (historyList) {
					this.allChatList = historyList
				} else {
					let data = [
						{
							id: new Date().getTime(),
							title: '新的聊天',
							active: true,
							chatList: []
						}
					]
					uni.setStorage({
						key: 'allChatList',
						data
					})
					this.allChatList = data
				}
			},
			saveLocalStorage() {
				let data = this.allChatList
				uni.setStorage({
					key: 'allChatList',
					data
				})
			},
			checkChatList(item) {
				this.allChatList.map(i => {
					if(i.id == item.id){
						i.active = true
					} else {
						i.active = false
					}
				})
				// let that = this
				// setTimeout(()=>{
				// 	that.scrollIntoView = `item${that.curChat.chatList.length - 1}`
				// },500)
			},
			onFocus() {
				this.borderColor = "#007aff"
			},
			onBlur() {
				this.borderColor = "rgba(0, 0, 0, 0.2)"
			},
			showDrawer() {
				console.log('showshowshow')
				this.$refs.drawerLeft.open()
			},
			onInput(e) {
				//this.message = e.target.value
			},
			sendMessage() {
				this.loading = true
				let data = {
					message: this.message
				}
				this.curChat.chatList.push({
					type: 'user',
					time: dateTimeStr('y/m/d h:i:s'),
					data
				})
				if(this.curChat.title == '新的聊天'){
					this.curChat.title = this.message
				}
				let that = this
				setTimeout(()=>{
					that.scrollIntoView = `item${that.curChat.chatList.length - 1}`
				},100)
				this.allChatList.map(i => {
					if(i.id == this.curChat.id){
						i = this.curChat
					}
				})
				
				this.saveLocalStorage()
				
				this.message = ''
				uni.request({
				    url: 'https://chat.chuckchen.top/conversation', //仅为示例，并非真实接口地址。
					method: 'POST',
				    data,
				    header: {
				        'Content-Type': 'application/json'
				    },
				    success: async (res) => {
						this.curChat.chatList.push({
							type: 'gpt',
							time: dateTimeStr('y/m/d h:i:s'),
							data: {
								message: res.data.response,
								//...res.data
							}
						})
						let that = this
						setTimeout(()=>{
							that.scrollIntoView = `item${that.curChat.chatList.length - 1}`
						},100)
						this.allChatList.map(i => {
							if(i.id == this.curChat.id){
								i = this.curChat
							}
						})
						this.saveLocalStorage()
						this.loading = false
				    },
					fail() {
						uni.showToast({
							title: '请求失败',
							icon: 'error',
							duration: 2000
						})
						this.loading = false
					}
				});
			},
			onLineChange(e) {
				if(e.detail.lineCount < 5){
					this.textAreaHeight = 20 + (20 * e.detail.lineCount)
				}
			}
		}
	}
</script>

<style>
	.bottom{
		display: flex;
		position: fixed;
		bottom:0;
		left:0;
		width:100%;
		padding: 0 10px;
		box-sizing: border-box;
		align-items: center;
		justify-content: center;
		background:white;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom); 
	}
	.inputArea {
		height: 40px;
		line-height: 20px;
		border:1px solid rgba(0, 0, 0, 0.2);
		border-radius: 6px;
		padding: 10px 5px;
		box-sizing: border-box;
		margin: 10px 0;
		flex: 1;
	}
	.bottom .button{
		width:60px;
		height:40px;
		margin-left:10px;
		display: flex;
		align-items: center;
	}
	.scorllView {
		height: calc(100vh - 104px); 
		overflow: auto; 
		padding:0 6px;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom); 
		font-size: 12px;
	}
	.chatItem{
		margin: 20px 0;
		display: flex;
	}
	.chatItem:last-child {
		padding-bottom: 80px;
	}
	.head{
		width: 40px;
		height: 40px;
		border-radius: 50%;
		background: rgba(24, 160, 88, 0.28);
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.chatItem.user .head{
		background: rgba(32, 128, 240, 0.16);
	}
	.content{
		flex: 1;
		width: 300px;
	}
	.content .time{
		font-size:12px;
	}
	
	.content .markdownView{
		background: white;
		border-radius: 12px;
		margin: 6px 40px 0 6px;
		display: inline-block;
		max-width: calc(100% - 60px);
		font-size:10px;
	}
	.chatItem.user .content{
		text-align: right;
	}
	.chatItem.gpt .content .time{
		padding-left:6px;
	}
	.chatItem.gpt .content .markdownView{
		margin: 6px 40px 0 6px;
	}
	.chatItem.user .content .time{
		text-align: right;
		padding-right:6px;
	}
	.chatItem.user .content .markdownView{
		margin: 6px 6px 0 40px;
		text-align: left;
	}
	
	.menuTop{
		display: block;
		height: 60px;
		width: 100%;
	}
	.menuTop .newChat{
		display: flex;
		align-items: center;
		justify-content: center;
		position:fixed;
		height: 60px;
		background: white;
		border-bottom: 1px solid #eee;
		width:100%;
	}
	.menuTop .newChat .newChatBtn{
		width: 80%;
		padding: 6px 0;
		text-align: center;
		border: 1px dashed #007aff;
		border-radius: 4px;
		color:#333;
	}
	.menuScroll{
		position:absolute;
		top: 60px;
		bottom: 80px;
		background:white;
		text-align: center;
	}
	.menuScroll .menuItem {
		display: inline-block;
		width: 80%;
		padding: 10px;
		border: 1px solid #eee;
		color: #333;
		border-radius: 4px;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		box-sizing: border-box;
		cursor: pointer;
	}
	.menuScroll .menuItem .text{
		white-space: nowrap;
		text-overflow:ellipsis;
		overflow:hidden;
	}
	.menuScroll .menuItem.active{
		border: 1px solid #007aff;
		color: #007aff;
	}
	
	.menuBottom{
		position: fixed;
		bottom:0;
		height: 80px;
		background:white;
		width:100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.menuBottom .clearAllChat{
		width: 80%;
		border:1px solid #eee;
		padding: 6px;
		text-align: center;
		color: #333;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom); 
	}
</style>
