<template>
	<view class="main">
		<view class="one">
			<!-- 聊天内容 -->
			<scroll-view class="scroll-view" scroll-y="true" scroll-with-animation="true"
				:scroll-into-view="scrollToView" refresher-enabled="true" :refresher-triggered="triggered"
				@refresherrefresh="getFresh">
				<view class="list-scroll-view">
					<view class="chat-ls" v-for="(item,index) in msgList" :key="index" :id="'msg'+ item._id">
						<view class="chat-time" v-if="item.time != ''">
							{{item.time}}
						</view>
						<view class="msg-m msg-left" v-if="item.speaker !=  user._id">
							<image class="user-img" :src="config.logo&&config.logo.length>0?config.logo[0].url:''">
							</image>
							<!-- 文字 -->
							<view class="message" v-if="item.msg_type =='0'">
								<view class="msg-text">{{item.content}}</view>
							</view>
							<!-- 图像 -->
							<view class="message img" v-else-if="item.msg_type =='1'" @tap="previewImg(item.content)">
								<image :src="item.content" class="msg-img" mode="widthFix"></image>
							</view>
						</view>
						<view class="msg-m msg-right" v-else-if="item.speaker == user._id">
							<u-avatar :text="formatName(user.name||user.nickname)" fontSize="22"
								randomBgColor></u-avatar>
							<!-- 文字 -->
							<view class="message" v-if="item.msg_type =='0'">
								<view class="msg-text">{{item.content}}</view>
							</view>
							<!-- 图像 -->
							<view class="message img" v-else-if="item.msg_type =='1'" @tap="previewImg(item.content)">
								<image :src="item.content" class="msg-img" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="two">
			<submit_1 @choseImg="choseImg" @inputs="inputs" @heights="heights"></submit_1>
		</view>
	</view>
</template>

<script>
	import moment from 'moment';
	import submit_1 from './common/submit_1.vue';
	export default {
		components: {
			submit_1,
		},
		data() {
			return {
				config: {},
				user: {},
				// 聊天记录
				msgList: [],
				total: 0,
				skip: 0,
				limit: 6,
				page: 0,
				// 判断是否跳到最后一条
				is_bottom: true,
				// 判断是否下拉刷新复位
				triggered: false,
				scrollToView: '', //滑动最后一条信息
				// 判断是否是选择图片刷新
				is_img: false
			}
		},
		onShow: async function() {
			const that = this;
			that.searchUser();
			that.searchConfig();
			// 判断是否是选择图片刷新
			if (!that.is_img) {
				await that.clearPage();
				await that.search()
			}
		},
		onPullDownRefresh: async function() {
			const that = this;
			that.clearPage();
			await that.search();
			uni.stopPullDownRefresh();
		},
		methods: {
			searchUser() {
				const that = this;
				try {
					const res = uni.getStorageSync('user');
					if (res) that.$set(that, `user`, res);
				} catch (e) {
					uni.showToast({
						title: err.errmsg,
						icon: 'error',
						duration: 2000
					});
				}
			},
			searchConfig() {
				const that = this;
				try {
					const res = uni.getStorageSync('config');
					if (res) that.$set(that, `config`, res);
				} catch (e) {
					uni.showToast({
						title: err.errmsg,
						icon: 'error',
						duration: 2000
					});
				}
			},
			async search() {
				const that = this;
				if (!that.user._id) return
				let info = {
					skip: that.skip,
					limit: that.limit,
					user: that.user._id
				}
				const res = await that.$api(`chat`, 'GET', {
					...info,
				})
				if (res.errcode == '0') {
					let list = [...res.data.reverse(), ...that.msgList];
					that.$set(that, `msgList`, list)
					that.$set(that, `total`, res.total)
				} else {
					uni.showToast({
						title: res.errmsg,
					});
				}
				// 跳转到最后一条数据 与前面的:id进行对照
				that.goBottom();
			},
			// 进行图片的预览
			previewImg(e) {
				const that = this;
				// 预览图片
				uni.previewImage({
					current: 0,
					urls: [e],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) +
								'张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			// 判断是否是选择图片刷新
			choseImg(e) {
				const that = this;
				that.$set(that, `is_img`, e)
			},
			//接受输入内容
			async inputs(e) {
				const that = this;
				let user = that.user
				if (user._id) {
					//时间间隔处理
					let data = {
						"user": user._id,
						"speaker": user._id,
						"content": e.message,
						"time": moment().format('YYYY-MM-DD HH:mm:ss'),
						"msg_type": e.type
					};
					// 发送给服务器消息
					let res = await that.$api(`chat`, `POST`, data);
					if (res.errcode == '0') {
						that.msgList.push(res.data);
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none'
						})
					}
					// 跳转到最后一条数据 与前面的:id进行对照
					that.goBottom();
				} else {
					uni.navigateTo({
						url: `/pagesHome/login/index`
					})
				}
			},
			//输入框高度
			heights(e) {
				const that = this;
				that.goBottom();
			},
			// 滚动到底部
			async goBottom() {
				const that = this;
				that.scrollToView = ""
				that.$nextTick(function() {
					that.scrollToView = 'msg123456789'
				})
			},
			// 下拉刷新分页
			getFresh(e) {
				const that = this;
				that.$set(that, `triggered`, true)
				that.$set(that, `is_img`, false)
				let msgList = that.msgList;
				let limit = that.limit;
				setTimeout(() => {
					if (that.total > msgList.length) {
						uni.showLoading({
							title: '加载中',
							mask: true
						})
						let page = that.page + 1;
						that.$set(that, `page`, page)
						let skip = page * limit;
						that.$set(that, `skip`, skip)
						that.$set(that, `is_bottom`, false)
						that.search();
						uni.hideLoading();
					} else {
						uni.showToast({
							title: `没有更多聊天记录了`,
							icon: 'none'
						})
					}
					that.triggered = false;
				}, 1000)
			},
			// 分页
			toPage(e) {
				const that = this;
				let list = that.list;
				let limit = that.limit;
				if (that.total > list.length) {
					uni.showLoading({
						title: '加载中',
						mask: true
					})
					let page = that.page + 1;
					that.$set(that, `page`, page)
					let skip = page * limit;
					that.$set(that, `skip`, skip)
					that.search();
					uni.hideLoading();
				} else that.$set(that, `is_bottom`, true)
			},
			// 清空列表
			clearPage() {
				const that = this;
				that.$set(that, `msgList`, [])
				that.$set(that, `skip`, 0)
				that.$set(that, `limit`, 6)
				that.$set(that, `page`, 0)
			},
			formatName(str) {
				if (str) return str.substr(0, 1) + new Array(str.length).join('');
			}
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
		overflow: hidden;

		.one {
			position: relative;
			flex-grow: 1;

			.scroll-view {

				.chat-ls {
					padding: 2vw 2vw 0 2vw;

					.chat-time {
						font-size: 24rpx;
						color: rgba(39, 40, 50, 0.3);
						line-height: 34rpx;
						padding: 10rpx 0rpx;
						text-align: center;
					}

					.msg-m {
						display: flex;
						padding: 20rpx 0;

						.user-img {
							flex: none;
							width: 80rpx;
							height: 80rpx;
							border-radius: 40rpx;
							border: 1px solid #c0c0c0;
						}

						.message {
							flex: none;
							max-width: 480rpx;
						}

						.img {
							margin: 0 20rpx;
						}

						.msg-text {
							font-size: 32rpx;
							color: rgba(39, 40, 50, 1);
							line-height: 44rpx;
							padding: 18rpx 24rpx;
							word-break: break-all;
						}

						.msg-img {
							max-width: 400rpx;
							border-radius: 20rpx;
						}

					}

					.msg-left {
						flex-direction: row;

						.msg-text {
							margin-left: 16rpx;
							background-color: var(--f1Color);
							;
							border-radius: 0rpx 20rpx 20rpx 20rpx;
						}



						.ms-img {
							margin-left: 16rpx;
						}

					}

					.msg-right {
						flex-direction: row-reverse;

						.msg-text {
							margin-right: 16rpx;
							background-color: var(--f3CColor);
							border-radius: 20rpx 0rpx 20rpx 20rpx;
						}

						.ms-img {
							margin-right: 16rpx;
						}
					}
				}
			}
		}

		.two {
			background-color: #f0f0f0;
			border-top: 1px solid rgba(39, 40, 50, 0.1);
		}
	}

	.scroll-view {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;

		.list-scroll-view {
			display: flex;
			flex-direction: column;
		}
	}

	.is_bottom {
		width: 100%;
		text-align: center;

		text {
			padding: 2vw 0;
			display: inline-block;
			color: var(--f85Color);
			font-size: var(--font14Size);
		}
	}
</style>