<template>
	<view class="invoice">
		<view class="select">
			<view class="day-inf" @click="getMouth">
				{{chooseDay}}
				<view class="unfold-img">
					<text class="lg text-gray cuIcon-unfold"></text>
				</view>
			</view>
			<view class="record" @click="gobillingRecord">
				开票记录
			</view>
		</view>
		<view>
			<!-- v-model="checked" @change="checkboxChange" -->
			<checkbox-group @change="checkboxChange">
				<view class="content-list" v-for="(item,index) in orderData.orderList" :key="item.id">
					<view class="active-check">
						<label class="check-style">
							<checkbox :value="item.orderSn" :checked="item.checked" class="round">
							</checkbox>
						</label>
						<view>
							<view class="station-name">{{item.stationName==null?'--':item.stationName}}</view>
							<view class="station-time">{{item.createTime==null?'--':item.createTime}}</view>
						</view>
					</view>
					<view>
						<view class="orders-price">￥{{item.trRealAmt==null?'0':item.trRealAmt}}</view>
						<view class="free-type">换电消费</view>
					</view>
				</view>
			</checkbox-group>
		</view>
		<view class="footer-box">
			<view class="check-page">
				<checkbox-group class="page-check" @change="allChoose">
					<label style="text-align: center;">
						<checkbox class="round" :disabled="useCheck" :checked="isAllChecked" value="1">
						</checkbox>
						<view>本页全选</view>
					</label>
				</checkbox-group>
				<checkbox-group class="page-check" @change="whole">
					<label style="text-align: center;">
						<checkbox class="round" :disabled="useCheck" :checked="wholeChecked" value="2">
						</checkbox>
						<view>全部选择</view>
					</label>
				</checkbox-group>
			</view>
			<view>
				<u-button color="#4C91FF" shape='circle' :disabled="nextStep" @click="goInvoiceInf">下一步</u-button>
			</view>
		</view>
		<u-datetime-picker ref="picker" v-model="chooseValue" mode="year-month" :show="timeShow" @confirm="confirm" @cancel="cancel"
			:immediateChange='true'>
		</u-datetime-picker>
	</view>
	<view v-if="orderData.orderList == null || orderData.orderList.length == 0">
		<view class="nonePage">
			<view class="noneBg">
			</view>
		</view>
	</view>
</template>

<script setup>
	import config from '@/common/config/config.js';
	import {
		reactive,
		ref,
	} from "vue";
	import {
		onLoad,
		onShow,
		onReachBottom,
		onUnload,
		onHide,
		onTabItemTap,
		onPullDownRefresh
	} from "@dcloudio/uni-app";
	const chooseValue = ref(Date.now())
	const chooseDay = ref()
	const checked = ref([])
	const checkboxValue1 = ref([]);
	const timeShow = ref(false)
	const orderData = reactive({ //请求的订单列表
		orderList: [],
		orderAskIng: []
	})
	const page = ref(1) //触底加载增加的页数
	const totalPages = ref() //总页数，用于判断是否加载完
	const isAllChecked = ref(false)
	const wholeChecked = ref(false)
	const nextStep = ref(true)
	const totalPrice = ref(0)
	const invoiceList = ref([])
	const orderType = ref(0)
	const useCheck=ref(false)
	const picker=ref(null)
	// 
	onLoad(async () => {})
	onShow(async () => {
		//
		chooseDay.value = await getDay(0) //获取当前时间年月
		page.value = 1
		await getOrder(0, chooseDay.value)
		
		nextStep.value = true
		// 勾选后切换页面清除已勾选的
		isAllChecked.value = false
		wholeChecked.value = false
		checked.value = []
		orderData.orderList.forEach(item => item.checked = false);
		console.log(orderData.orderList,'orderData.orderList====show');
		// setTimeout(()=>{
			if(orderData.orderList == null || orderData.orderList.length == 0){
				useCheck.value=true
			}else{
				useCheck.value=false
			}
		// },1000)
		
	})
	onReachBottom(async () => {
		if (page.value < totalPages.value) {
			page.value += 1
			await getOrder(1, chooseDay.value)
			orderData.orderList = orderData.orderList.concat(orderData.orderAskIng)
		} else {
			uni.$u.toast('没有更多啦');
		}
	})

	// 全选
	const whole = (e) => {
		wholeChecked.value = !wholeChecked.value;
		uni.showLoading({
			title: '加载中'
		});
		if (wholeChecked.value) {
			nextStep.value = false
			isAllChecked.value = true
			uni.$request({
				url: config.wxUrl_pay + 'pay/invoice/getAmount'
			}).then(res => {
				totalPrice.value = res.data.data
				console.log(res.data.data, 'qwwwwwwwwwwww');
				orderType.value = 1
				uni.hideLoading();
			}).catch((err) => {
				uni.showToast({
					title: '加载失败',
					duration: 2000,
					icon: 'error'
				});
			})
		} else {
			uni.hideLoading();
			nextStep.value = true
			isAllChecked.value = false
			orderType.value=0
		}
		orderData.orderList.map(item => item.checked = wholeChecked.value);

	}
	const allChoose = (e) => {
		isAllChecked.value = !isAllChecked.value;

		orderData.orderList.map(item => item.checked = isAllChecked.value);

		if (isAllChecked.value) {
			totalPrice.value = 0
			nextStep.value = false
			for (let i = 0; i < orderData.orderList.length; i++) {
				if (!checked.value.includes(orderData.orderList[i].orderSn)) {
					checked.value.push(orderData.orderList[i].orderSn)
				}
				console.log(orderData.orderList[i].trRealAmt,'orderData.orderList[i].trRealAmt')
				totalPrice.value = (totalPrice.value * 100 + orderData.orderList[i].trRealAmt * 100) / 100;
				// checked.value.push(orderData.orderList[i].id)
			}
			invoiceList.value = checked.value
			console.log(checked.value, 'checked.value', totalPrice.value);
		} else {
			checked.value = []
			nextStep.value = true
			wholeChecked.value = false
		}
	}
	const getOrder = async (type, data) => {
		await uni.$request({
			url: config.wxUrl_pay + 'pay/invoice/pageSwapOrder?pageNo=' +
				page.value + "&pageSize=" + 10 + "&date=" + data
		}).then(res => {
			console.log(res, 'pppp');
			res.data.data.data.forEach((item) => {
				Object.assign(item, {
					checked: false
				})
			})
			if(wholeChecked.value==true){
				res.data.data.data.forEach((item) => {
						item.checked=true
					
				})
			}
			console.log(res.data.data.data, '==========>');
			if (type == 1) {
				orderData.orderAskIng = res.data.data.data //触底加载的列表
			} else {
				orderData.orderList = res.data.data.data //渲染的列表
			}
			totalPages.value = res.data.data.totalPage //总页数
		}).catch((err) => {
			uni.showToast({
				title: '加载失败',
				duration: 2000,
				icon: 'error'
			});
		})
	}
	const goInvoiceInf = () => {

		uni.navigateTo({
			url: '../invoiceInf/invoiceInf?price=' + totalPrice.value +
				'&list=' + JSON.stringify(invoiceList.value) + '&orderType=' + orderType.value
		})
	}
	const gobillingRecord = () => {
		picker.value.innerValue=Date.now()
		console.log('show =',picker.value);
		uni.navigateTo({
			url: '../billingRecord/billingRecord'
		})
	}
	// 多选
	const checkboxChange = (n) => {
		console.log('n.detail.value', n.detail.value);
		// 
		invoiceList.value = n.detail.value
		if (n.detail.value.length !== 0) {
			nextStep.value = false
			console.log(nextStep.value, 'nextStep.value');
		} else {
			console.log('null');
			nextStep.value = true
		}
		for (var i = 0; i < orderData.orderList.length; i++) {
			var item = orderData.orderList[i];
			if (n.detail.value.includes(item.orderSn)) {
				item.checked = true;
			} else {
				item.checked = false;
			}
		}

		// 是否全部选中
		let allSelected = orderData.orderList.every(item => item.checked === true);
		if (allSelected) {
			isAllChecked.value = true;
		} else {
			isAllChecked.value = false;
			wholeChecked.value=false
			orderType.value=0
		}
		// 价格
		totalPrice.value = 0
		orderData.orderList.forEach(item => {
			if (n.detail.value.indexOf(item.orderSn) > -1) {
				totalPrice.value = (totalPrice.value * 100 + item.trRealAmt * 100) / 100;
			}
		});
		console.log(totalPrice.value, 'totalPrice');
	};

	const getMouth = () => {
		timeShow.value = true
		
	}
	const cancel = () => {
		timeShow.value = false
	}
	const confirm = () => {
		setTimeout(() => {
			// 勾选后切换页面清除已勾选的
			isAllChecked.value = false
			checked.value = []
			orderData.orderList.forEach(item => item.checked = false);

			let n = new Date(chooseValue._rawValue)
			let year = n.getFullYear()
			let month = n.getMonth() + 1
			console.log('month: ', month, toString.call(month));
			month = month < 10 ? ('0' + month) : month
			let res = year + '-' + month
			chooseDay.value = res
			timeShow.value = false
			page.value = 1 //点击查询页面请求第一页
			getOrder(0, res)
			console.log('3333',chooseValue._rawValue);
		}, 500)
	}
	const getDay = (day) => {
		var today = new Date();
		var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
		today.setTime(targetday_milliseconds);
		var tYear = today.getFullYear();
		var tMonth = today.getMonth();
		var tDate = today.getDate();
		tMonth = doHandleMonth(tMonth + 1);
		tDate = doHandleMonth(tDate);
		// return tYear + "-" + tMonth + "-" + tDate;
		return tYear + "-" + tMonth;
	}
	const doHandleMonth = (month) => {
		var m = month;
		if (month.toString().length == 1) {
			m = "0" + month;
		}
		return m;
	}
</script>

<style lang='less' scoped>
	.invoice {
		background: #F2F6F7;
	}

	.select {
		font-size: 28rpx;
		color: #171717;
		display: flex;
		justify-content: space-between;
		padding: 0 32rpx;
		/* padding: 16rpx 32rpx 24rpx 32rpx; */
		margin: 0rpx 0 24rpx 0;
		padding-top: 16rpx;
	}

	.day-inf {
		display: flex;

	}

	.unfold-img {
		margin-left: 8rpx;
	}

	.record {
		font-size: 28rpx;
		font-weight: 400;
		color: #4C91FF;

	}

	.content-list {
		width: 100%;
		padding: 32rpx 96rpx 32rpx 32rpx;
		display: flex;
		justify-content: space-between;
		background: #FFFFFF;
		box-shadow: -2px 2px 8px 0px #7AA7D026;
		margin-bottom: 16rpx;
	}

	.station-name {
		color: #171717;
		font-size: 28rpx;
		font-weight: 400;
	}

	.station-time {
		font-size: 24rpx;
		font-weight: 400;
		color: #808080;
		margin-top: 8rpx;
	}

	.orders-price {
		color: #4C91FF;
		font-size: 32rpx;
		font-weight: 400;
		text-align: right;
	}

	.footer-box {
		width: 100%;
		position: fixed;
		bottom: 0;
		padding: 32rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		display: flex;
		justify-content: space-between;

		/deep/.u-button {
			width: 330rpx;
			height: 72rpx;
		}
	}

	.free-type {
		color: #585858;
		font-size: 20rpx;
		font-weight: 400;
		text-align: right;
		margin-top: 9rpx;
	}

	.active-check {
		display: flex;
		align-items: center;
	}

	::deep.u-checkbox,
	::deep.u-checkbox-label--left {
		flex-direction: column !important;
	}

	.active-check {}

	.check-style {
		margin-right: 25rpx;
	}

	.footer-box {
		.check-page {
			display: flex;
			font-size: 20rpx;
			font-weight: 400;
			color: #171717;

		}

		.page-check {
			display: flex;
			justify-content: center;
			margin-right: 32rpx;
		}
	}
	.nonePage {
		width: 100%;
		height: calc(100vh - 230rpx);
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.noneBg {
		width: 336rpx;
		height: 452rpx;
		background: url('@/static/user/none.png') no-repeat;
		background-size: 100% 100%;
	}
</style>
<style lang="less">
	page {
		background-color: #F2F6F7;
		padding-bottom: 150rpx;
	}

	.invoice {}
</style>