<template>
	<view style="background-color: #F6F7FD;">

		<!-- <view class="storeName" style="padding-top:var(--status-bar-height) ;">
			<u--image src="/static/right.png" width="50rpx" height="50rpx" @click='backFn'></u--image>
			<view class="" @click="timeFn">
				{{timeFn()}}
			</view>
			<view class="">

			</view>
		</view> -->

		<!-- 消息 -->
		<view class="content" @click="showPlus=false" id="content">
			<view class="">
				<u-loadmore :status="status" />
			</view>
			<!--  -->
			<view class="task-li" v-for="item,index in list" :key="index">

				<!-- 对方消息 -->
				<view v-if="formId==item.fromUser.id">
					<view class="task-li-r">
						<view class="" style="margin-right: 10rpx;">
							<u--image :showLoading="true" :src="a" shape="circle" width="40px" height="40px"></u--image>
						</view>
						<view @longpress="copyText(item.content)" class="task-li-content" v-if="item.type=='text'"
							style="margin-right: 10rpx;">
							{{item.content}}
						</view>
						<!-- 图片 -->
						<view class="task-li-content" v-if="item.type=='image'" style="margin-right: 10rpx;"
							@tap="showOverLayFn(item.content,item.type)">
							<image :src="item.content" style="width:200rpx" mode="widthFix"></image>
						</view>
						<!-- 视频 -->
						<view class="task-li-content" v-if="item.type=='video'"
							style="margin-right: 10rpx;position: relative;"
							@tap="showOverLayFn(item.content,item.type)">
							<u--image :showLoading="true" :src="a" width="100px" height="80px"></u--image>
							<view class="yl-text">
								点击预览
							</view>
							<!-- <video :src="item.content" @loadedmetadata="onVideoLoaded" controls id="vi1"
							style="width: 400rpx; height: 100px;"></video> -->
							<!-- <image src="item.content" style="width:200rpx" mode="widthFix"></image> -->
							<!-- <canvas canvas-id="videoCanvas1" style="width: 100px; height: 100px;"></canvas> -->
						</view>

					</view>
					<view class="send-time">
						{{item.sendTime}}
					</view>
				</view>
				<!-- 我的消息 -->
				<view class="task-li-l" v-if="true">

					<!-- 文字 -->
					<view class="task-li-content" @longpress="copyText(item.content)" v-if="item.type=='text'"
						style="margin-right: 10rpx;">
						{{item.content}}
					</view>
					<!-- 图片 -->
					<view class="task-li-content" v-if="item.type=='image'" style="margin-right: 10rpx;"
						@tap="showOverLayFn(item.content,item.type)">
						<image :src="item.content" style="width:200rpx" mode="widthFix"></image>
					</view>
					<!-- 视频 -->
					<view class="task-li-content" v-if="item.type=='video'"
						style="margin-right: 10rpx;position: relative;" @tap="showOverLayFn(item.content,item.type)">
						<u--image :showLoading="true" src="/static/YL1.png" width="100px" height="80px"></u--image>
						<view class="yl-text">
							点击预览
						</view>
					</view>
					<view class="">
						<u--image :showLoading="true" :src="a" shape="circle" width="40px" height="40px"></u--image>
					</view>
				</view>




			</view>
			<!-- 本地 -->
			<view v-if="local">
				<view class="localTask" v-if="localType=='video'">
					<view class="task-li-content" style="margin-right: 10rpx;">
						<video :src="local" controls id="vi1" style="width: 400rpx; height: 100px;"></video>
						<u-line-progress :percentage="progress" activeColor="#19BE6B"></u-line-progress>
						<!-- <canvas canvas-id="videoCanvas1" style="width: 100px; height: 100px;"></canvas> -->
					</view>
					<view class="" style="margin-right: 10rpx;">
						<u--image :showLoading="true" shape="circle" :src="a" width="40px" height="40px"></u--image>
					</view>
				</view>

				<view class="localTask" v-if="localType=='image'">
					<view class="task-li-content" style="margin-right: 10rpx;">
						<!-- 	<image :src="local" controls id="vi1" style="width: 400rpx; height: 100px;"></image> -->
						<image :src="local" style="width:200rpx" mode="widthFix"></image>
						<u-line-progress :percentage="progress" activeColor="#19BE6B"></u-line-progress>
					</view>
					<view class="" style="margin-right: 10rpx;">
						<u--image :showLoading="true" shape="circle" :src="a" width="40px" height="40px"></u--image>
					</view>
				</view>
			</view>

			<view style="height: 50px;background-color: #F6F7FD;">


			</view>
		</view>
		<!-- 底部 -->

		<view class="bottom">
			<!--  -->
			<view class="send-col">
				<input type="text" class="send-ipt" @click="scrollFn(300)" v-model="value" placeholder="请输入聊天内容"
					placeholder-style="color:#DDD;" :cursor-spacing="6">

				<u--image :showLoading="true" src="/static/img/bussness/Plus.png" width="32px" height="32px"
					@click="showPlusFn"></u--image>

				<button class="send" @tap="sendFn">发送</button>
			</view>
			<!-- 发送照片 -->
			<view class="plus" v-if="showPlus">
				<view class="plus_li">
					<u--image :showLoading="true" src="/static/img/bussness/XC.png" width="120rpx" height="120rpx"
						@click="choseImgFn"></u--image>
					<text>图片</text>
				</view>
				<view class="plus_li">
					<u--image :showLoading="true" src="/static/img/bussness/SP.png" width="120rpx" height="120rpx"
						@click="choseVideoFn"></u--image>

					<text>视频</text>
				</view>
				<!-- asdas -->
			</view>

		</view>
		<!-- 遮罩图 -->


		<u-overlay :show="show" @click="show = false">
			<view class="warp">
				<view class="rect" @tap.stop @longpress="saveImage(overLaySrc)" v-if="overLayType=='image'">

					<image :showLoading="true" style="width: 80vw;" mode="widthFix" :src="overLaySrc"></image>
				</view>
				<view class="rect" @tap.stop v-if="overLayType=='video'">
					<video :src="overLaySrc"></video>
				</view>
			</view>
		</u-overlay>

	</view>
</template>

<script>
	// import request from "@/api/index.js"
	import {
		bindScoket,
		sendMsgApi
	} from "@/api/bussness.js"
	export default {
		data() {
			return {
				a: "https://img1.baidu.com/it/u=716638254,3920932970&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1695920400&t=aeec3d0e86c23759d5f82b3757e9b442",
				list: [],
				value: "",
				showPlus: false,
				num: 0,
				flags: true,
				scollNum: 999999999999,
				client_id: "",
				formId: "",
				name: "",
				status: "lodemore",
				page: 1,
				limit: 10,
				formUser: "",
				show: false,
				overLaySrc: "",
				overLayType: "",
				canvasContext: null,
				timer: "",
				local: "",
				localType: "",
				progress: "",
				showNotice: false

			}
		},
		methods: {
			timeFn(time) {
				// 1695722299000
				const currentDate = new Date(); // 当前日期对象
				const targetDate = new Date(1695722299000);
				if (this.isSameDay(currentDate, targetDate)) {
					const hours = targetDate.getHours(); // 小时
					const minutes = targetDate.getMinutes(); // 分钟
					return hours + ':' + minutes;

				} else if (this.isYesterday(currentDate, targetDate)) {
					return '昨天';
				}
				const month = targetDate.getMonth() + 1; // 月份（注意月份从0开始，需要加1）
				const day = targetDate.getDate(); // 日期
				return month + '月' + day + '日';


			},
			isSameDay(date1, date2) {
				return (
					date1.getFullYear() === date2.getFullYear() &&
					date1.getMonth() === date2.getMonth() &&
					date1.getDate() === date2.getDate()
				);
			},
			isYesterday(currentDate, targetDate) {
				const yesterday = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() - 1);
				return this.isSameDay(yesterday, targetDate);
			},
			saveImage(src) {
				uni.saveImageToPhotosAlbum({
					filePath: src,
					success() {
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						});
					},
					fail() {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			},
			copyText(value) {
				const text = value;
				uni.setClipboardData({
					data: text,
					success() {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						});
					}
				});
			},
			backFn() {
				uni.navigateBack()
			},

			showOverLayFn(src, type) {
				this.show = true
				this.overLaySrc = src
				this.overLayType = type
			},
			getListFn() {
				request("POST", "enterprise/im/getMessageList", {
					limit: this.limit,
					page: this.page,
					toContactId: this.formId,
				}).then(res => {
					if (res.data.data.length == 0) {
						this.status = "nomore"
						return
					}
					this.list.unshift(...res.data.data)
					this.status = "loadmore"
				}).catch(err => {
					console.log(err, "获取消息列表失败")
				})
			},
			scrollFn(time) {
				this.scollNum += 500
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: this.scollNum,
					});
				}, time ? time : 100)

			},
			generateRandId() {
				var d = new Date().getTime();
				var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
					var r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return (c == "x" ? r : r & 0x3 | 0x8).toString(16);
				});
				return uuid;
			},
			sendFn() {
				if (!this.value) return
				this.num++
				this.flags = !this.flags
				request("POST", "enterprise/im/sendMessage", {
					content: this.value,
					extends: null,
					fileName: "",
					fileSize: 0,
					file_cate: 0,
					file_id: 0,
					fromUser: {
						...this.fromUser
					},
					from_user: this.fromUser.id,
					id: this.generateRandId(),
					is_group: 0,
					is_read: 0,
					sendTime: Date.now(),
					status: "going",
					toContactId: this.formId,
					type: "text",
				}).then(res => {
					console.log("发送消息成功")
					// this.list.push(res.data.data)
				}).catch(err => {
					console.log(err, "发送消息失败")
				})

				this.value = ""
				this.scrollFn(100)



			},
			login() {
				return
				// request("POST", "common/Pub/login", {
				// 	account: 13800000006,
				// 	password: "123456",
				// 	rememberMe: false,
				// }).then(res => {
				// 	uni.setStorageSync("token", (res.data.data.authToken))
				// 	uni.setStorageSync("userinfo", JSON.stringify(res.data.data.userInfo))

				// })
			},
			showPlusFn() {
				this.showPlus = !this.showPlus
				this.scrollFn(200)
			},
			choseImgFn() {
				this.login()
				let time = Date.now()
				let that = this
				// https://im.raingad.com/common/upload/uploadFile
				uni.chooseImage({
					count: 1, // 最多可以选择的图片张数
					success: res => {
						const tempFilePath = res.tempFilePaths[0];
						const file = res.tempFiles[0]
						console.log(file)
						that.local = tempFilePath
						that.localType = 'image'
						that.showPlus = false
						that.scrollFn(200)
						const uploadTask = uni.uploadFile({
							url: "https://ceshi-im.lihaink.cn/common/upload/uploadFile",
							filePath: tempFilePath, // 选择的图片文件路径
							name: 'file',
							header: {
								"Authorization": uni.getStorageSync("token")
							},
							formData: {
								message: JSON.stringify({
									"id": this.generateRandId(),
									"sendTime": Date.now(),
									"status": "going",
									"type": "image",
									// "content": "blob:https://im.raingad.com/e2ffd725-a9e7-4a01-b7da-83fd64af97a4",
									"content": `blob:${tempFilePath}`,
									"is_read": 0,
									"is_group": 0,
									"file_id": 0,
									"file_cate": 0,
									"fileName": file.name,
									"fileSize": file.size,
									"extends": null,
									"fromUser": {
										...this.fromUser
									},
									from_user: this.fromUser.id,
									toContactId: this.formId,
								})
							}, // 服务端接收文件的字段名
							success: function(uploadRes) {
								that.local = ""
								that.list.push(JSON.parse(uploadRes.data).data)

								// 处理上传成功的逻辑
							},
							fail: function(error) {
								console.log('上传失败', error);
								// 处理上传失败的逻辑
							}
						});

						uploadTask.onProgressUpdate((res) => {
							this.progress = res.progress
							console.log('上传进度', res.progress);

						});
					},
					fail: err => {
						console.log(err, "没有选择图片");
					}
				});
			},
			choseVideoFn() {
				let that = this
				uni.chooseVideo({
					sourceType: ['album', 'camera'], // 视频选择的来源，可以是相册或摄像头
					maxDuration: 600, // 视频的最大时长（单位：秒）
					camera: 'back', // 摄像头类型，可以是前置或后置
					success: res => {
						const tempFilePath = res.tempFilePath;
						that.local = res.tempFilePath
						that.localType = 'video'
						that.showPlus = false
						that.scrollFn(200)
						const uploadTask = uni.uploadFile({
							url: "https://ceshi-im.lihaink.cn/common/upload/uploadFile",
							filePath: tempFilePath, // 选择的图片文件路径
							name: 'file',
							header: {
								"Authorization": uni.getStorageSync("token")
							},
							formData: {
								message: JSON.stringify({
									"id": this.generateRandId(),
									"sendTime": Date.now(),
									"status": "going",
									"type": "image",
									// "content": "blob:https://im.raingad.com/e2ffd725-a9e7-4a01-b7da-83fd64af97a4",
									"content": `blob:${tempFilePath}`,
									"is_read": 0,
									"is_group": 0,
									"file_id": 0,
									"file_cate": 0,
									"fileName": "20210719150601_4401e.jpg",
									"fileSize": 72046,
									"extends": null,
									"fromUser": {
										...this.fromUser
									},
									from_user: this.fromUser.id,
									toContactId: this.formId,
								})
							}, // 服务端接收文件的字段名
							success: function(uploadRes) {
								that.local = ""
								that.list.push(JSON.parse(uploadRes.data).data)

								// 处理上传成功的逻辑
							},
							fail: function(error) {
								uni.showToast({
									title: '视频不能超过60s',
									duration: 2000,
									icon: 'none'
								});
								that.local = false
							}
						});

						uploadTask.onProgressUpdate((res) => {
							this.progress = res.progress
							console.log('上传进度', res.progress);

						});
					},
					fail: err => {
						uni.showToast({
							title: '视频不能超过60s',
							duration: 2000,
							icon: 'none'
						});
					}
				});
			},
		},
		onShow() {
			return
			let that = this
			this.scrollFn(500)
			this.timer = setInterval(() => {
				request("POST", "enterprise/im/getMessageList", {
					limit: 1,
					page: 1,
					toContactId: this.formId,
				}).then(res => {

					if (res.data.data[0]?.id != this.list[this.list.length - 1]?.id) {
						this.list.push(res.data.data[0])
						if (res.data.data[0].type == 'video' || res.data.data[0].type == 'image') {
							this.local = ""
						}
						// console.log(res.data.data)
					}
					// this.list.unshift(...res.data.data)
					// this.status = "loadmore"
				})
			}, 3000)
		},

		async onPullDownRefresh() {
			this.status = "loading"
			this.page++
			await this.getListFn()
			// console.log("刷新")
			uni.stopPullDownRefresh();

		},
		created() {
			let obj = {
				"user_id": 2,
				"account": "13800000002",
				"realname": "熊大",
				"avatar": "https://ceshi-im.lihaink.cn/avatar/熊大/120/2",
				"email": "xiongda@kaishanlaw.com",
				"sex": 2,
				"role": 0,
				"motto": null,
				"remark": "",
				"name_py": "xiongda",
				"setting": null,
				"is_auth": 0,
				"last_login_time": 1695720745,
				"last_login_ip": "221.182.82.214",
				"delete_time": 0,
				"status": 1,
				"qrUrl": "https://ceshi-im.lihaink.cn/scan/u/oVQ5OmjEa7zD",
				"displayName": "熊大",
				"id": 2
			}
			this.fromUser = obj
			console.log(this.fromUser)
			return
			this.getListFn()

		},
		onUnload() {
			clearInterval(this.timer)
		},
	}
</script>

<style lang="scss">
	.yl-text {
		position: absolute;
		color: black;
		top: 60%;
		left: 50%;
		transform: translateX(-50%);
		font-size: 24rpx;

	}



	// .storeName {
	// 	position: fixed;
	// 	text-align: center;
	// 	background-color: white;
	// 	font-weight: bold;
	// 	height: 80rpx;
	// 	width: 100vw;
	// 	z-index: 9;
	// 	display: flex;
	// 	align-items: center;
	// 	justify-content: space-between;
	// }

	.topflag {
		height: 80rpx;
		background-color: #F6F7FD;
	}

	.content {
		padding: 0 20rpx;
		min-height: 100vh;
		// height: 89vh;
		background-color: #F6F7FD;
		overflow: auto;
		padding-top: 10rpx;
		// padding-bottom: 50px;

		.task-li {
			margin-bottom: 20rpx;
		}

		.task-li-l {
			display: flex;
			justify-content: flex-end;
		}

		.task-li-r {
			display: flex;
		}

		.task-li-content {
			background-color: white;
			padding: 20rpx;
			border-radius: 20rpx;
			color: white;
			word-break: break-all;
			max-width: 60vw;

		}

	}

	.bottom {
		background-color: white;
		// height: 8vh;
		// padding: 20rpx;
		padding: 20rpx 0;
		position: fixed;
		box-sizing: border-box;
		// bottom: 400px;
		padding-bottom: 500px;
		/* #ifdef APP-PLUS */
		bottom: 0px;
		padding-bottom: 10px;
		/* #endif */

		.send-col {
			display: flex;
			align-items: center;
			justify-content: space-around;

			.send-ipt {
				width: 70vw;
				background-color: #F5F5F5;
				height: 60rpx;
				border-radius: 20rpx;
				padding-left: 20rpx;
			}
		}

		.send {
			background-color: #2573fb;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 6rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #1573fb;
			}
		}

		.plus {
			display: flex;
			background-color: white;
			padding: 20rpx;

			.plus_li {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin-right: 20rpx;
				flex-wrap: wrap;
			}
		}


	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {}

	.localTask {
		display: flex;
		justify-content: flex-end;
	}
</style>