<template>
	<view class="page">
		<view class="title-top">
			<div class="left">
				<view @click="show = true">{{pageIndex.time}}年<u-icon name="arrow-down"></u-icon></view>
				<u-picker v-model="show" mode="time" :params="{year: true}" @confirm="confirm"></u-picker>
			</div>
			<div class="right">
				<view class="price" style="font-size: 40rpx;"><u-icon name="rmb" style="font-size: 24rpx;" />{{allPay}}
				</view>
			</div>
		</view>
		<view class="record-list">
			<view class="record-item" v-for="(item, index) in dataList" :key="index">
				<view class="info-title">
					<!-- <view class="title">{{formatDate(item.tenementOrderDate)}}</view> -->
					<view class="right">
						<view class="price"><u-icon name="rmb" style="font-size: 24rpx;" />{{item.dingPay}}</view>

					</view>
					<view class="price">
						<u-button type="success" @click="baoShow(item.id)"
							style="height: 32px;border-radius: 10px;" v-if="item.isOpeningInvoice!='2'">申请开票</u-button>
							<u-button type="primary" @click="sent(item.id)"
								style="height: 32px;border-radius: 10px;" v-else>查看发票</u-button>
					</view>
				</view>
				<view class="info-items" v-for="(value, ids) in item.ziList">
					<view class="info-item">
						<view class="left title">
							{{value.tenementOrderParent==''?value.tenementOrder:value.tenementOrderParent}}
						</view>
						<view class="right">
							<view class="price"><u-icon name="rmb" style="font-size: 24rpx;" />{{value.paymentAmount}}
							</view>
						</view>
					</view>
					<view class="info-item">
						<view class="left" style="color: #0FBB59;">{{value.payState==1?'支付成功':''}}</view>
						<view class="right" style="color: #8A8A8A;">{{formatDateTime(value.paymentTime)}}</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="dataList.length === 0" class="nonemsg" style="font-size: 24rpx;">
			暂无数据
		</view>
		<u-popup class="userForm" v-model="joinShow" mode="center" border-radius="20" :closeable="true" width="90%">
			<view style="padding: 30rpx;">
				<u-form class="form-box" :model="form" ref="uForm" label-width="140">
					<view style="padding: 10rpx;">
						<view class="title" style="font-size: 16px;font-weight: bold;">填写发票信息</view>
						<u-form-item label="发票类型">
							<view class="button-group">
								<view class="invoice-btn" :class="{ active: invoiceType === 'ordinary' }"
									@click="selectInvoiceType('ordinary')">
									普通发票
								</view>
								<view class="invoice-btn" :class="{ active: invoiceType === 'special' }"
									@click="selectInvoiceType('special')">
									专用发票
								</view>
							</view>
						</u-form-item>
						<u-form-item label="抬头类型">
							<view class="button-group">
								<view class="invoice-btn" v-if="form.invoiceType!='专用发票'"
									:class="{ active: taitoutype === 'ordinary' }" @click="ttType('ordinary')">
									个人
								</view>
								<view class="invoice-btn" :class="{ active: taitoutype === 'special' }"
									@click="ttType('special')">
									单位
								</view>
							</view>
						</u-form-item>
						<u-form-item label="发票抬头" ><u-input v-model="form.invoiceTitle" placeholder="必填"/></u-form-item>
						<u-form-item label="单位税号" v-if="form.titleType=='单位'">
							<u-input v-model="form.unitTaxNo" placeholder="必填"/>
						</u-form-item>
						<u-form-item label="注册地址" v-if="form.titleType=='单位'">
							<u-input v-model="form.registerAddress" :placeholder="form.invoiceType!='专用发票'?'选填':'必填'" />
						</u-form-item>
						<u-form-item label="注册电话" v-if="form.titleType=='单位'">
							<u-input v-model="form.registerPhone"
								:placeholder="form.invoiceType!='专用发票'?'选填':'必填'" /></u-form-item>
						<u-form-item label="开户银行" v-if="form.titleType=='单位'">
							<u-input v-model="form.openingBank"
								:placeholder="form.invoiceType!='专用发票'?'选填':'必填'" /></u-form-item>
						<u-form-item label="银行账号" v-if="form.titleType=='单位'">
							<u-input v-model="form.bankAccount"
								:placeholder="form.invoiceType!='专用发票'?'选填':'必填'" /></u-form-item>
						<u-button type="success" style="height: 35px;" @click="submit">提交</u-button>
					</view>
				</u-form>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show: false,
				dataList: [],
				allPay: 0,
				pageIndex: {
					time: ''
				},
				merchants: '',
				joinShow: false,
				form: {
					invoiceType: '普通发票', //发票类型
					titleType: '个人', //抬头类型
					invoiceTitle: '', //发票抬头
					unitTaxNo: '', //单位税号
					registerAddress: '', //注册地址
					registerPhone: '', //注册电话
					openingBank: '', //开户银行
					bankAccount: '', //银行账号
					tenementId: '', //缴费订单号ID
					businessUserId: '', //商家ID
					createTime: ''
				},
				invoiceType: 'ordinary',
				taitoutype: 'ordinary',

			}
		},
		onShow() {
			this.pageIndex.time = this.getCurrentYear()
		},
		onLoad(options) {

			console.log()
			if (options.msg && options.merchants) {
				this.allPay = 0
				let receivedMsg = JSON.parse(decodeURIComponent(options.msg))
				this.merchants = decodeURIComponent(options.merchants)
				console.error(this.merchants)
				this.getAll(receivedMsg.list)
			}

		},
		methods: {
			baoShow(val) {
				this.form = {
					invoiceType: '普通发票', //发票类型
					titleType: '个人', //抬头类型
					invoiceTitle: '', //发票抬头
					unitTaxNo: '', //单位税号
					registerAddress: '', //注册地址
					registerPhone: '', //注册电话
					openingBank: '', //开户银行
					bankAccount: '', //银行账号
					tenementId: val, //缴费订单号ID
					businessUserId: '', //商家ID
					createTime: ''
				}
				this.invoiceType = 'ordinary'
				this.taitoutype =  'ordinary'
				this.joinShow = true

			},
			submit() {
				this.form.businessUserId = uni.getStorageSync('user').businessUserId
				if (!this.form.invoiceTitle) {
					uni.showToast({
						icon: 'none',
						title: '请输入发票抬头'
					});
					return false;
				}
				if(this.form.invoiceType == '专用发票'){
					if (!this.form.unitTaxNo) {
						uni.showToast({
							icon: 'none',
							title: '请输入单位税号'
						});
						return false;
					}
					if (!this.form.registerAddress) {
						uni.showToast({
							icon: 'none',
							title: '请输入注册地址'
						});
						return false;
					}
					if (!this.form.registerPhone) {
						uni.showToast({
							icon: 'none',
							title: '请输入注册电话'
						});
						return false;
					}
					if (!this.form.openingBank) {
						uni.showToast({
							icon: 'none',
							title: '请输入开户银行'
						});
						return false;
					}
					if (!this.form.bankAccount) {
						uni.showToast({
							icon: 'none',
							title: '请输入银行账号'
						});
						return false;
					}
				}
				 if(this.form.invoiceType == '普通发票' && this.form.titleType == '单位'){
					 
					 if (!this.form.unitTaxNo) {
					 	uni.showToast({
					 		icon: 'none',
					 		title: '请输入单位税号'
					 	});
					 	return false;
					 }
				 }
				this.$http.sendRequest('/cereInvoiceTitle/add', 'POST', this.form, 2).then(res => {
						uni.showToast({
							icon: 'none',
							title: '提交成功'
						})
						uni.navigateBack({
						  delta: 1
						})
				})
			},
			selectInvoiceType(type) {
				if (type == 'ordinary') {
					this.form.invoiceType = '普通发票'
				} else {
					this.form.invoiceType = '专用发票'
					this.form.titleType = '单位'
					this.taitoutype = 'special'
				}
				this.invoiceType = type; // 点击更新选中状态

			},
			ttType(type) {
				if (type == 'ordinary') {
					this.form.titleType = '个人'
					this.form.unitTaxNo = ''
					this.form.registerAddress = ''
					this.form.registerPhone = ''
					this.form.openingBank = ''
					this.form.bankAccount = ''
				} else {
					this.form.titleType = '单位'
				}
				this.taitoutype = type; // 点击更新选中状态

			},
			sent(ids){
				this.$http.sendRequest(`/cereInvoiceTitle/getByTenementId/${ids}`, 'GET', '', 2).then(res => {
					  const url = this.$img+res.data.data.invoiceUrl
					    uni.downloadFile({
					      url: url,
					      success: (res) => {
					        if (res.statusCode === 200) {
					          const filePath = res.tempFilePath;
					          // 保存到本地
					          uni.saveFile({
					            tempFilePath: filePath,
					            success: (saveRes) => {
					              const savedFilePath = saveRes.savedFilePath;
					              // 打开文件
					              if (uni.getSystemInfoSync().platform === 'ios') {
					                // iOS处理
					                plus.runtime.openFile(savedFilePath, {
					                  contentType: 'application/pdf'
					                });
					              } else {
					                // 安卓或小程序处理
					                uni.openDocument({
					                  filePath: savedFilePath,
					                  success: () => {
					                    console.log('打开成功');
					                  },
					                  fail: (err) => {
					                    console.error('打开失败', err);
					                  }
					                });
					              }
					            },
					            fail: (err) => {
					              console.error('保存失败', err);
					            }
					          });
					        }
					      },
					      fail: (err) => {
					        console.error('下载失败', err);
					      }
					    });
				})
			},
			getAll(receivedMsg) {
				let totalPay = 0
				const redList = []
				// 用于存储 tenementOrderParent 相同的项
				const groupedItems = {};
				// 遍历 receivedMsg.list 数组
				receivedMsg.forEach(item => {
					if (item.payState == 1) {
						totalPay += item.paymentAmount
						if (item.tenementOrderParent === '') {
							// 如果 tenementOrderParent 为空，添加 dingPay 字段并添加到 redList
							let newItem = {
								...item,
								ziList: [],
								dingPay: item.paymentAmount
							};
							newItem.ziList.push(item)
							redList.push(newItem);
						} else {
							// 如果 tenementOrderParent 不为空，将相同 tenementOrderParent 的项分组
							if (!groupedItems[item.tenementOrderParent]) {
								groupedItems[item.tenementOrderParent] = {
									ziList: [],
									dingPay: 0
								};
							}
							groupedItems[item.tenementOrderParent].ziList.push(item);
							groupedItems[item.tenementOrderParent].dingPay += item.paymentAmount;
							groupedItems[item.tenementOrderParent].paymentTime = item.paymentTime;
							groupedItems[item.tenementOrderParent].payDay = item.payDay;
							groupedItems[item.tenementOrderParent].payState = item.payState;
						}
					}

				});
				// 将分组后的对象添加到 redList
				for (const key in groupedItems) {
					redList.push({
						tenementOrderParent: key,
						...groupedItems[key]
					});
				}

				//   receivedMsg.list.map(item=>{
				// let obj ={
				// 	...item,
				// 	dingPay:0,
				// 	ziList:[]
				// }
				//    if (item.payState == 1) {
				// 	 obj.ziList.push(item)
				// 	 if(item.tenementOrderParent ){

				// 	 }
				// 	 obj.dingPay +=item.paymentAmount
				// 	 this.orderPay+=item.paymentAmount
				// 	  this.allPay+=item.paymentAmount
				// 	  redList.push(obj)
				//    }

				//   })
				this.allPay = totalPay;
				this.dataList = redList

			},
			getCurrentYear() {
				const year = new Date().getFullYear();
				return `${year}`;
			},
			confirm(e) {
				this.pageIndex.time = e.year
				const {
					firstDay,
					lastDay
				} = this.getYearFirstAndLastDay(e.year)
				this.$http.sendRequest('/cerePropertyOrder/queryByName', 'POST', {
					relatedMerchants: this.merchants,
					paymentTimeStart: firstDay,
					paymentTimeEnd: lastDay
				}, 1).then(res => {
					console.log(res)
					if (res.data.data.length > 0) {
						this.getAll(res.data.data[0].cerePropertyOrderList)
					} else {
						this.dataList = []
						this.allPay = 0
					}
				})
			},
			getYearFirstAndLastDay(year) {
				console.log(year)
				const firstDay = new Date(year, 0, 1);
				const lastDay = new Date(year, 11, 31);
				console.log(firstDay.toISOString().split('T'))
				return {
					firstDay: firstDay.toISOString().split('T')[0],
					lastDay: lastDay.toISOString().split('T')[0]
				}
			},
			formatDateTime(dateTimeStr) {
				// 创建 Date 对象
				const date = new Date(dateTimeStr);
				// 获取月份，由于 getMonth() 返回值从 0 开始，所以要加 1，并确保为两位数字
				const month = String(date.getMonth() + 1).padStart(2, '0');
				// 获取日期，并确保为两位数字
				const day = String(date.getDate()).padStart(2, '0');
				// 获取小时，并确保为两位数字
				const hours = String(date.getHours()).padStart(2, '0');
				// 获取分钟，并确保为两位数字
				const minutes = String(date.getMinutes()).padStart(2, '0');

				// 按照所需格式拼接并返回结果
				return `${month}月${day}日 ${hours}:${minutes}`;
			},
			formatDate(dateStr) {
				// 使用 split 方法将日期字符串按 - 分割成数组
				const [year, month, day] = dateStr.split('-');
				// 将 month 和 day 转换为数字，去除可能存在的前导零
				const formattedMonth = parseInt(month, 10);
				const formattedDay = parseInt(day, 10);
				// 按照目标格式拼接字符串
				return `${formattedMonth}月${formattedDay}号`;
			},
			currentTime() {
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1; // 月份从0~11，所以加一
				let day = date.getDate();
				let hours = date.getHours();
				let minutes = date.getMinutes();
				let seconds = date.getSeconds();

				// 为月、日、时、分、秒添加前导零（如果需要）
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				hours = hours < 10 ? '0' + hours : hours;
				minutes = minutes < 10 ? '0' + minutes : minutes;
				seconds = seconds < 10 ? '0' + seconds : seconds;

				// 拼接日期和时间字符串
				let strDate = `${year}-${month}-${day} ${hours}:${minutes}`;
				return strDate;
			},
		}
	}
</script>

<style scoped lang="scss">
	@import 'rentPayDetails.scss';

	/* 使用深度选择器覆盖 u-input 的样式*/
	::v-deep .u-input__input {
		text-align: right;
		// padding-right: 15px; 
	}

	.invoice-type-container {
		display: flex;
		align-items: center;
		padding: 10rpx;
	}

	.label {
		margin-right: 20rpx;
		color: #666;
		font-size: 28rpx;
	}

	.button-group {
		display: flex;
	}

	.invoice-btn {
		height: 30px;
		line-height: 150%;
		padding: 10rpx 24rpx;
		border: 2rpx solid #ddd;
		border-radius: 30rpx;
		margin-right: 20rpx;
		color: #333;
		font-size: 28rpx;
		transition: all 0.3s;
	}

	.invoice-btn.active {
		border-color: #3F9B6A;
		color: #3F9B6A;
		border-width: 2rpx;
	}
</style>