<template>
	<view class="index">
		<view>
			<view class="index_title">
				<view class="d-flex" style="justify-content: space-between;">
					<view @click="switchUser">切换账号</view>
					<view></view>
					<view style="justify-content: flex-end;display: flex;" @click="toInvoicing">
						<uni-icons type="plus" size="40rpx" color="#4b93d9" style="font-weight: bold;"></uni-icons>
						<view style="margin-top: 2rpx;">申请发票</view>
					</view>
				</view>
			</view>
			<view class="index_picker">
				<uni-datetime-picker v-model="datetimerange" type="daterange" rangeSeparator="至" @change="handleDateTimeChange"  />
			</view>
		</view>
		
		<scroll-view scroll-y="true" class="scroll-Y" @scrolltolower="onReachBottom1" :lower-threshold="0" 
			:scroll-top="scrollTop" @scroll="scrolltop" refresher-enabled="true" :refresher-triggered="refreshing"
			:refresher-threshold="50" @refresherrefresh="onRefresh">
			<view class="index_list" v-for="(item, index) in universityList" :key="index" style="margin-bottom: 20rpx;" @click="toviewinvoice(item.id,item.status)"
			:class="item.status=== 4 ?'back1':'back2'">
				<view class="d-flex jcontent-between">
					<view class="index_list_size" :class="item.status=== 4 ?'grey1':'black'">{{item.serial_number}}</view>
					<view class="index_list_color" :class="item.status=== 4 ?'grey2':'blue'">
						{{item.status==3?item.status_str+',点击获取':item.status==2?item.status_str+',点击查看':item.status_str}}
					</view>
				</view>
				<view class="d-flex jcontent-between">
					<view>开票项目</view>
					<view>{{item.project_id}}</view>
				</view>
				<view class="d-flex jcontent-between">
					<view>开票总金额</view>
					<view class="Price_color" :class="item.status=== 4 ?'grey3':'green'">￥{{item.amount}}</view>
				</view>
				<view class="d-flex jcontent-between">
					<view>抬头类型</view>
					<view>{{item.head_type}}</view>
				</view>
				<view class="d-flex jcontent-between">
					<view>抬头名称</view>
					<view>{{item.head_title}}</view>
				</view>
				<view class="d-flex jcontent-between">
					<view>申请时间</view>
					<view>{{item.create_time}}</view>
				</view>
				<view class="d-flex jcontent-between">
					<view>账期年月</view>
					<view>{{item.expire_time}}</view>
				</view>
				<view :class="item.status=== 3 ? 'index_list_box1': item.status=== 4 ?'index_list_box3':''">
					<view :class="item.status=== 3 ? 'index_list_box2': item.status=== 4 ?'index_list_box4':''" class="">
						{{item.status=== 3 ? item.status_str: item.status=== 4 ? item.status_str :''}}
					</view>
				</view>
			</view>
			
			<uni-load-more :status="status" :content-text="contentText"></uni-load-more>
			
		</scroll-view>
		
		<view class="view_icons" @tap="goTop" v-if="this.scrollTop>1500">
			<uni-icons type="arrow-up" size="40rpx" color="#fff"></uni-icons>
		</view>
		
		<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0" @close="close">
			<view class="view_popup">
				<view style="margin: 40rpx 80rpx;padding: 40rpx;" @click="login">
					<image src="../../static/weixin.png" mode="widthFix" style="width: 80rpx;"></image>
					<view>微信登录</view>
				</view>
				<view style="margin: 40rpx 80rpx;padding: 40rpx;" @click="mobile">
					<image src="../../static/mobile.png" mode="widthFix" style="width: 80rpx;"></image>
					<view>手机号登录</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import API from '@/common/js/api.js'
	export default {
		data() {
			return {
				datetimerange: [],//时间
				// 首页数据
				universityList:[],
				page: 1,//页码
				limit: 10,//每页显示几条
				status: 'more',//状态
				//显示的状态
				contentText: {
					contentdown: '查看更多',
					contentrefresh: '加载中....',
					contentnomore: '没有更多咯'
				},
				appId:'',
				redirectUri:'',
				state:'',
				scrollTop: 0,//滚动条位置
				start_date:'',//开始日期
				end_date:'',//结束日期
				refreshing: false,
			}
		},
		onLoad(options) {
			
			const url = window.location.href;
			// 获取URL中的参数对象
			const params = this.getUrlParams(url);
			
			// 获取code参数
			const code = params['code'];
			
			// 获取start参数
			const start = params['start'];
			if(!uni.getStorageSync('AccessToken')){
				this.cont()
			}
			
			if(uni.getStorageSync('AccessToken')){
				if(!uni.getStorageSync('pucode')||!uni.getStorageSync('phone')){
					uni.showToast({title: '请先绑定用户信息',icon: 'none'})
					setTimeout(()=>{
						uni.navigateTo({
							url:"/pages/login/registerphone?id=0"
						})
					},2000)
				}
			}
			
			// this.getWxCode()
		},
		onShow() {
			if(uni.getStorageSync('AccessToken')){
				this.getUniversityList();
			}
			this.$nextTick(() => {
				if(uni.getStorageSync('AccessToken')){
					this.handleClose();
				}else{
					this.showTokenExpiredPopup();
				}
			})
		},
		created() {
		    uni.$on('tokenExpired', this.showTokenExpiredPopup); // 监听 token 失效事件
		},
		beforeDestroy() {
		    uni.$off('tokenExpired', this.showTokenExpiredPopup); // 清理监听
		},
		mounted() {},
		methods: {
			handleClose() {
			  this.$refs.popup.close(); // 关闭弹窗
			},
			showTokenExpiredPopup() {
			  this.$refs.popup.open(); // 打开弹窗
			},
			onRefresh() {
				this.getUniversityList()
				if (this.refreshing) return;
				this.refreshing = true;
				setTimeout(() => {
					this.refreshing = false;
				}, 1000)
			},
			// 解析URL中的参数
			getUrlParams(url) {
				const params = {};
				url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
					params[key] = value;
				});
				return params;
			},
			cont(){
				let code = this.getUrlCode('code'); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
				let state1 = this.getUrlCode('state');
				let data = {
					code : code,
					state: state1
				}
				if(code&&state1){
					API.wx(data, res => {
						if(res.code==1){
							this.removepath()
							uni.showToast({title: res.msg,icon: 'none'})
							uni.setStorageSync('AccessToken', res.data.token);
							uni.setStorageSync('openid', res.data.openid);
							uni.setStorageSync('phone', res.data.phone);
							this.handleClose();
							this.getUniversityList();
							if(!res.data.phone || !res.data.pucode){
								uni.navigateTo({
									url:"/pages/login/registerphone?id=0"
								})
							}
						}else{
							uni.showToast({title: res.msg,icon: 'none'});
							this.login();
						}
					})
				}
			},
			getWxCode(){
				API.getWxCode({}, res => {
					if (res.code == 1) {
						this.redirectUri = res.data.redirectUri;
						this.appId = res.data.appId;
						this.state = res.data.state
					}
				})
			},
			// 首页获取数据
			getUniversityList(){
				let data = {
					limit: this.limit,
					page: this.page,
					start_date: this.start_date,
					end_date: this.end_date
				}
				this.status = 'loading'; // 加载中
				setTimeout(()=>{
					API.Home(data, res => {
						if (res.code == 1) {
							this.page = res.data.current_page;
							this.limit = res.data.per_page;
							if (this.page === 1) {
								this.universityList = res.data.data;
							} else {
								this.universityList = this.universityList.concat(res.data.data);
							}
							// 判断是否还有更多数据
							if (res.data.data.length < this.limit) {
								this.status = 'noMore'; // 没有更多数据
							} else {
								this.status = 'more'; // 还有更多数据
							}
						}
					})
				},1000)
			},
			//上拉加载
			onReachBottom1() {
				if (this.status == 'noMore') {
					return;
				}
				this.page++;
				this.getUniversityList();
			},
			// 正则匹配请求地址中的参数函数
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||[, ''])[1].replace(/\+/g, '%20')) || null
			},
			removepath(){
				// 获取当前 URL
				const url = window.location.href;
				// 使用正则表达式去掉 code 和 state 参数并替换成#/
				const newUrl = url.replace(/[\?&]code=[^&]*&?/, '?').replace(/[\?&]state=[^&]*&?/, '#/');
				// 使用 replaceState 更新 URL，而不刷新页面
				window.history.replaceState({}, document.title, newUrl);
			},
			handleDateTimeChange(value){
				if (value.length==0) {
					this.start_date = "";
					this.end_date = "";
					this.getUniversityList();
				}else{
					this.start_date = value[0];
					this.end_date = value[1];
					this.getUniversityList();
				}
			},
			// 跳转微信登录页面
			login(){
				uni.navigateTo({
					url:"/pages/login/wxlogin"
				})
			},
			// 跳转手机号登录
			mobile(){
				uni.navigateTo({
					url:"/pages/login/registerphone?id=1"
				})
			},
			// 跳转申请发票页面
			toInvoicing(){
				if(!uni.getStorageSync('AccessToken')){
					this.showTokenExpiredPopup();
					return
				}
				if(!uni.getStorageSync('phone')||!uni.getStorageSync('pucode')){
					uni.showToast({title: '请先绑定用户信息',icon: 'none'});
					setTimeout(()=>{
						uni.navigateTo({
							url:"/pages/login/registerphone?id=0"
						})
					},2000)
				}else{
					uni.navigateTo({
						url:'/pages/Invoicing/Invoicing'
					})
				}
			},
			// 切换账号
			switchUser(){
				uni.clearStorageSync();
				location.reload();
			},
			// 获取滚动条滑动数据
			scrolltop(e){
				this.scrollTop = e.detail.scrollTop
			},
			// 跳转回顶部
			goTop(){
				// const threshold = 4000; // 阈值：当滚动位置超过这个值时才执行
				// if (this.scrollTop < threshold) {
					const duration = 500; // 动画持续时间（毫秒）
					const start = this.scrollTop; // 开始的滚动位置
					const startTime = performance.now(); // 记录开始时间
					
					const scrollToTop = () => {
						const currentTime = performance.now(); // 当前时间
						const elapsed = currentTime - startTime; // 计算经过的时间
						const progress = Math.min(elapsed / duration, 1); // 计算进度（0 到 1）
					
						// 使用线性插值计算新的滚动位置
						this.scrollTop = start * (1 - progress);
					
						if (progress < 1) {
							requestAnimationFrame(scrollToTop); // 继续动画
						} else {
							this.scrollTop = 0; // 确保最终位置为 0
						}
					};
					
					// 开始滚动到顶部的过程
					requestAnimationFrame(scrollToTop);
				// } else {
				// 如果没有达到阈值，可以选择直接滚动到顶部
					// this.scrollTop = 0; // 直接设置为 0
				// }
			},
			toviewinvoice(id,status){
				if(uni.getStorageSync('AccessToken')&&status==3){
					uni.navigateTo({
						url:`/pages/Invoiced/Invoiced?id=${id}`
					})
				}else if(uni.getStorageSync('AccessToken')&&status==2){
					uni.navigateTo({
						url:`/pages/Invoiced/fail?id=${id}`
					})
				}else if(!uni.getStorageSync('AccessToken')){
					uni.showToast({title: '请先进行登入',icon: 'none'});
					this.showTokenExpiredPopup();
				}
			}
		}
	}
</script>
<style>
	page {
		/* overflow: hidden; */
		/* #ifdef H5 */
		height: 100%;
		/* #endif */
	}
</style>
<style lang="scss" scoped>
	.index{
		/* #ifdef H5 */
			height: 100%;
		/* #endif */
		/* #ifdef MP-WEIXIN || APP-PLUS */
			height: 100vh;
		/* #endif */
		font-size: 28rpx;
		
		.index_title{
			color: #4b93d9;
			padding: 40rpx;
			// font-weight: bold;
		}
		
		.index_picker{
			padding: 0px 20rpx;
			margin-bottom: 20rpx;
		}
		
		.back1{
			background-color: #ebebeb;
		}
		.back2{
			background-color: #fff;
		}
		.black{
			color: #000;
		}
		.blue{
			color: #489ed9;
		}
		.green{
			color: #7daf1d;
		}
		.grey1{
			color: #959595;
		}
		.grey2{
			color: #afafaf;
		}
		.grey3{
			color: #939393;
		}
		
		.view_icons{
			right: 5%;
			bottom: 5%;
			width: 50px;
			height: 50px;
			display: flex;
			position: fixed;
			align-items: center;
			border-radius: 40px;
			background-color: #55aaff;
			justify-content: center;
		}
		
		.view_popup{
			height: 150px;
			display: flex;
			text-align: center;
			justify-content: space-between;
		}
		
		.index_list{
			padding: 30rpx;
			line-height: 60rpx;
			color: #939393;
			position: relative;
			font-weight: bold;
			
			.index_list_size{
				font-size: 34rpx;
				font-weight: bold;
			}
			
			.index_list_color{
				font-size: 26rpx;
				font-weight: bold;
			}
			
			.Price_color{
				font-weight: bold;
			}
			
			.index_list_box1{
				border: 1px solid #d82d33;
				border-radius: 16rpx;
				line-height: 24rpx;
				padding: 4rpx;
				position: absolute;
				top: 25%;
				left: 45%;
				transform: rotate(-15deg);
				
				.index_list_box2{
					border: 1px solid #d82d33;
					border-radius: 16rpx;
					padding: 20rpx 30rpx;
					color: #d82d33;
					font-weight: bold;
				}
			}
			
			.index_list_box3{
				border: 1px solid #939393;
				border-radius: 16rpx;
				line-height: 24rpx;
				padding: 4rpx;
				position: absolute;
				top: 25%;
				left: 45%;
				transform: rotate(-15deg);
				
				.index_list_box4{
					border: 1px solid #939393;
					border-radius: 16rpx;
					padding: 20rpx 30rpx;
					color: #939393;
					font-weight: bold;
				}
			}
		}
		
		.scroll-Y{
			width: 100%;
			/* #ifdef H5 */
				height: calc(100vh - 308rpx);
				// height: calc(100vh - 108px); //去除导航栏就开启这个
			/* #endif */
			/* #ifdef MP-WEIXIN || APP-PLUS */
				height: calc(100vh - 218rpx);
			/* #endif */
		}
	}
</style>
