<template>
	<view class="container">
		<!-- 头部选择房间区域 -->
		<view class="select-item" @click="navigateToSelect">
			<view class="picker-item-logol">
				<image class="picker-item-logo-left" src="../../static/room.png"></image>
			</view>
			<view class="picker-item-label">已选房间</view>
			<view class="picker-item-content" v-if="roomSelect=='请选择宿舍'">{{roomSelect}}</view>
			<view class="picker-item-content2" v-else>{{roomSelect}}</view>
			<view class="picker-item-logor">
				<image class="picker-item-logo-right" src="../../static/right.png"></image>
			</view>
		</view>
		<!-- 账单显示区域 -->
		<view class="bill">
			<!-- 筛选框区域 -->
			<view class="choose">
				<view class="time" v-if="isShow">
					<uni-data-select :clear="false" :placeholder="time_value+''" :localdata="time_range"
						@change="changeTime">
					</uni-data-select>
				</view>
				<view class="type" v-if="isShow">
					<uni-data-select :clear="false" placeholder="全部" :localdata="type_range" @change="changeType">
					</uni-data-select>
				</view>
			</view>

			<!-- 没有账单时展示的内容 -->
			<view class="null" v-if="!list.length">
				<img src="../../static/null.png">
				<span>暂无账单</span>
			</view>

			<!-- 有账单时展示的内容 -->
			<view class="has" v-else>
				<!-- 账单列表区域 -->
				<view class="has_bill">
					<view class="item" v-for="item in list" :key="item.id">
						<view class="item_header">
							{{item.payMonth+item.paymentItem}}
						</view>
						<view class="item_box">
							<view class="item_box_1">
								上月表数：{{item.lastElectry}}
							</view>
							<view class="item_box_2">
								本月表数：{{item.nowElectry}}
							</view>
						</view>
						<view class="item_box">
							<view class="item_box_1">
								用量：{{item.nowTonnage}}吨
							</view>
							<view class="item_box_2">
								补助吨数：{{item.subsidiesTonnage}}吨
							</view>
						</view>
						<view class="item_box" v-if="item.payItemType=='2'">
							<view class="item_box_1">
								支付人：{{item.payerName}}
							</view>
						</view>
						<view class="item_notes">
							备注：{{item.orderNotice}}
						</view>

						<view class="item_box">
							<view class="item_box_1 font">
								{{item.payCreateTime}}
							</view>
							<view class="item_box_2">
								实付款：{{item.realPayAmount}}
							</view>
						</view>

						<view class="item_button">

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

							<button class="feedback" type="warn" size="mini" disabled v-if="item.payItemType=='2'">
								已支付
							</button>

							<button class="feedback" type="primary" size="mini" @click="navigateToPay(item)" v-else>
								支付
							</button>
						</view>
					</view>
				</view>

			</view>
		</view>

		<!-- 电话区域按钮 -->
		<view class="phone">
			<view class="phone_box">
				咨询电话：
				<span @click="handlePhone">82293462</span>
			</view>
		</view>

		<!-- 悬浮按钮区域 -->
		<view v-if="roomSelect!='请选择宿舍'" class="suspend_button" @click="goBill" @touchstart="down"
			@touchmove.prevent.stop="move" @touchend="end">
			订单查询
		</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="popSubmit('valiForm')">
							提交
						</button>
						<button type="primary" plain size="mini" @click="close">
							取消
						</button>
					</view>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	// 引入照片压缩js文件
	import * as TranslateImage from '../../util/imageZip.js'
	// 引入加密函数
	import {
		rsaEncrypt
	} from '@/util/rsa'

	export default {
		data() {
			return {
				// 图片上传组件的样式
				imageStyles: {
					width: 75,
					height: 75,
					border: {
						color: "#ccc",
						width: 1,
						style: 'dashed',
						radius: '5px'
					}
				},
				// 选择的宿舍绑定数据
				roomSelect: "请选择宿舍",
				// 悬浮按钮移动标识
				flags: false,
				maxW: 0,
				maxH: 0,
				position: {
					x: 0,
					y: 0
				},
				nx: 0,
				ny: 0,
				// 账单数据
				list: [],
				// 时间筛选框选中值绑定数据
				time_value: "",
				// 时间筛选框列表绑定数据
				time_range: [],
				// 支付状态 0是全部 1是未支付 2是已支付
				pay_type: 0,
				// 支付状态筛选框列表绑定数据
				type_range: [{
						value: 1,
						text: "全部"
					},
					{
						value: 2,
						text: "未支付"
					},
					{
						value: 3,
						text: "已支付"
					},
				],
				// 订单反馈弹窗 表格的验证规则
				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: []
				},
				// 弹窗标题
				popTitle: "",
				// 订单号
				orderNo: "",
				// 金额
				amount: "",
				// 微信支付参数
				form: {
					appId: "",
					timeStamp: "",
					nonceStr: "",
					signType: "",
					paySign: "",
					package: "",
				},
				//农商行地址
				notifyUrl: "https://chtech.ncjti.edu.cn/jiaofei/jiaofei-api/tuitionpayment/pay/jxnxs/notify/",
				// 反馈提交图片参数
				imgs: []
			};
		},
		onLoad() {
			// 判断是否存在card_number，不存在则重新授权
			this.getAuthorization();

			// 如果之前已经选择过宿舍,则从缓存中读取
			if (localStorage.room) {
				this.roomSelect = localStorage.room
				this.getData()
				this.getTimeList()
			}
		},

		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 rsaRoom = rsaEncrypt(localStorage.room)
				// console.log(rsaRoom);

				// 获取当前年份
				if (!this.time_value) {
					let date = new Date();
					this.time_value = date.getFullYear()
				}

				let res = await this.$myRequest({
					url: "/payableinfowater/queryWaterInfo",
					method:"post",
					data: {
						dorm: rsaRoom,
						year: this.time_value,
						payStatu: this.pay_type,
					},
				});
				// console.log(res);
				if (res.success) {
					this.list = res.data
				}
			},
			// 获取时间筛选框时间数组
			async getTimeList() {
				let res = await this.$myRequest({
					url: "/payableinfowater/queryAllYear",
					data: {
						dorm: localStorage.room,
					},
				});
				// console.log(res);
				if (res.success) {
					this.time_range = 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);
			},
			// 订单反馈按钮弹窗
			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,
					},
				});
				// console.log(res);
				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();
			},
			// 订单反馈弹窗提交按钮回调
			popSubmit(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();
			},
			// 时间筛选框数据改变回调
			changeTime(e) {
				if (e != "") {
					this.time_range.forEach((element) => {
						if (element.value == e) {
							this.time_value = element.text
						}
					})
					this.getData()
				}
			},
			// 支付状态筛选框数据改变回调
			changeType(e) {
				if (e == 1 || e == 2 || e == 3) {
					if (e == 1) {
						this.pay_type = 0
					} else if (e == 2) {
						this.pay_type = 1
					} else if (e == 3) {
						this.pay_type = 2
					}
					this.getData()
				}
			},
			// 跳转到选择宿舍页面
			navigateToSelect() {
				uni.navigateTo({
					url: '/pages/select/select',
				});
			},
			// 支付回调
			navigateToPay(item) {
				// console.log(item);
				this.amount = item.realPayAmount;
				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: "",
						itemName: item.paymentItem,
						payYear: item.payMonth,
						payDetail: item.payAmountDetail,
						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.id,
						studentNo: "",
						itemName: item.paymentItem,
						payYear: item.payMonth,
						payDetail: item.payAmountDetail,
						dorm: item.dorm,
						payOrderLoan: 0,
						orderNotice: item.orderNotice,
						payCount: "1",
						notPaySize: 0,
						nowRealPayAmount: item.realPayAmount,
						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;
			},

			// 订单查询悬浮按钮回调
			goBill() {
				uni.navigateTo({
					url: "/pages/bill/bill"
				})
			},

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

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

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

			move(event) {
				let suspend_button = document.querySelector(".suspend_button");
				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;
					}
					suspend_button.style.left = this.nx + "px";
					suspend_button.style.top = this.ny + "px";
				}
			},

			end() {
				this.flags = false;
			},

			// 拨打电话回调
			handlePhone() {
				uni.makePhoneCall({
					phoneNumber: '82293462'
				});
			},
			// 下拉刷新
			onPullDownRefresh() {
				if (localStorage.room) {
					this.roomSelect = "黄家湖" + localStorage.room
					this.getData()
					this.getTimeList()
				}
				setTimeout(() => {
					uni.stopPullDownRefresh();
				}, 1500)
			},
		},
		computed: {
			// 计算出缓存中是否存在宿舍号
			isShow() {
				if (localStorage.room) {
					return true
				} else {
					return false
				}
			}
		},
	}
</script>

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

		.select-item {
			margin: 19rpx 0;
			display: flex;
			background-color: #ffffff;
			height: 139rpx;

			.picker-item-logol {
				width: 88rpx;
				display: flex;
				justify-content: flex-end;
				align-items: center;

				.picker-item-logo-left {
					width: 58rpx;
					height: 58rpx;
				}
			}

			.picker-item-label {
				font-size: 30rpx;
				width: 161rpx;
				height: 139rpx;
				line-height: 139rpx;
				text-align: center;
			}

			.picker-item-content {
				width: 360rpx;
				height: 139rpx;
				line-height: 139rpx;
				font-size: 36rpx;
				text-align: center;
				color: #999999;
			}

			.picker-item-content2 {
				width: 360rpx;
				height: 139rpx;
				line-height: 139rpx;
				font-size: 32rpx;
				text-align: center;
				color: black;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.picker-item-logor {
				width: 91rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				.picker-item-logo-right {
					width: 40rpx;
					height: 40rpx;
				}
			}
		}

		.bill {
			margin: 20rpx 0;
			min-height: 920rpx;

			.choose {
				display: flex;
				margin: 0 20rpx;

				.time {
					flex: 1;
					padding-right: 40rpx;
				}

				.type {
					flex: 1;
				}
			}

			.null {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin: 0 auto;
				padding-top: 300rpx;
				width: 50%;
				height: 400rpx;

				img {
					height: 90%;
				}

				span {
					margin-top: 30rpx;
				}
			}

			.has {
				margin: 0 20rpx;



				.has_bill {
					margin-top: 20rpx;

					.item {
						margin-bottom: 20rpx;
						border-radius: 10rpx;
						background-color: #fff;

						.item_header {
							height: 96rpx;
							line-height: 96rpx;
							text-align: center;
							font-weight: bold;
							border-radius: 10rpx 10rpx 0 0;
							background-color: #e7eef5;
						}

						.item_box {
							display: flex;
							margin: 0 30rpx;
							height: 70rpx;
							line-height: 70rpx;
							font-weight: bold;

							.item_box_1 {
								flex: 1.5;
							}

							.item_box_2 {
								flex: 1;
							}

							.font {
								font-weight: normal;
								color: #999;
							}
						}

						.item_notes {
							margin: 0 30rpx;
							height: 60rpx;
							line-height: 60rpx;
							font-size: 26rpx;
							color: #999;
						}

						.item_button {
							display: flex;
							justify-content: flex-end;
							margin: 10rpx 50rpx;
							height: 74rpx;
							line-height: 74rpx;

							.feedback {
								margin: 0;
								padding: 0;
								width: 140rpx;
								height: 65rpx;
								line-height: 65rpx;
								font-size: 26rpx;
							}

							.right {
								margin-right: 50rpx;
							}
						}
					}
				}
			}
		}

		.phone {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 20rpx 0;
			height: 70rpx;

			.phone_box {
				margin-bottom: 20rpx;

				span {
					color: #4993EA;
				}
			}
		}

		.suspend_button {
			position: fixed;
			left: 80rpx;
			bottom: 120rpx;
			width: 140rpx;
			height: 140rpx;
			line-height: 140rpx;
			text-align: center;
			border-radius: 70rpx;
			color: #fff;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.popup_view {
			width: 650rpx;

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

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

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

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

	::v-deep .uni-select__input-placeholder {
		font-size: 28rpx;
		color: #3a3a3a;
	}

	::v-deep .uniui-bottom::before {
		color: #fff;
	}

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