<template>
	<view class="content">
		<view class="intr">
			<view class="intr_top">
				<view class="intr_img">
					<image src="../../static/img/top.png" mode="widthFix"></image>
				</view>
				<view class="intr_con">
					<view>你好！</view>
					<view> 我是大卫博士品牌创始人-常来</view>
				</view>

			</view>
			<view class="intr_bottom">
				<view>如果你对我们的产品以及服务有什么意见或者建议，</view>
				<view style="margin-top:5px;">请在下方给我留言。</view>
			</view>
		</view>
		<view class="msg_box">
			<view class="msg_title">请留言</view>
			<view class="msg_con">
				<view class="msg_text">
					<textarea placeholder="说点什么吧~" auto-height placeholder-style="color:#CCCCCC;font-size:28rpx"
						v-model="value" />
				</view>
				<view class="msg_imgs">
					<view class="img_box" v-for="(item,index) in imgList" :key='index'>
						<image :src="item" class="img" @click="previewImage(imgList,index)"></image>
						<image src="../../static/img/del.png" class="del_icon" @click.stop="delImg(index)"></image>
					</view>
				</view>
			</view>
			<view class="add_msg">
				<view class="left flexB" @click="addImg">
					<image src="../../static/img/up.png" mode="widthFix"></image>
					<text style="margin-left: 10rpx;">添加图片</text>
				</view>
				<view class="right" @click="submit">
					提交
				</view>
			</view>
		</view>
		<view class="new_reply" v-if="msgList.length>0">
			<view class="msg_user flexB">
				<view class="flexS">
					<image src="../../static/img/index.png"></image>
					<text>{{msgList[0].replyTime}}</text>
				</view>
				<view class="reply_hint">最新回复</view>
			</view>
			<view style="padding-left: 88rpx;font-size:28rpx;color:#333">您好，您的建议我们已经收到，感谢您的反馈。</view>
		</view>
		<view class="msg_record">
			<view class="msg_title">留言历史</view>
			<view class="msg_list" v-for="(item,idx) in msgList" :key="item.id"
				:style="{'margin-top':idx===0?'0':'10rpx'}">
				<view class="msg_user flexS">
					<image :src="item.avatar"></image>
					<text>{{item.time}}</text>
				</view>
				<view class="msg_info">
					<view v-if="item.isOpen" @click="changeOpen(idx)">
						<text>{{item.reply}}</text>
						<text class="show">收起</text>
						<image src="../../static/img/arrow_right.png" class="arrow"></image>
					</view>
					<view v-else>
						<text>{{item.reply|getName}}</text>
						<text class="show" v-if="item.reply&&item.reply.trim().length>20"
							@click="changeOpen(idx)">展开</text>
						<image src="../../static/img/arrow_down.png" class="arrow"
							v-if="item.reply&&item.reply.trim().length>20" @click="changeOpen(idx)"></image>
					</view>
					<view class="img_list flexS" v-if="item.img&&item.img.length>0">
						<view class="img_item" v-for="(temp,index) in item.img" :key="index">
							<image :src="temp" @click="previewImage(item.img,index)"></image>
						</view>
					</view>
				</view>
			</view>
			<view class="noData" v-if="msgList.length===0">
				<image src="../../static/img/no_comment.png" mode=""></image>
				<view>--暂无留言--</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		submitMsg,
		history,
		wechats,
		getCookie
	} from '../../api/index.js'
	var jweixin = require('jweixin-module');
	export default {
		data() {
			return {
				latitude: '',
				longitude: '',
				value: '', //提交内容
				unionid: '', //用户id
				imgList: [], //展示图片列表
				msgList: [], //留言历史列表
				upImgList: [], //上传图片列表
				jsdk: '', //微信的jsdk
				index: 1, //当前页数
				totalPage: 0, //总页数
				isIos: false // 是否是iphone手机
			}
		},
		filters: {
			getName(val) {
				if (!val) return '';
				return val.length > 15 ? val.slice(0, 15) + '...' : val;
			},
		},
		onLoad() {
			let params = this.getUrlParam('code');
			if (!params) {
				this.toWxchatLogin()
				return
			}
			if (Number(this.getQueryVariable('status')) === 1) {
				getCookie({
					code: params
				}).then(res => {
					uni.setStorageSync('unionid', res.data.unionid)
					this.unionid = res.data.unionid
					this.getRecord()
					this.getAddress()
				})
			}
			uni.getSystemInfo({
				success: res => {
					if (res.model === 'iPhone') {
						this.isIos = true
					} else {
						this.isIos = false
					}
				}
			})
		},
		onShow() {
			this.unionid = uni.getStorageSync('unionid')
			if (this.unionid) {
				this.index = 1
				this.getRecord()
			}
		},
		onReachBottom() {
			this.getMore()
		},
		methods: {
			// 点击放大图片
			previewImage(urls, current) {
				uni.previewImage({
					urls,
					current
				});
			},
			//通过后端获取wx.config的配置,再通过微信的js-sdk获取经纬度
			getAddress() {
				const _this = this;
				let link = '';
				if (this.isIos) {
					link = window.location.href.split('#')[0]
				} else {
					link = window.location.href
				}
				wechats({
					url: link,
					unionid: this.unionid
				}).then(res => {
					if (res.code == 200) {
						let data = JSON.parse(res.data);
						this.jsdk = data
						console.log('后端返回的wx.config的配置:', JSON.parse(res.data));
						_this.getLocation(data);
					} else {
						uni.showToast({
							title: res.msg
						})
					}
				});
			},
			getLocation(params) {
				const _this = this;
				// 判断是否支持获取定位
				jweixin.config({
					debug: false, //开启debug模式.正式环境设置为false,测试环境设置为true
					appId: params.appId,
					timestamp: params.timestamp,
					nonceStr: params.nonceStr,
					signature: params.signature,
					jsApiList: ['getLocation'] //根据需要看需要哪些SDK的功能
				});
				// sdk加载完成后执行
				jweixin.ready(() => {
					jweixin.checkJsApi({
						jsApiList: ['getLocation'],
						success: res => {
							if (res.checkResult.getLocation == false) {
								alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
								return;
							}
						}
					});
					jweixin.error(res => {
						console.log(res.errMsg, 'err');
					});
					// 获取位置
					jweixin.getLocation({
						type: 'gcj02',
						success: res => {
							this.longitude = res.longitude
							this.latitude = res.latitude
						},
						cancel: res => {
							uni.showToast({
								title: '您已禁止获取位置信息',
								icon: 'none'
							});
						},
						fail: err => {
							uni.showToast({
								title: err,
								icon: 'none'
							});
						}
					});
				});
			},

			// 获取留言记录
			getRecord(isMore) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				history({
					unionid: this.unionid,
					index: this.index
				}).then(res => {
					if (res.code === 200) {
						let list = res.data.list
						list.map(i => {
							this.$set(i, 'isOpen', false)
							if (res.data.avatar) {
								this.$set(i, 'avatar', res.data.avatar)
							}
						})
						this.msgList = isMore ? list.concat(list) : list
						this.totalPage = Math.ceil(res.data.total / res.data.size)
					} else {
						uni.showModal({
							content: res.msg,
							showCancel: false
						})
					}
					uni.hideLoading()
				}).catch(() => {
					uni.hideLoading()
				})
			},
			// 获取更多记录
			getMore() {
				if (this.index >= this.totalPage) {
					uni.showToast({
						title: '没有更多啦~',
						icon: 'none'
					});
					return false;
				}
				this.index++;
				this.getRecord(true)
			},
			// 提交留言
			submit() {
				if (this.upImgList.length === 0 && !this.value) {
					uni.showModal({
						content: '留言内容不能为空',
						showCancel: false
					})
					return
				}
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				submitMsg({
					latitude: this.latitude,
					longitude: this.longitude,
					value: this.value,
					imgList: this.upImgList,
					unionid: this.unionid
				}).then(res => {
					if (res.code === 200) {
						uni.showModal({
							content: '留言提交成功',
							showCancel: false,
						})
						this.value = ''
						this.imgList = []
						this.upImgList = []
						this.getRecord()
					} else {
						uni.showModal({
							content: res.msg,
							showCancel: false
						})
					}
					uni.hideLoading()
				}).catch(() => {
					uni.hideLoading()
				})

			},
			// 展开/收起留言
			changeOpen(idx) {
				this.msgList[idx].isOpen = !this.msgList[idx].isOpen
				let list = this.msgList
				if (this.msgList[idx].isOpen) {
					for (let i = 0; i < list.length; i++) {
						if (i === idx) {
							list[i].isOpen = true
						} else {
							list[i].isOpen = false
						}

					}
				}
			},
			// 选择图片
			addImg() {
				if (this.imgList.length > 9) {
					uni.showModal({
						content: '图片最多只能上传9张',
						showCancel: false
					})
					return
				}
				const _this = this;
				// 判断是否支持选择图片
				jweixin.config({
					debug: false, //开启debug模式.正式环境设置为false,测试环境设置为true
					appId: this.jsdk.appId,
					timestamp: this.jsdk.timestamp,
					nonceStr: this.jsdk.nonceStr,
					signature: this.jsdk.signature,
					jsApiList: ['chooseImage', 'getLocalImgData'] //根据需要看需要哪些SDK的功能
				});
				// sdk加载完成后执行
				jweixin.ready(() => {
					jweixin.checkJsApi({
						jsApiList: ['chooseImage', 'getLocalImgData'],
						success: res => {
							if (res.checkResult.chooseImage == false || res.checkResult
								.getLocalImgData == false) {
								alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
								return;
							}
						}
					});
					jweixin.error(res => {
						console.log(res.errMsg, 'chooseError');
					});

					jweixin.chooseImage({
						count: 1, // 默认9
						sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
						success: res => {
							let localIds = res.localIds
								.toString(); // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
							if (this.isIos) {
								jweixin.getLocalImgData({
									localId: localIds, // 图片的localID
									success: res => {
										this.imgList.push(res.localData)
									},
									fail: err => {
										console.log(err, '下载图片错误')
									}
								})
							} else {
								this.imgList.push(localIds)
							}
							this.uploadImage(localIds)
						},
						fail: err => {
							console.log(err, '选择图片错误')
						}

					})
				});
			},
			uploadImage(localId) {
				const _this = this;
				// 判断是否支持上传图片
				jweixin.config({
					debug: false, //开启debug模式.正式环境设置为false,测试环境设置为true
					appId: this.jsdk.appId,
					timestamp: this.jsdk.timestamp,
					nonceStr: this.jsdk.nonceStr,
					signature: this.jsdk.signature,
					jsApiList: ['uploadImage'] //根据需要看需要哪些SDK的功能
				});
				// sdk加载完成后执行
				jweixin.ready(() => {
					jweixin.checkJsApi({
						jsApiList: ['uploadImage'],
						success: res => {
							if (res.checkResult.uploadImage == false) {
								alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
								return;
							}
						}
					});
					jweixin.error(res => {
						console.log(res.errMsg, 'uploadError');
					});

					jweixin.uploadImage({
						localId,
						isShowProgressTips: 1, // 默认为1，显示进度提示
						success: res => {
							let serverId = res.serverId; // 返回图片的服务器端ID
							this.upImgList.push(serverId)
							console.log(serverId, 'serverId')
						},
						fail: err => {
							console.log(err, '上传图片错误')
						}

					})
				});
			},
			delImg(idx) {
				this.imgList.splice(idx, 1)
				this.upImgList.splice(idx, 1)
			},
			toWxchatLogin() {
				const url = '/pages/index/index';
				const state = 'cli';
				const wxURL = 'https://open.weixin.qq.com/connect/oauth2/authorize';
				const appid = 'wx5224793b7dc7f7b7';
				const redirect_uri = encodeURIComponent(`https://api.app.jiuweiyun.cn/api/xxShouQuan#${url}`);
				const auth = () =>
					(window.location.href =
						`${wxURL}?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`
					);
				auth();
			},
			getQueryVariable(variable) {
				var query = window.location.search.substring(1);
				var vars = query.split("&");
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split("=");
					if (pair[0] == variable) {
						return pair[1];
					}
				}
				return (false);
			},
			//获取code值方法
			getUrlParam(name) {
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); //构造一个含有目标参数的正则表达式对象
				var r = window.location.search.substr(1).match(reg); //匹配目标参数
				if (r != null) return decodeURIComponent(r[2]);
				return null; //返回参数值
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F2F2F2;
	}

	.content {
		padding-bottom: 120rpx;

		.msg_box,
		.intr,
		.new_reply {
			width: 100%;
			background: #fff;
		}

		.msg_user {
			image {
				width: 78rpx;
				height: 78rpx;
				border-radius: 50%;
			}

			text {
				font-size: 26rpx;
				color: #999;
				margin-left: 18rpx;
			}
		}

		.intr {
			padding: 20rpx 30rpx 30rpx;
			box-sizing: border-box;

			.intr_top {
				display: flex;
				justify-content: flex-start;
				align-items: center;

				.intr_img {
					image {
						width: 167rpx;
						height: 167rpx;
					}

				}

				.intr_con {
					view:first-child {
						font-size: 46rpx;
						margin-bottom: 20rpx;
					}

					view:last-child {
						font-size: 32rpx;
					}
				}
			}

			.intr_bottom {
				view {
					color: #999;
					letter-spacing: 2rpx;
				}
			}
		}

		.msg_box {
			margin-top: 20rpx;
			// padding: 0 30rpx;
			box-sizing: border-box;



			.msg_con {
				.msg_text {
					margin: 30rpx 30rpx 50rpx;

					textarea {
						width: 100%;
						// padding: 20rpx;
						box-sizing: border-box;
					}
				}
			}

			.msg_imgs {
				width: 100%;
				display: flex;
				flex-wrap: wrap;
				justify-content: flex-start;
				align-items: center;
				padding: 0 30rpx;
				box-sizing: border-box;

				.img_box {
					width: 220rpx;
					height: 220rpx;
					width: 33.33%;
					margin-top: 15rpx;
					position: relative;



					.img {
						width: 220rpx;
						height: 220rpx;
						border-radius: 16rpx;
					}

					.del_icon {
						position: absolute;
						top: 10rpx;
						right: 20rpx;
						width: 40rpx;
						height: 40rpx;
					}
				}
			}

			.add_msg {
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-top: 2rpx solid #F2F2F2;
				margin: 26rpx auto 0;
				height: 112rpx;
				width: 94%;
				box-sizing: border-box;

				.left {
					image {
						width: 66rpx;
						height: 57rpx;
					}

					text {
						font-size: 24rpx;
						color: #999;
					}
				}

				.right {
					width: 168rpx;
					height: 72rpx;
					background-color: #F76453;
					color: #fff;
					font-size: 32rpx;
					text-align: center;
					line-height: 72rpx;
					border-radius: 8rpx;
				}
			}
		}

		.msg_box,
		.msg_record {
			margin-top: 20rpx;

			.msg_title {
				width: 100%;
				height: 78rpx;
				line-height: 78rpx;
				padding-left: 30rpx;
				box-sizing: border-box;
				border-bottom: 2rpx solid #F1F1F1;
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.new_reply {
			padding: 20rpx 30rpx;
			box-sizing: border-box;
			margin-top: 20rpx;

			.reply_hint {
				color: #F76454;
				font-size: 24rpx;
				letter-spacing: 3rpx;

				&::before {
					content: '';
					display: inline-block;
					width: 10rpx;
					height: 10rpx;
					background: #F76454;
					border-radius: 50%;
					margin: 0 6rpx 5rpx 0;

				}
			}
		}

		.msg_record {
			width: 100%;

			.msg_title {
				background: #fff;
			}

			.msg_list {
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				background: #fff;

				.msg_user {
					image {
						width: 78rpx;
						height: 78rpx;
						border-radius: 50%;
					}

					text {
						font-size: 26rpx;
						color: #999;
						margin-left: 18rpx;
					}
				}

				.msg_info {
					padding-left: 88rpx;

					text {
						font-size: 28rpx;
						color: #666;
						letter-spacing: 2rpx;
					}

					.arrow {
						width: 24rpx;
						height: 24rpx;
					}

					.show {
						color: #F76454;
						margin: 0 10rpx;
					}

					.img_list {
						flex-wrap: wrap;

						.img_item {
							width: 33.33%;
							text-align: center;

							image {
								width: 150rpx;
								height: 150rpx;
								border-radius: 10rpx;
							}
						}
					}
				}
			}
		}

		.noData {
			width: 100%;
			background: #fff;
			text-align: center;
			padding: 20rpx 0;

			image {
				width: 458rpx;
				height: 351rpx;
			}

			view {
				font-size: 28rpx;
				margin-top: 10rpx;
			}
		}

	}

	.flexV {
		display: flex;
		align-items: center;
	}

	.flexT {
		display: flex;
		justify-content: flex-start;
		vertical-align: flex-start;
	}

	.flexC {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.flexS {
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.flexSS {
		display: flex;
		align-items: flex-start;
		justify-content: flex-start;
	}

	.flexE {
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.flexA {
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.flexB {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.flexBS {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.flexCC {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.box {
		.top {
			padding: 15rpx 12rpx 30rpx 12rpx;
			margin-bottom: 20rpx;
			background-color: #fff;

			.topFlex {
				display: flex;
				align-items: center;

				&_right {
					display: flex;
					flex-direction: column;
					font-family: MicrosoftYaHei;
				}
			}

			&_bottom {
				margin: 5rpx 0 0 19rpx;
				font-size: 28rpx;
				color: #999;
				letter-spacing: 2rpx;
			}
		}

		.liuyan {
			background-color: #fff;

			&_title {
				color: #181818;
				font-family: SourceHanSansCN-Medium;
				font-weight: 500;
				padding-left: 30rpx;
				line-height: 78rpx;
				font-size: 32rpx;
				border-bottom: 2rpx solid #F1F1F1;
			}

			&_content {
				padding: 30rpx;
				box-sizing: border-box;

				textarea {
					padding: 0 0 40rpx;
				}
			}

			.upload-img-box {
				width: 100%;
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;
				word-wrap: break-word;
				align-items: center;

				.imgBox {
					position: relative;
				}

				.img {
					width: 220rpx;
					height: 220rpx;
					margin-top: 15rpx;

				}

				.del {
					position: absolute;
					top: 20rpx;
					right: 10rpx;
					width: 40rpx;
				}
			}

			&_submit {
				margin: 0 30rpx;
				padding: 25rpx 0;
				border-top: 2rpx solid #F1F1F1;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.left {
					display: flex;
					align-items: center;
					font-size: 24rpx;
					color: #999;
				}

				.right {
					width: 168rpx;
					height: 72rpx;
					background-color: #F76453;
					color: #fff;
					font-size: 32rpx;
					text-align: center;
					line-height: 72rpx;
					border-radius: 8rpx;
				}
			}
		}

		.hui {
			background-color: #fff;
			margin-top: 20rpx;
			padding: 20rpx 35rpx 30rpx 25rpx;

			.flex {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.left {
					display: flex;
					align-items: center;
					color: #999;
					font-size: 28rpx;

					.time {
						margin-left: 10rpx;
					}
				}

				.right {
					font-size: 28rpx;
					color: #F76454;

					text {
						font-weight: bold;
						margin-right: 10rpx;
						font-size: 34rpx;
					}
				}
			}

			.content {
				margin: 0 0 0 95rpx;
				font-size: 28rpx;
				color: #333;
			}
		}

		.history {
			margin-top: 20rpx;
			background-color: #fff;

			&_title {
				color: #181818;
				padding-left: 30rpx;
				line-height: 78rpx;
				font-size: 32rpx;
				border-bottom: 2rpx solid #F1F1F1;
			}

			&_content {
				background-color: #fff;
				padding: 30rpx 35rpx 20rpx 25rpx;

				.flex {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.left {
						display: flex;
						align-items: center;
						color: #999;
						font-size: 28rpx;

						.time {
							margin-left: 10rpx;
						}
					}
				}

				.content {
					margin: 0 0 0 95rpx;
					font-size: 28rpx;
					color: #333;
				}
			}
		}
	}
</style>
