<template>
	<view class="mainbox">
		<view class="imgs">
			<image v-for="(img,i) in images" :key="i" :src="img" mode="aspectFill" @click="previewImage(i,images)"></image>
		</view>
		<view class="con">
			<view class="title">
				<text class="tag" :style="{backgroundColor: info.isProcessCompleted==1? '#eee': info.isHandlePlatform==0&&info.isHandleStore==0 ? 'red':'#2583EB', color: info.isProcessCompleted==1? '#666':'#fff'}">
					{{info.isProcessCompleted==1? '已结束':info.isHandlePlatform==0&&info.isHandleStore==0 ? '待处理':'已处理'}}
				</text>{{info.title}}</view>
			<view>{{info.content}}</view>
			<view style="margin-top: 24rpx;color:#999999">时间：{{info.createTime || '--'}}</view>
		</view>
		<view class="con" v-show="msgList&&msgList.length>0">
			<view class="msg">
				<view v-for="(msg,i) in msgList" :key="i" :class="msg.sendType !=1?'storemsg':''" style="margin-bottom: 24rpx;">
					<view class="lable">{{msg.sendType ==2?'商家回复：':msg.sendType ==3?'平台回复：':msg.sendType ==1?'我：':''}}</view>
					<view class="imgs" v-if="msg.images">
						<image v-for="(img,i) in msg.images.split(',')" :key="i" :src="img" mode="aspectFill" @click="previewImage(i,msg.images.split(','))"></image>
					</view>
					<view class="val">{{msg.content||''}}</view>
					<view class="val x-f" style="margin-top: 10rpx;font-size: 28rpx;color:#999999;">
						<text style="margin-right: 16rpx;">{{msg.createTime || '--'}}</text>
						<!-- <u-icon name="chat" color="#999" size="48rpx" v-if="info.isProcessCompleted!=1&&(msg.sendType ==2||msg.sendType ==3)" @click="open"></u-icon> -->
					</view>
				</view>
			</view>
			<!-- <view class="mymsg">
				<view class="val">问题问题问题问题问题问题问题问题问题问题</view>
				<view class="val x-f" style="margin-top: 10rpx;font-size: 28rpx;color:#999999;"><text style="margin-right: 16rpx;">2022-12-22 12:33</text></view>
			</view> -->
		</view>
		<view class="chatbox" v-if="info.isProcessCompleted!=1">
			<u-icon name="chat" color="#999" size="48rpx"@click="open"></u-icon>
		</view>
		<u-popup :show="show" :closeable="true" @close="close">
			<view class="replybox">
				<view class="replybox-title">回复:</view>
				<view class="form-item">
					<u-upload v-if="fileList1.length>0" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" width="60" height="60":maxCount="4"></u-upload>
					<u--textarea v-model="content" placeholder="输入回复内容" border="none" count
						maxlength='300'></u--textarea>
				</view>
				<view class="replybox-footer x-bc">
					<view class="uploadbox" :style="{visibility: fileList1.length>0 ? 'hidden':'visible'}">
						<u-upload :disabled="fileList1.length>0" :fileList="fileList1" uploadIcon="photo" uploadIconColor="#666" @afterRead="afterRead" @delete="deletePic" name="1" width="24" height="24":maxCount="4"></u-upload>
					</view>
					<view class="send" @click="send">发送</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {storeComplaintDetail,storeComplaintMsg,storeComplaintMsgAdd} from "@/api/user.js"
	export default {
		data() {
			return {
				id:'',
				images:[],
				info: {},
				msgList: [],
				fileList1: [],
				show: false,
				content:'',
				replyImages: ""
			}
		},
		onLoad(option) {
			this.id = option.id
			this.getDetail()
			this.getMsg()
		},
		methods: {
			open() {
				this.content = ''
				this.fileList1 = []
				this.replyImages = ''
				this.show = true
			},
			close() {
				this.show = false
			},
			previewImage(index,images) {
				uni.previewImage({
					current: index,
					urls: images
				});
			},
			getDetail() {
				storeComplaintDetail(this.id).then(res=>{
					if(res.code == 200) {
						this.info = res.data || {}
						this.images = res.data&&res.data.images.split(',')
					} else {
						uni.showToast({
							title:res.msg,
							icon: "none"
						})
					}
				})
			},
			getMsg() {
				storeComplaintMsg({
					complaintId: this.id,
					pageNum: 1,
					pageSize: 100,
				}).then(res=>{
					if(res.code == 200) {
						this.msgList = res.rows
					} else {
						uni.showToast({
							title:res.msg,
							icon: "none"
						})
					}
				})
			},
			send() {
				const replyImages = this.getSuccessUrls(this.fileList1);
				if (replyImages === 'failed') return;
				this.replyImages = replyImages;
				if(!this.content) {
					uni.showToast({
						title: '请输入回复内容',
						icon: "none"
					})
					return
				}
				const param = {
					complaintId: this.id,
					sendType: 1,
					content: this.content,
					images: this.replyImages
				}
				storeComplaintMsgAdd(param).then(res=>{
					if(res.code == 200) {
						this.getMsg()
						this.show = false
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				})
			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: result.status,
						message: result.status == 'failed' ? '上传失败' : '',
						url: result.url
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.getStorageSync('requestPath') +'/app/common/uploadOSS', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						success: (res) => {
							if(res.statusCode == 200&&JSON.parse(res.data).code == 200) {
								resolve({
									url:JSON.parse(res.data).url,
									status: 'success'
								})
							} else {
								resolve({
									url:url,
									status: 'failed'
								})
							}
						},
						fail: (res) => {
							resolve({
								url:url,
								status: 'failed'
							})
						}
					});
				})
			},
			getSuccessUrls(list) {
			  if (!list || list.length === 0) return '';
			
			  const hasUploading = list.some(v => v.status === 'uploading');
			  const hasFailed = list.some(v => v.status === 'failed');
			
			  if (hasUploading) {
			    uni.showToast({ title: '请等待图片上传完成', icon: 'none' });
			    return 'failed';
			  }
			  if (hasFailed) {
			    uni.showToast({ title: '请检查是否有图片上传失败', icon: 'none' });
			    return 'failed';
			  }
			
			  return list.filter(v => v.status === 'success').map(v => v.url).join(',');
			},
		}
	}
</script>

<style scoped lang="scss">
	.chatbox {
		height: 80rpx;
		width: 80rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		bottom: 200rpx;
		right: 50rpx;
		z-index: 999;
		box-shadow: 0 0 20px 5px #eee;
		background-color: #fff;
	}
	.lable {
		margin-bottom: 16rpx;
		font-weight: bold;
	}
	.tag {
		padding: 5rpx 6rpx;
		font-size: 20rpx;
		color: #FFFFFF;
		background-color: red;
		border-radius: 10rpx;
		margin-right: 10rpx;
	}
	.send{
		flex-shrink: 0;
		padding: 10rpx 24rpx;
		font-size: 28rpx;
		border-radius: 28rpx 28rpx 28rpx 28rpx;
		background-color: #2583EB;
		font-weight: 500;
		font-size: 24rpx;
		color: #fff;
	}
	.replybox {
		padding: 0 24rpx 24rpx 24rpx;
		&-title {
			padding: 24rpx 0;
		}
		.form-item {
			background-color: #fff;
			border: 1rpx solid #ddd;
			border-radius: 10rpx;
			padding: 16rpx;
		}
		&-footer {
			margin-top: 24rpx;
		}
		.uploadbox {
			position: relative;
		}
	}
	.msg{
		margin-bottom: 20rpx;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
	}
	.storemsg {
		background-color: #f5f5f5;
		padding: 16rpx;
		border-radius: 16rpx;
	}
	.val {
		color:#222;
		word-break: break-all;
	}
	.mainbox {
		padding: 24rpx;
		.imgs {
			display: flex;
			flex-wrap: wrap;
			image {
				height: 150rpx;
				width: 150rpx;
				margin: 0 20rpx 20rpx 0;
			}
		}
		.con{
			display: block;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			padding: 24rpx;
			overflow: hidden;
			font-size: 28rpx;
			margin-bottom: 24rpx;
			color: #666666;
			.title {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 16rpx;
			}
		}
	}
</style>