<template>
	<view class="cash">
		<u-navbar title="申请提现" title-bold back-icon-color="#fff" :background="{background:'rgb(255, 117, 129)'}" immersive
			:border-bottom="false" title-color="#fff">
			<view slot="right" class="u-p-r-30 u-flex u-col-center  color-fff" @click="showRule">
				<text class="rule-btn">规则</text>
			</view>
		</u-navbar>
		<view class=""
			style="background-color: #ff7581;height: 400upx;border-bottom-right-radius: 40upx;border-bottom-left-radius: 40upx;">

			<view style="font-size: 32upx;color: #FFFFFF;padding-top: 100upx;">可提现总额</view>
			<view style="font-size: 40upx;color: #FFFFFF;padding-top: 20upx;">¥ {{ mayMoney }}</view>

			<view
				style="width: 90%;height: max-content;margin-left: 40upx;background-color: #FFFFFF;box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;margin-top: 50upx;border-radius: 20upx;">
				<view style="display: flex;flex-direction: row;padding: 20upx;">
					<view style="font-size: 32upx;color: #333333;">提现金额
						<!-- <text style="font-size: 28upx;color: #ff7581;"
              v-if="shouxufei">（注：提现手续费为{{shouxufei * 100}}%）</text> -->
					</view>
				</view>
				<view
					style="display: flex;flex-direction: row;padding: 20upx;justify-content: space-between;align-items: center;">
					<view style="display: flex;align-items: center;">
						<view style="font-size: 40upx;color: #333333;">¥</view>
						<input type="number" v-model="money" placeholder="请输入金额" @input="moneyInput" @blur="moneyBlur"
							style="font-size: 40upx;color: #333333;text-align: left;margin-left: 10upx;width: 80%;" />
					</view>
					<view @click="setAllMoney"
						style="font-size: 30rpx;color: #333333;background: #ff7581;color: white;border-radius: 10rpx;padding: 7rpx 15rpx;flex-shrink: 0;">
						全部
					</view>

				</view>
				<view style="background: #E6E6E6;width: 100%;height: 1upx;"></view>

				<!-- <view style="display: flex;flex-direction: row;flex-wrap: wrap;">
          <view style="display: flex;flex-direction: row;" v-for="(item, index) in moneyList" :key="index">
            <view>
              <view style="padding: 20upx;" @click="getOut1(item.money)">
                <view
                  style="padding-top: 40upx;width: 180upx; height: 120upx;background-color: #FFFFFF;border:1px solid #ff7581;border-radius: 10upx;">
                  {{ item.money }}
                </view>
              </view>
            </view>
          </view>
        </view> -->
			</view>
			<view @click="withdraw"
				style="margin: 32upx;font-size: 18px;background: #ff7581;color: white;border-radius: 10px;height: 40px;line-height: 40px;">
				{{!isWithdraw?'观看广告提现':'立即提现'}}
			</view>

			<view style="display: flex;width: 100%;justify-content: center;">
				<view class="u-flex-1" style="color: grey;padding-bottom: 30px;padding-top: 20upx;" @click="realName">
					实名认证
				</view>
				<!-- <view class="u-flex-1" style="color: grey;padding-bottom: 30px;padding-top: 20upx;" @click="goZhifuBao">
					提现账号
				</view> -->
				<view class="u-flex-1" style="color: grey;padding-bottom: 30px;padding-top: 20upx;" @click="goqianbao">
					红包明细
				</view>
				<!-- <view style="color: grey;padding-bottom: 30px;padding-top: 20upx;width: 33%;" @click="gojilu">提现记录
        </view> -->
			</view>

			<view style="text-align: left" class="moneyList u-p-b-30">
				<view v-if="list.length" v-for="(item, index) in 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>

				<view class="page-box" v-if="!list.length">
					<view class="centre">
						<image src="../../static/images/learn/none.png" mode=""></image>
						<view class="tips">
							暂无记录
						</view>
					</view>
				</view>

			</view>

		</view>

		
		<u-modal v-model="ruleShow" confirm-text="知道了" @confirm="ruleConfirm" :title="rule_title" :title-style="{fontWeight:'700'}" confirm-color="rgb(255, 117, 129)">
			<view class="u-p-30 u-text-left">
				<scroll-view scroll-y="true" style="max-height: 50vh;" >
					<rich-text class="color-666" :nodes="rule_content"></rich-text>
				</scroll-view>
			</view>
		</u-modal>
		
		
		<view style="width: 0;height: 0;overflow: hidden;;">
			<!-- 激励视频广告 -->
			<ad-rewarded-video v-if="adRewardedVideo" ref="adRewardedVideo" adpid="1531580352" :loadnext="true" v-slot:default="{loading, error}"
				:url-callback="urlCallback" @load="onadload" @close="onadclose" @error="onaderror">
			</ad-rewarded-video>
		</view>
		
	</view>
</template>

<script>
	import { $cache_config, $cache_index,$cache_rule } from '@/store/cashe.js'
	import { init } from '@/utils/init.js'
	export default {
		data() {
			return {
				ruleShow: false,
				rule_title: "",
				rule_content: "",
				money: '',
				mayMoney: '0',
				shouxufei: '',
				moneyList: [{
						money: '10'
					},
					{
						money: '20'
					},
					{
						money: '50'
					},
					{
						money: '100'
					},
					{
						money: '200'
					},
					{
						money: '500'
					}
				],
				value: 0,
				min: '',
				token: '',
				userId: '',
				zhifubao: '',
				zhifubaoName: '',
				list: [],
				page: 1,
				limit: 10,
				totalCount: 0,
				cashMoney: 0,
				urlCallback: null,
				adRewardedVideo: true,
				adRewardedVideoloadNum: 0,
				isWithdraw: false,
				withdrawNum: $cache_config.withdrawNum,
				ruleIndex: 0,
				ruleList: $cache_rule.ruleCash||[]
			};
		},
		onLoad() {
			this.getExtractFei();
			this.getMoneyDetail();
			
			this.configInit()
			if ($cache_rule.ruleCash) {
				this.ruleInit()
				return
			}
			this.$Request.getT("app/announcement", {type: 1}).then(res => {
				if (res.code == 0 && res.data.length > 0) {
					this.ruleList = res.data
					$cache_rule.set('ruleCash',this.ruleList)
					this.ruleInit()
					this.ruleShow = true
				}
			});
		},
		onShow() {
			this.token = uni.getStorageSync('token')
			this.userId = uni.getStorageSync('userId')
			this.getcashMoney()
			this.$u.api.userinfo().then(res => {
				if (res.code === 0) {
					if (res.data.certName) {
						this.zhifubaoName = res.data.certName;
					}
					if (res.data.accountNo) {
						this.zhifubao = res.data.accountNo;
					}
					
				}
			})
			
		},
		onReachBottom: function() {
			if (this.page * this.limit < this.totalCount) {
				this.page = this.page + 1;
				this.getMoneyDetail();
			}
		},
		onPullDownRefresh: function() {
			this.page = 1;
			// that.list = []
			this.getMoneyDetail();
		},
		onNavigationBarButtonTap() {
			// this.list();
		},
		onReady() {
			this.$nextTick(()=>{
				this.adRewardedVideoloadNum = 0
				this.$refs.adRewardedVideo.load();
			})
			this.getCanCash()
		},
		methods: {
			async configInit(){
				if(!$cache_config.withdrawNum){
					const res = await init(true)
					this.withdrawNum = $cache_config.withdrawNum
				}
			},
			
			ruleInit(){
				this.rule_title = this.ruleList[this.ruleIndex].title
				this.rule_content = this.ruleList[this.ruleIndex].content
			},
			/**
			 * 规则弹窗打开
			 */
			showRule(){
				if( this.ruleList.length <= 0) {
					uni.showToast({
						title: "暂未配置规则",
						icon: 'none'
					})
					return
				}
				this.ruleInit()
				this.ruleShow = true
			},
			ruleConfirm(){
				this.ruleIndex++
				if( this.ruleIndex >= this.ruleList.length) {
					this.ruleIndex = 0
					return
				}
				this.ruleShow = false
				setTimeout(res=>{
					this.ruleInit()
					this.ruleShow = true
				},300)
			},
			/**
			 * 获取看广告状态
			 */
			getCanCash() {
				this.$Request.getT('app/cash/canCash').then(res => {
					console.log(res)
					if (res.code == 0) {
						this.isWithdraw = res.data;
					} else {
						this.isWithdraw = false;
					}
				})
			},
			/**
			 * 广告数据加载成功回调
			 * @param {Object} e
			 */
			onadload(e) {
				this.adRewardedVideo = true;
				console.log('广告数据加载成功');
			},
			
			/**
			 * 广告加载失败回调
			 * @param {Object} e
			 */
			onaderror(e) {
				if ( this.adRewardedVideoloadNum >=3 ) {
					this.adRewardedVideo = false;
					return
				} 
				this.adRewardedVideoloadNum++
				setTimeout(() => {
					this.$refs.adRewardedVideo.load();
				}, 1000); // 10
				console.log("广告加载失败")
			},
			
			/**
			 * 广告播放成功回调
			 * @param {Object} e
			 */
			async onadclose(e) {
				const detail = e.detail
				if (detail && detail.isEnded) {
					// 正常播放结束
					let res = await this.$Request.getT('app/ad/state', {
						extraKey: this.urlCallback.extra
					})
					this.getCanCash()
				} else {
					// 播放中途退出
				}
			},
			withdraw() {
					
				if ( !this.isWithdraw ) {
					this.urlCallback = {
						userId: uni.getStorageSync('userId'),
						extra: 'cash:'+uni.getStorageSync('userId') + "" + new Date().getTime(),
					}
					this.$refs.adRewardedVideo.show();
				} else {
					this.getOut()
				}
				
			},
			
			moneyInput(e) {
				let num = e.detail.value.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.money = num;
				});

			},
			moneyBlur(e) {
				let num = e.detail.value.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.money = num;
				});
			},
			setAllMoney() {
				this.money = this.mayMoney.toFixed(2)
			},
			
			/**
			 * 获取提现记录
			 */
			getMoneyDetail() {
				let that = this;
				let token = uni.getStorageSync('token')
				if (token) {
					//可以提现金额查询预估收入查询
					let data = {
						page: this.page,
						limit: this.limit
					}
					this.$Request.getT('app/cash/selectPayDetails', data).then(res => {
						this.totalCount = res.data.totalCount;
						
						if (res.data.list.length > 0) {
							if(this.page==1){
								this.list = res.data.list
							}else{
								this.list = [...this.list, ...res.data.list];
							}
						}
					})
				}

			},

			//获取收取费
			getExtractFei() {
				this.$u.get('app/common/type/152').then(res => {
					if (res.code === 0) {
						if (res.data && res.data.value) {
							this.shouxufei = res.data.value;
						}
					}
				});
				this.$u.get('app/common/type/112').then(res => {
					if (res.code === 0) {
						if (res.data && res.data.value) {
							this.cashMoney = res.data.value;
						}
					}
				});

			},
			
			/**
			 * 可提现金额
			 */
			getcashMoney() {
				let data = {
					page: this.page,
					limit: this.limit
				}
				
				this.$Request.getT('app/moneyDetails/selectUserMoney').then(res => {
					if (res.code == 0) {
						this.mayMoney = res.data.amount || 0
					}
				})
			},
			
			/**
			 * 提现记录
			 */ 
			gojilu() {
				uni.navigateTo({
					url: '/me/invite/cashList'
				});
			},
			
			/**
			 * 红包明细
			 */
			goqianbao() {
				uni.navigateTo({
					url: '/me/invite/moneyList?moneyType=1&viewType=2'
				});
			},
			
			/**
			 * 实名认证
			 */
			realName() {
				uni.navigateTo({
					url: '/me/invite/realName'
				});
			},
			
			/**
			 * 绑定支付宝
			 */
			goZhifuBao() {
				uni.navigateTo({
					url: '/me/invite/zhifubao'
				});
			},
			
			getMoney() {
				let that = this;
				let token = that.token
				let userId = that.userId
				if (token) {
					//this.$queue.showLoading("加载中...");
					//可以提现金额查询预估收入查询
					let data = {
						amount: that.money
					}
					uni.showLoading({
						title: '提现中'
					});
					this.$u.api.withdraw(data).then(res => {
						console.log(res)
						if (res.code == 0) {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
							that.money = ''
							setTimeout(function() {
								that.getcashMoney()
							}, 1500)

						} else if (res.code == 9999) {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
							setTimeout(function() {
								uni.navigateTo({
									url: '/me/invite/zhifubao'
								});
							}, 1500)
							
					    } else if (res.code == 9991) {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
							setTimeout(function() {
								uni.navigateTo({
									url: '/me/invite/realName'
								});
							}, 1500)
							
					    } else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
				}
			},
			
			getOut() {
				let that = this;
				let token = that.token
				let userId = that.userId
				let cashMoney = that.cashMoney;

				if (token) {
					
					if (!/^\d+(\.\d{1,2})?$/.test(that.money)) {
						uni.showToast({
							icon: 'none',
							title: '请输入正确金额，不能包含中文，英文，特殊字符和小数'
						});
						return;
					}
					let shouxufei = parseFloat(that.money * that.shouxufei).toFixed(2);
					if (parseFloat(that.mayMoney).toFixed(2) >= parseFloat(that.money)) {
						// if (parseFloat(that.mayMoney).toFixed(1) >= parseFloat(that.money) + shouxufei * 1) {
						if (parseFloat(that.money).toFixed(2) >= parseFloat(cashMoney)) {
							if (that.shouxufei > 0) {
								uni.showModal({
									title: "提现申请提示",
									content: `每日只可提现${this.withdrawNum}次`,
									success: (e) => {
										if (e.confirm) {
											uni.showModal({
												title: "提现申请提示",
												content: '请仔细确认收款人信息\n\n收款人姓名:' + that.zhifubaoName + '\n\n提现金额:' + that
													.money + '元\n\n收款人账号：' + that.zhifubao + '',
												// content: '请仔细确认收款人信息\n\n收款人姓名:' + that.zhifubaoName + '\n\n提现金额:' + that
												// 	.money + '元\n\n提现手续费：' + shouxufei +
												// 	'\n\n收款人账号：' + that.zhifubao + '',
												success: (e) => {
													if (e.confirm) {
														// that.money = money
														that.getMoney();
														that.getMoneyDetail();
													}
												}
											});
										}
									}
								});
								
							} else {
								uni.showModal({
									title: "提现申请提示",
									content: '每日只可提现一次',
									success: (e) => {
										if (e.confirm) {
											uni.showModal({
												title: "提现申请提示",
												content: '请仔细确认收款人信息\n\n收款人姓名:' + that.zhifubaoName + '\n\n提现金额:' + that
													.money + '元\n\n收款人账号：' + that.zhifubao +
													'',
												success: (e) => {
													if (e.confirm) {
														// that.money = money
														that.getMoney();
														that.getMoneyDetail();
													}
												}
											});
										}
									}
								});
								
							}
					
						} else {
							uni.showToast({
								icon: 'none',
								title: "提现金额必须大于或等于" + cashMoney + "元才可提现"
							});
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: "您的余额不足"
						});
					}
				} else {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}
			}
			
		}
	};
</script>

<style lang="scss" scoped>
	// @import '../../static/css/index.css';
	.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;
	}

	.cash {
		text-align: center;
		background: white;
		height: 100%;
		position: absolute;
		width: 100%;

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

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

	.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>