<template>
	<view class="container">
		<view class="body">
			<!-- 顶部tab标签区域 -->
			<view class="tab">
				<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text"
					activeColor="#fff">
				</uni-segmented-control>
				<view class="select" v-if="list.length">
					<uni-data-picker class="picker" placeholder="点击根据时间筛选" popup-title="请选择筛选条件" :localdata="dataTree"
						@change="onchange">
					</uni-data-picker>
				</view>
				<view class="content" v-if="list.length">
					<!-- 缴费失败区域 -->
					<view v-show="current === 0">
						<view class="detail" v-for="item in list" :key="item.id">
							<view class="detail_title">
								<view class="title1">
									{{ item.payYear }}水费账单
								</view>
								<text>缴费失败</text>
							</view>

							<view class="info">
								<view class="place">
									<view class="name">宿舍</view>
									<view class="rooms">{{ item.dorm }}</view>
								</view>

								<view class="place">
									<view class="name">上月表数</view>
									<view class="rooms">{{ item.payForIdentify }}</view>
								</view>

								<view class="place">
									<view class="name">本月表数</view>
									<view class="rooms">{{ item.studentName }}</view>
								</view>

								<view class="place">
									<view class="name">用量</view>
									<view class="rooms">{{ item.className }}</view>
								</view>

								<view class="place">
									<view class="name">补助吨数</view>
									<view class="rooms">{{ item.parentOrder }}</view>
								</view>

								<view class="place">
									<view class="time">备注：{{item.orderNotice}}</view>
								</view>

								<view class="timeAndNumber">
									<view class="time">{{ item.createTime }}</view>
									<view class="number">待付款￥{{ item.nowPayAmount }}</view>
								</view>

								<view class="button">
									<button type="primary" plain size="mini" class="button_item"
										@click="handleFeedback(item)">
										订单反馈
									</button>

									<button type="primary" plain size="mini" class="button_item"
										@click="goPayPage(item)">
										继续支付
									</button>
								</view>
							</view>
						</view>
					</view>
					<!-- 缴费成功区域 -->
					<view v-show="current === 1">
						<view class="detail" v-for="item in list" :key="item.id">
							<view class="detail_title">
								<view class="title1">
									{{ item.payYear }}水费账单
								</view>
								<text class="title3">缴费成功</text>
							</view>

							<view class="info">
								<view class="place">
									<view class="name">宿舍</view>
									<view class="rooms">{{ item.dorm }}</view>
								</view>
								<view class="place">
									<view class="name">上月表数</view>
									<view class="rooms">{{ item.payForIdentify }}</view>
								</view>

								<view class="place">
									<view class="name">本月表数</view>
									<view class="rooms">{{ item.studentName }}</view>
								</view>

								<view class="place">
									<view class="name">用量</view>
									<view class="rooms">{{ item.className }}</view>
								</view>

								<view class="place">
									<view class="name">补助吨数</view>
									<view class="rooms">{{ item.parentOrder }}</view>
								</view>

								<view class="place">
									<view class="time">备注：{{item.orderNotice}}</view>
								</view>

								<view class="timeAndNumber">
									<view class="time">{{ item.createTime }}</view>
									<view class="number">实付款￥{{ item.nowPayAmount }}</view>
								</view>

								<view class="button2">
									<button class="button_item" type="primary" plain size="mini"
										@click="handleFeedback(item)">
										订单反馈
									</button>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 图片区域 -->
				<view class="image" v-if="!list.length"></view>

				<!-- 提示信息区域 -->
				<view class="infoNo" v-if="!list.length"> 暂无缴费订单信息 </view>

				<view style="height: 15px"></view>
			</view>

			<!-- 悬浮按钮返回主页区域 -->
			<view id="item_box" class="suspension" @click="goHome" @touchstart="down" @touchmove.prevent="move"
				@touchend="end">
				<view class="icon">
					<img src="../../static/home.png" />
				</view>
				<view class="info">返回主页</view>
			</view>

			<!-- 订单反馈弹窗区域 -->
			<uni-popup ref="popup_feedback" background-color="#fff" :is-mask-click="false">
				<view class="popup_view">
					<view class="title">{{popTitle}}</view>

					<view class="forms">
						<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData">

							<uni-forms-item label="姓名:" required name="feedbackPersonName">
								<uni-easyinput v-model="valiFormData.feedbackPersonName" placeholder="请输入姓名" />
							</uni-forms-item>

							<uni-forms-item label="联系电话:" required name="feedbackPersonPhone">
								<uni-easyinput maxlength="11" v-model="valiFormData.feedbackPersonPhone" type="number"
									placeholder="请输入联系人手机号码" />
							</uni-forms-item>

							<uni-forms-item label="宿舍号:" required name="feedbackRoom">
								<uni-easyinput v-model="valiFormData.feedbackRoom" placeholder="请输入宿舍号" />
							</uni-forms-item>

							<uni-forms-item label="反馈信息:" required name="feedbackInfo">
								<uni-easyinput type="textarea" v-model="valiFormData.feedbackInfo"
									placeholder="请输入反馈信息" />
							</uni-forms-item>

							<uni-forms-item label="上传图片:" name="feedbackImg">
								<uni-file-picker limit="3" title="最多上传3张图片" v-model="valiFormData.feedbackImg"
									fileMediatype="image" :image-styles="imageStyles" mode="grid" @select="select"
									@delete="handleDelete">
								</uni-file-picker>
							</uni-forms-item>
						</uni-forms>

						<view class="form_button">
							<button type="primary" size="mini" @click="submit('valiForm')">
								提交
							</button>
							<button type="primary" plain size="mini" @click="close">
								取消
							</button>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	// 引入照片压缩js文件
	import * as TranslateImage from '../../util/imageZip.js'
	export default {
		data() {
			return {
				// 图片上传组件的样式
				imageStyles: {
					width: 75,
					height: 75,
					border: {
						color: "#ccc",
						width: 1,
						style: 'dashed',
						radius: '5px'
					}
				},
				// 时间筛选框绑定数据
				dataTree: [],
				// 分段器数据
				items: ["缴费失败", "缴费成功"],
				// 当前激活分段器
				current: 1,
				// 缴费状态
				payStatu: 2,
				// 支付时间
				payYear: "",
				// 页面账单数据
				list: [],
				// 订单反馈弹窗 表格的验证规则
				rules: {
					feedbackPersonName: {
						rules: [{
								required: true,
								errorMessage: "请输入姓名",
							},
							{
								minLength: 2,
								maxLength: 8,
								errorMessage: "请输入正确的姓名",
							}
						],
					},
					feedbackPersonPhone: {
						rules: [{
								required: true,
								errorMessage: "请输入联系人手机号码",
							},
							{
								pattern: /^[1]([3-9])[0-9]{9}$/,
								errorMessage: '请输入正确的手机号码'
							}
						],
					},
					feedbackRoom: {
						rules: [{
							required: true,
							errorMessage: "请输入宿舍号",
						}, ],
					},
					feedbackInfo: {
						rules: [{
							required: true,
							errorMessage: "请输入反馈信息",
						}, ],
					},
				},
				// 订单反馈弹窗 表格绑定数据
				valiFormData: {
					feedbackPersonName: "",
					feedbackPersonPhone: "",
					feedbackRoom: "",
					feedbackInfo: "",
					feedbackImg: []
				},
				// 订单号
				orderNo: "",
				// 支付金额
				amount: "",
				// 微信支付参数
				form: {
					appId: "",
					timeStamp: "",
					nonceStr: "",
					signType: "",
					paySign: "",
					package: "",
				},
				//农商行地址
				notifyUrl: "https://chtech.ncjti.edu.cn/jiaofei/jiaofei-api/tuitionpayment/pay/jxnxs/notify/",
				// 悬浮窗移动标识
				flags: false,
				// 定位属性
				position: {
					x: 0,
					y: 0,
				},
				nx: "",
				ny: "",
				xPum: "",
				yPum: "",
				maxW: "",
				maxH: "",
				// 弹窗标题
				popTitle: "",
				// 反馈提交图片参数
				imgs: []
			};
		},
		onLoad() {
			// 判断是否存在card_number，不存在则重新授权
			this.getAuthorization();
			this.getData()
			this.getTime()
		},
		methods: {
			getAuthorization() {
				let card_number = localStorage.getItem("card_number");
				let studentName = localStorage.getItem("studentName");
				let openId = localStorage.getItem("openId");
				if (!card_number || !studentName || !openId) {
					uni.showModal({
						title: "提示",
						content: "请先领取校园卡或授权后再进行相关操作",
						showCancel: false,
						success: () => {
							uni.reLaunch({
								url: "/pages/index/index",
							});
						},
					});
				}
			},
			// 获取账单列表数据
			async getData() {
				let res = await this.$myRequest({
					url: "/payorder/queryWaterOrder",
					data: {
						dorm: localStorage.room,
						payYear: this.payYear,
						payStatu: this.payStatu,
						itemName: "水费缴纳"
					}
				})
				// console.log(res);
				if (res.success) {
					this.list = res.data
				}
			},
			// 获取时间数组
			async getTime() {
				let res = await this.$myRequest({
					url: "/payableinfowater/queryAllYear",
					data: {
						dorm: localStorage.room,
						payStatu: this.payStatu,
					}
				})
				// console.log(res);
				if (res.success) {
					this.dataTree = res.data
				}
			},
			// 上传图片回调
			select(e) {
				e.tempFiles.forEach((item) => {
					TranslateImage.translate(item.path, ((res) => {
						// 判断图片大小是否过大
						if (Number(res.size) > 1000000) {
							uni.showModal({
								content: `图片过大,请重新上传`,
								showCancel: false,
								success() {}
							})
							return
						}

						uni.showLoading({
							title: '上传中'
						});

						// 上传图片
						uni.uploadFile({
							url: `https://chtech.ncjti.edu.cn/jiaofei/jiaofei-api/tuitionpayment/feedbackmsg/uploadImage`,
							filePath: res.url,
							name: 'images',
							success: (uploadFileRes) => {
								// 收集提交请求所需要的图片参数数据
								this.imgs.push((JSON.parse(uploadFileRes.data).data))

								const path = item.path;
								this.valiFormData.feedbackImg.push({
									url: path,
									name: ""
								})
								uni.hideLoading();
							},
							fail: () => {
								uni.hideLoading();
							}
						});
					}))
				})
			},
			// 删除图片回调
			handleDelete(e) {
				const num = this.valiFormData.feedbackImg.findIndex(v => v.path === e.tempFilePath);
				this.valiFormData.feedbackImg.splice(num, 1);
				this.imgs.splice(num, 1);
			},
			// 筛选框数据改变回调
			onchange(e) {
				// console.log(e);
				if (e.detail.value.length == 0) {
					this.payYear = "";
				} else {
					this.payYear = e.detail.value[0].text;
				}
				this.getData()
			},

			// 顶部tab标签切换回调
			onClickItem(e) {
				this.current = e.currentIndex;
				if (this.current == 0) {
					this.payStatu = 1;
				} else {
					this.payStatu = 2;
				}
				this.getData()
			},

			// 订单反馈按钮回调
			async handleFeedback(item) {
				this.popTitle = item.title
				this.valiFormData.feedbackPersonName = "";
				this.valiFormData.feedbackPersonPhone = "";
				this.valiFormData.feedbackRoom = "";
				this.valiFormData.feedbackInfo = "";
				this.valiFormData.feedbackImg = [];
				this.imgs = []

				let res = await this.$myRequest({
					url: "/wechat/getUserNameTele",
					data: {
						cardNumber: localStorage.card_number,
					},
				});

				if (res.success) {
					this.valiFormData.feedbackPersonName = res.data.name
					this.valiFormData.feedbackPersonPhone = res.data.telephone
					this.valiFormData.feedbackRoom = localStorage.room
				}

				this.$refs.popup_feedback.open();
			},

			// 订单反馈弹窗提交按钮回调
			submit(ref) {
				this.$refs[ref]
					.validate()
					.then(async (res) => {
						// 如果上传了图片,处理图片参数字段
						if (res.feedbackImg.length) {
							res.image = this.imgs.join(";")
						}
						res.feedbackItemName = "水费缴纳"

						// 整理参数
						let {
							feedbackImg,
							...data
						} = res

						let result = await this.$myRequest({
							url: "/feedbackmsg/save",
							method: "post",
							data
						})
						if (result.success) {
							uni.showToast({
								title: '提交成功',
							});
						}

						this.$refs.popup_feedback.close();
					})
					.catch((err) => {
						console.log("err", err);
					});
			},

			// 订单反馈弹窗取消按钮回调
			close() {
				this.$refs.popup_feedback.close();
			},

			// 继续支付按钮回调
			goPayPage(item) {
				console.log(item);
				this.orderNo = item.orderNo;
				this.amount = item.nowPayAmount;
				this.getQuery(item)
			},

			// 处理参数
			async getQuery(item) {
				// console.log(item);
				let res = await this.$myRequest({
					url: `/payorder/${item.payForIdentify}/receiveOrder`,
					method: "post",
					data: {
						id: item.id,
						studentNo: item.studentNo,
						itemName: item.payItem,
						payYear: item.payYear,
						payDetail: item.payDetail,
						dorm: item.dorm,
						payOrderLoan: "",
						orderNotice: item.orderNotice,
						// payItemType: 1,
						payCount: "1",
						notPaySize: 0,
						nowRealPayAmount: item.realPayAmount,
						payerCardNumber: localStorage.card_number,
						payerName: localStorage.studentName
					}
				})
				// console.log(res);
				if (res.success) {
					this.createPayorder(item)
				}
			},

			// 创建订单
			async createPayorder(item) {
				let res = await this.$myRequest({
					url: `/payorder/${item.payForIdentify}/create`,
					method: "post",
					data: {
						id: item.payinfoId,
						studentNo: item.payForIdentify,
						itemName: item.payItem,
						payYear: item.payYear,
						payDetail: item.payDetail,
						dorm: item.dorm,
						payOrderLoan: item.payOrderLoan,
						orderNotice: item.orderNotice,
						payCount: "2",
						notPaySize: 0,
						nowRealPayAmount: item.nowPayAmount,
						payerCardNumber: localStorage.card_number,
						payerName: localStorage.studentName
					},
				});
				// console.log(res);
				if (res.success) {
					this.orderNo = res.data[0].orderNo;
					if (res.data[0].payMethod == "1") {
						// console.log("建行");
						this.getjhPay();
					} else {
						// console.log("农商");
						this.getnsPay();
					}
				}
			},

			// 建行支付请求
			async getjhPay() {
				let res = await this.$myRequest({
					url: "/pay/ccb/getJsApiParam",
					data: {
						orderNo: this.orderNo,
						openId: localStorage.openId,
						secondOrderNo: "",
						payment: "2"
					},
				});
				// console.log(res);
				if (res.success) {
					this.form = {
						...res.data,
					};
					//调起微信支付
					this.wxPay();
				} else {
					uni.showToast({
						title: res.message,
						icon: "error",
						mask: true,
					});
				}
			},

			// 微信支付回调
			wxPay() {
				let that = this;

				function onBridgeReady() {
					WeixinJSBridge.invoke(
						"getBrandWCPayRequest",
						that.form,
						function(res) {
							if (res.errMsg == "get_brand_wcpay_request:ok") {
								// 使用以上方式判断前端返回,微信团队郑重提示：
								//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							}
						}
					);
				}
				// 兼容处理
				if (typeof WeixinJSBridge == "undefined") {
					if (document.addEventListener) {
						document.addEventListener(
							"WeixinJSBridgeReady",
							onBridgeReady,
							false
						);
					} else if (document.attachEvent) {
						document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
						document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
					}
				} else {
					onBridgeReady();
				}
			},

			// 农商支付请求
			getnsPay() {
				let O = "6fc31630a4d3de99f5e41debbd35b9f0";

				let out_no = this.orderNo;

				let amount = this.amount;

				let appoint_notify = this.notifyUrl;

				let mainUrl =
					`https://q.jxnxs.com/newpay?O=${O}&out_no=${out_no}&amount=${amount}&appoint_notify=${appoint_notify}`;

				window.location.href = mainUrl;
			},

			// 返回主页按钮回调
			goHome() {
				uni.navigateTo({
					url: "/pages/home/home",
				});
			},

			// 实现移动端拖拽
			down(event) {
				let item_box = document.querySelector("#item_box");
				this.flags = true;
				let touch;
				if (event.touches) {
					touch = event.touches[0];
				} else {
					touch = event;
				}

				this.maxW = document.body.clientWidth - item_box.offsetWidth;
				this.maxH = document.body.clientHeight - item_box.offsetHeight;

				this.position.x = touch.clientX - item_box.offsetLeft;
				this.position.y = touch.clientY - item_box.offsetTop;
			},

			move(event) {
				let item_box = document.querySelector("#item_box");
				if (this.flags) {
					let touch;
					if (event.touches) {
						touch = event.touches[0];
					} else {
						touch = event;
					}
					this.nx = touch.clientX - this.position.x;
					this.ny = touch.clientY - this.position.y;

					if (this.nx < 0) {
						this.nx = 0;
					} else if (this.nx > this.maxW) {
						this.nx = this.maxW;
					}

					if (this.ny < 0) {
						this.ny = 0;
					} else if (this.ny >= this.maxH) {
						this.ny = this.maxH;
					}

					item_box.style.left = this.nx + "px";
					item_box.style.top = this.ny + "px";
				}
			},

			end() {
				this.flags = false;
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		position: relative;
		overflow: auto;
		height: 100vh;
		background-image: url(../../static/bg.png);
		background-size: 100% 100%;

		.body {
			margin: 0 30rpx;

			.tab {
				padding-top: 20rpx;

				.select {
					display: flex;
					margin-top: 20rpx;
					padding: 0 6rpx;
					height: 100rpx;
					border-radius: 10rpx;

					.picker {
						width: 100%;
						padding-top: 8rpx;
					}
				}

				.content {
					height: 80vh;
					overflow: auto;

					.detail {
						margin-bottom: 30rpx;
						background-color: #fff;
						border-radius: 5px;

						.detail_title {
							position: relative;
							height: 96rpx;
							line-height: 96rpx;
							text-align: center;
							border-radius: 5px 5px 0 0;
							background-color: #e7eef5;

							.title1 {
								font-size: 32rpx;
							}

							text {
								position: absolute;
								top: 0;
								right: 30rpx;
								font-size: 24rpx;
								color: red;
							}

							.title3 {
								color: #ff8b02;
							}
						}

						.info {
							.place {
								display: flex;
								margin-left: 34rpx;
								margin-top: 30rpx;

								.name {
									width: 200rpx;
									text-align-last: justify;
									color: #808080;
								}

								.rooms {
									padding-left: 130rpx;
									width: 440rpx;
									font-size: 32rpx;
								}

								.time {
									flex: 5;
									font-size: 24rpx;
									color: #999;
								}
							}

							.timeAndNumber {
								display: flex;
								margin-left: 34rpx;
								margin-top: 20rpx;

								.time {
									flex: 5;
									font-size: 24rpx;
									color: #999;
								}

								.number {
									flex: 5;
									font-size: 32rpx;
								}
							}

							.button {
								display: flex;
								justify-content: flex-end;
								margin-top: 20rpx;
								padding-bottom: 30rpx;

								.button_item {
									margin: 0 20rpx;
									padding: 0;
									width: 90px;
								}
							}

							.button2 {
								display: flex;
								margin-top: 20rpx;
								padding-bottom: 20rpx;

								.button_item {
									padding: 0;
									margin-left: auto;
									margin-right: 60rpx;
									width: 90px;
								}
							}
						}
					}
				}

				.image {
					margin: 260rpx auto;
					width: 438rpx;
					height: 360rpx;
					background: url(../../static/null.png);
					background-size: 100%;
				}

				.infoNo {
					margin-top: 100rpx;
					text-align: center;
					font-size: 36rpx;
				}
			}

			.suspension {
				position: absolute;
				left: 36rpx;
				bottom: 50rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 140rpx;
				height: 140rpx;
				border-radius: 70rpx;
				background-color: rgba(0, 0, 0, 0.4);
				overflow: auto;

				.icon {
					flex: 1;

					img {
						margin-top: 20rpx;
						width: 40rpx;
					}
				}

				.info {
					flex: 2;
					font-size: 24rpx;
					color: #fff;
				}
			}

			.popup_view {
				width: 650rpx;

				.title {
					height: 90rpx;
					line-height: 90rpx;
					text-align: center;
					font-size: 36rpx;
					font-weight: bold;
					background-color: #e7eef5;
				}

				.forms {
					margin: 40rpx;
					width: 550rpx;

					.form_button {
						display: flex;
						text-align: center;

						button {
							width: 200rpx;
						}
					}
				}
			}
		}
	}

	::v-deep .uni-forms-item__label {
		width: 160rpx !important;
	}

	::v-deep .placeholder {
		color: #fff;
	}

	::v-deep .input-arrow {
		border-color: #fff;
	}
</style>
