<template>
	<view class="container">
		<up-navbar title="申请提现" :autoBack="true" bgColor="rgb(255, 117, 129)" leftIconColor="#FFF"
			:titleStyle="{color:'#FFF'}">
			<template #right>
				<view class="u-p-r-30 u-flex u-col-center" style="color: #fff;">
					<text class="rule-btn" @click="showRule">规则</text>
				</view>
			</template>
		</up-navbar>

		<view class="content">
			<view class="title">可提现总额</view>
			<view class="mayMoney">¥ {{ data.mayMoney }}</view>
			<view class="val" style="">
				<view style="display: flex;flex-direction: row;padding: 20upx;">
					<view style="font-size: 32upx;color: #333333;">提现金额</view>
				</view>
				<view class="input" style="">
					<view style="display: flex;align-items: center;">
						<view style="font-size: 40upx;color: #333333;">¥</view>
						<input type="digit" v-model="data.money" placeholder="请输入金额" @input="moneyInput"
							style="font-size: 32rpx;color: #333333;text-align: left;margin-left: 10rpx;width: 80%;" />
					</view>
					<view class="allbtn" @click="setAllMoney">
						全部
					</view>

				</view>

			</view>
			<view class="witBtn" @click="goWithdraw"> {{data.isWithdraw?'立即提现':'观看广告提现'}} </view>
			<view style="color: #666;" @click="WithdrawalAlipay">
				提现到支付宝
			</view>
			<view class="tab" style="">
				<view @click="linkTo('/pages/me/withdraw/realName')">实名认证</view>
				<!-- <view @click="linkTo('/pages/me/withdraw/alipay')">提现账号</view> -->
				<view @click="linkTo('/pages/me/withdraw/moneyList?moneyType=1&viewType=2')">红包明细</view>
			</view>

			<view class="moneyList u-p-b-30">
				<view v-if="data.list.length" v-for="(item, index) in data.list" :key="index" class="item">
					<view>
						<view style="margin-bottom: 8upx;text-align: right;">
							<text style="margin-bottom: 8upx;color: green" v-if="item.state===1"> 提现成功</text>
							<text style="margin-bottom: 8upx;color: green" v-if="item.state===0||item.state==3">
								提现中</text>
							<text style="margin-bottom: 8upx;color: #FD6416" v-if="item.state===-1||item.state===2">
								提现失败
							</text>
						</view>

						<view style="color: #999999;font-size: 28upx;">
							<view style="margin-bottom: 8upx"> 收款人账号：{{ item.zhifubao }}</view>
							<view style="margin-bottom: 8upx"> 收款人姓名：{{ item.zhifubaoName }}</view>
							<view style="margin-bottom: 8upx"> 发起时间：{{ item.createAt }}</view>
							<view style="margin-bottom: 8upx" v-if="item.state===1">成功时间 {{ item.outAt }}</view>
							<view style="margin-bottom: 8upx;color: #FD6416" v-if="item.state===-1||item.state===2">
								失败原因：{{ item.refund }}
							</view>

							<view style="margin-bottom: 8upx;text-align: right;">
								<!-- 提现金额： -->
								<text style="color: #FD6416;font-size: 32upx;font-weight: 600"> ￥{{ item.money }}</text>
							</view>
						</view>
					</view>
				</view>
				<emprty-card v-if="!data.list.length" />
			</view>

		</view>


		<up-modal :show="data.ruleShow" confirm-text="知道了" title="规则说明" :title="data.rule_title"
			:title-style="{fontWeight:'700'}" @confirm="ruleConfirm" confirm-color="rgb(255, 117, 129)">
			<view class="u-p-30 u-text-left" v-if="data.ruleShow">
				<scroll-view scroll-y="true" style="max-height: 50vh;">
					<rich-text  style="text-align: justify;font-size: 18px;color: #666;"
						:nodes="data.rule_content"></rich-text>
				</scroll-view>
			</view>
		</up-modal>

		<view style="width: 0;height: 0;overflow: hidden;">
			<!-- 激励视频广告 -->
			<ad-rewarded-video ref="adRewardedw" :adpid="data.adpid" :loadnext="true" :url-callback="data.urlCallback"
				@load="onadload" @close="onadclose" @error="onaderror">
			</ad-rewarded-video>
		</view>

	</view>
</template>

<script setup>
	import { reactive, nextTick, ref } from 'vue';
	import { onReady,onLoad,onShow,onLaunch,onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
	import { selectUserMoney, selectPayDetails, canCash, state, withdraw } from '@/api/me/withdraw.js';
	import { selectUserById } from '@/api/user/user.js';
	import { announcement } from '@/api/index/index.js';
	import { commonType } from '@/api/init.js';
	import { linkTo } from '@/utils/app.js';
	
	const data = reactive({
		ruleShow: false,
		rule_title: "",
		rule_content: "",
		money: '',
		mayMoney: '0',
		list: [],
		page: 1,
		limit: 10,
		totalCount: 0,
		cashMoney: 0,
		urlCallback: {},
		adpid: null,
		adRewardedShow: false,
		adRewardedNum: 0,
		adRewardedVideoloadNum: 0,
		isWithdraw: false,
		userInfo: null,
		ruleIndex: 0,
		ruleList: []
	})

	const adRewardedw = ref(null);
	onLoad(() => {
		// if ( uni.getSystemInfoSync().platform == 'android' ) {
		// data.adpid = 1531580352
		// }
		// if ( uni.getSystemInfoSync().platform == 'ios' ) {
		data.adpid = 1373604770
		// }
		getExtractFei();
		getMoneyDetail();
		getCanCash()
		announcement({
			type: 1
		}).then(res => {
			data.ruleList = res
			
			ruleInit()

		})
	})
	onShow(() => {
		getcashMoney()
		getUserInfo();
	})
	onReady(() => {
		nextTick(() => {
			data.adRewardedVideoloadNum = 0
			adRewardedw.value.load();
			data.ruleShow = true
		})
	})

	onReachBottom(() => {
		if (data.page * data.limit < data.totalCount) {
			data.page = data.page + 1;
			getMoneyDetail();
		}
	})
	onPullDownRefresh(() => {
		data.page = 1;
		data.list = []
		getMoneyDetail();
	})
	function ruleInit(){
		data.rule_content = ""
		data.rule_title = data.ruleList[data.ruleIndex].title
		data.rule_content = data.ruleList[data.ruleIndex].content
	}
	/**
	 * 规则弹窗打开
	 */
	function showRule() {
		if (data.ruleList.length <= 0) {
			uni.showToast({
				title: "暂未配置规则",
				icon: 'none'
			})
			return false;
		}
		ruleInit()
		data.ruleShow = true
	}
	/**
	 * 规则确认
	 */
	function ruleConfirm() {
		console.log(1)
		data.ruleShow = false
		data.ruleIndex++
		if (data.ruleIndex >= data.ruleList.length) {
			data.ruleIndex = 0
			return
		}
		setTimeout(res => {
			ruleInit()
			data.ruleShow = true
		}, 300)
	}

	function getUserInfo() {
		selectUserById().then(res => {
			data.userInfo = res;
		})
	}

	function WithdrawalAlipay() {
		if (data.userInfo.zhiFuBao) {
			if (data.money) {
				withdraw({
					amount: data.money,
					isAlipay: 1
				}).then(res => {
					data.money = ''
					uni.setStorageSync('adRewardedNum', 0)
					setTimeout(function() {
						getcashMoney()
					}, 1500)
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				})
			}else{
				uni.showToast({
					title: "请输入金额",
					icon: 'none',
				})
			}
		} else {
			uni.showToast({
				title: "请绑定支付宝",
				icon: 'none',
			})
			setTimeout(() => {
				// 未绑定信息
				linkTo('/pages/me/withdraw/alipay')
			}, 1500)
		}
	}

	function back() {
		uni.navigateBack()
	}
	/**
	 * 获取看广告状态
	 */
	async function getCanCash() {
		canCash().then(res => {
			data.isWithdraw = res;
			console.log(res)
			if (uni.getStorageSync('adRewardedNum') >= 3) {
				data.isWithdraw = true;
				// uni.setStorageSync('adRewardedNum',0)
			} else {
				uni.setStorageSync('adRewardedNum', ((uni.getStorageSync('adRewardedNum') || 0) + 1))
			}
		})

	}
	/**
	 * 广告数据加载成功回调
	 * @param {Object} e
	 */
	function onadload(e) {
		data.adRewardedShow = true;
		uni.setStorageSync('adRewardedNum', 0)
		console.log('广告数据加载成功');
	}

	/**
	 * 广告加载失败回调
	 * @param {Object} e
	 */
	function onaderror(e) {
		if (data.adRewardedVideoloadNum >= 3) {
			return
		}
		data.adRewardedVideoloadNum++
		setTimeout(() => {
			adRewardedw.value.load();
		}, 1000); // 10
		console.log("广告加载失败", e)
	}

	/**
	 * 广告播放成功回调
	 * @param {Object} e
	 */
	async function onadclose(e) {
		const detail = e.detail
		if (detail && detail.isEnded) {
			// 正常播放结束
			console.log(data.urlCallback.extra)
			let res = await state({
				extraKey: data.urlCallback.extra
			})
			console.log(res)
			uni.setStorageSync('adRewardedNum', 0)
			getCanCash()
		} else {
			// 播放中途退出
		}
	}

	function onNavigationBarButtonTap() {
		console.log(1)
		data.ruleShow = true
	}

	/**
	 * 提现触发
	 */
	function goWithdraw() {
		if (!data.isWithdraw) {
			if (!data.adRewardedShow) {
				uni.showToast({
					icon: 'none',
					title: '广告加载失败，请稍后重试'
				});
				return
			}
			data.urlCallback = {
				userId: uni.getStorageSync('userInfo').userId,
				extra: 'cash:' + uni.getStorageSync('userInfo').userId + "" + new Date().getTime(),
			}
			adRewardedw.value.show();
		} else {
			getOut()
		}

	}

	function moneyInput(e) {
		data.money = e.detail.value.match(/^\d*(\.?\d{0,2})/g)[0] || null;
	}

	/**
	 * 全部提现赋值
	 */
	function setAllMoney() {
		data.money = getMoneys(data.mayMoney)
	}

	/**
	 * 
	 * 金额格式化
	 * money:金额
	 * 保留两位小数&不四舍五入
	 */
	function getMoneys(money) {
		if (!money || isNaN(money)) return "0.00";
		let num = parseFloat(money + '') + '';
		num = parseInt(money * 100 + '') / 100 + ''

		let reg = /(-?\d+)(\d{4})/;
		while (reg.test(num)) {
			num = num.replace(reg, "$1,$2");
		}

		let idx = num.indexOf('.')
		if (idx === -1) {
			num = num + '.00'
		}

		if (idx > 0) {
			let num_per = num.substring(0, idx) + '.'
			let num_next = num.substring(idx + 1).padEnd(2, '0')
			num = num_per + num_next
		}

		return num;
	}

	/**
	 * 获取提现记录
	 */
	function getMoneyDetail() {
		selectPayDetails({
			page: data.page,
			limit: data.limit
		}).then(res => {
			data.totalCount = res.totalCount;
			if (res.list.length > 0) {
				data.list = [...data.list, ...res.list];
			}
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 500);
		})
	}

	/**
	 * 获取最低提现金额
	 */
	function getExtractFei() {
		commonType(112).then(res => {
			if (res && res.value) {
				data.cashMoney = res.value;
			}
		});
	}

	/**
	 * 可提现金额
	 */
	const totalMoney=ref(0)
	function getcashMoney() {
		selectUserMoney().then(res => {
			data.mayMoney = getMoneys(res.amount) || 0
			totalMoney.value=res.amount||0
		})
	}

	/**
	 * 跳转
	 * @param {Object} url
	 */
	function navTo(url) {
		uni.navigateTo({
			url: url
		});
	}

	function getMoney() {
		uni.showLoading({
			title: '提现中'
		});
		withdraw({
			amount: data.money
		}).then(res => {
			console.log(res)
			data.money = ''
			uni.setStorageSync('adRewardedNum', 0)
			setTimeout(function() {
				getcashMoney()
			}, 1500)
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}).catch(res => {
			if (res.code == 9991) {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				setTimeout(function() {
					linkTo('/pages/me/withdraw/alipay')
				}, 1500)
			} else {

			}
		})
	}

	function getOut() {

		if (!/^\d+(\.\d{1,2})?$/.test(data.money)) {
			uni.showToast({
				icon: 'none',
				title: '请输入正确金额，不能包含中文，英文，特殊字符和小数'
			});
			return;
		}
		if (!data.userInfo.accountNo) {
			uni.showToast({
				icon: 'none',
				title: "请先实名认证"
			});
			setTimeout(() => {
				linkTo('/pages/me/withdraw/realName')
			}, 1500)
			return;
		}
		console.log(data.mayMoney);
		console.log(parseFloat(data.mayMoney));
		if (totalMoney.value*1 >= parseFloat(data.money)) {
			if (parseFloat(data.money).toFixed(2) >= parseFloat(data.cashMoney)) {
				uni.showModal({
					title: "提现申请提示",
					content: '每日只可提现一次',
					success: (e) => {
						if (e.confirm) {
							setTimeout(() => {
								uni.showModal({
									title: "提现申请提示",
									content: '请仔细确认收款人信息\n\n收款人姓名:' + data.userInfo.certName +
										'\n\n提现金额:' + data
										.money + '元\n\n收款人账号：' + data.userInfo.accountNo + '',

									success: (e) => {
										if (e.confirm) {
											console.log(data.money)
											getMoney();
											getMoneyDetail();
										}
									}
								});
							}, 200)
						}
					}
				});


			} else {
				uni.showToast({
					icon: 'none',
					title: "提现金额必须大于或等于" + data.cashMoney + "元才可提现"
				});
			}
		} else {
			uni.showToast({
				icon: 'none',
				title: "您的余额不足"
			});
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		text-align: center;
		background: white;
		position: absolute;
		width: 100%;

		.nav {
			width: 100%;

			position: fixed;
			background-color: #ff7581;
			left: 0;
			top: 0;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 100rpx 30rpx 15rpx 30rpx;

			.navTitle {
				color: #fff;
				font-size: 32rpx;
				font-weight: bold;
			}

			.ruleBtn {
				font-size: 30rpx;
				color: #fff;
			}
		}

		.content {
			background-color: #ff7581;
			height: 500rpx;
			border-bottom-right-radius: 40rpx;
			border-bottom-left-radius: 40rpx;

			.title {
				font-size: 32rpx;
				color: #FFFFFF;
				padding-top: 230rpx;
			}

			.mayMoney {
				font-size: 40rpx;
				color: #FFFFFF;
				padding-top: 20rpx;
			}

			.val {
				width: 90%;
				height: max-content;
				margin-left: 40rpx;
				background-color: #FFFFFF;
				box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;
				margin-top: 50rpx;
				border-radius: 20rpx;

				.input {
					display: flex;
					padding: 20rpx;
					justify-content: space-between;
					align-items: center;
				}

				.allbtn {
					font-size: 28rpx;
					color: #333333;
					background: #ff7581;
					color: white;
					border-radius: 10rpx;
					padding: 7rpx 15rpx;
					flex-shrink: 0;
				}
			}

			.witBtn {
				margin: 32rpx;
				font-size: 36rpx;
				background: #ff7581;
				color: white;
				border-radius: 20rpx;
				height: 80rpx;
				line-height: 80rpx;
			}

			.tab {
				width: 100%;
				display: flex;
				width: 100%;
				justify-content: space-around;

				>view {
					font-size: 28rpx;
					color: #666;
					padding-bottom: 60rpx;
					padding-top: 20rpx;
				}
			}

			.moneyList {
				text-align: left
			}
		}

		.cash-top {
			padding: 32upx 32upx 50upx 32upx;
			/* border-bottom: 1px solid gainsboro; */
			background: #5074FF;
		}

		.leiji {
			font-size: 14px;
			color: #ffffff;
			margin-bottom: 10px;
		}
	}

	.rule-btn {
		font-size: 16px;
		// padding: 2rpx 10rpx;
		// border: 1px solid rgba(255, 255, 255, .8);
		// border-radius: 4rpx;
	}

	.view2-view-text {
		font-size: 14px;
		color: #000000;
		margin-left: 20upx;
		width: 80%;
	}

	.view2-view-image-right {
		width: 18upx;
		height: 30upx;
		margin-left: 50upx;
	}

	.moneyList {
		.item {
			background: white;
			padding: 32rpx;
			margin: 32rpx;
			font-size: 28rpx;
			box-shadow: 7px 9px 34px rgba(0, 0, 0, 0.1);
			border-radius: 16upx;
		}

		.item:first-child {
			margin-top: 0;
		}
	}


	.centre {
		text-align: center;
		padding: 200rpx 0;
		font-size: 32rpx;
		box-sizing: border-box;

		image {
			width: 360rpx;
			height: 360rpx;
			// margin-bottom: 20rpx;
			margin: 0 auto 20rpx;
			// border: 1px dotted #000000;
		}

		.tips {
			font-size: 34rpx;
			color: #999999;
			margin-top: 20rpx;
		}

		.btn {
			margin: 80rpx auto;
			width: 600rpx;
			border-radius: 32rpx;
			line-height: 90rpx;
			color: #ffffff;
			font-size: 34rpx;
			background: #ff7581;
		}
	}
</style>