<!-- 提现 -->
<template>
	<s-layout title="提现">
		<view class="bg-white ss-modal-box ss-flex-col">
			<!-- 提现方式 -->
			<view class="modal-content">
				<view class="out-title ss-p-l-30 ss-m-y-30">选择提现方式</view>
				<radio-group @change="onTapOut">
					<label class="out-type-item" v-for="item in state.outMethods" :key="item.title">
						
						<view class="out-item ss-flex ss-col-center ss-row-between ss-p-x-30 border-bottom"
							:class="{ 'disabled-out-item': item.disabled }">
							<view class="ss-flex ss-col-center">
								<view class="check-box ss-flex ss-col-center ss-p-l-10">
								  <radio
								    :value="item.value"
								    color="var(--ui-BG-Main)"
								    style="transform: scale(0.8)"
								    :disabled="item.disabled"
								    :checked="state.payment === item.value"
								  />
								</view>
								<text class="out-title">{{ item.title }}</text>
								
							</view>
							<text style="float: right;" v-if="item.account">{{item.account}}</text>
							<text style="float: right;" v-else @click="handleBind(item.value)">暂未绑定，点击绑定&nbsp;></text>
						</view>
						
					</label>
				</radio-group>
			</view>
			<!-- 提现金额 -->
			<view class="modal-content ">
				<view class="out-title ss-p-l-30 ss-m-y-30">提现金额</view>
				<view class="ss-flex ss-row-left ss-col-center  input-money ss-m-y-30" >
					￥
					<input v-model.number="state.outMoney"  class="uni-input " type="number"
						placeholder="请输入金额" oninput="handleInput" />
				</view>
				<view class="ss-flex ss-row-center ss-col-center ss-m-t-30">
					您当前可兑换金额:￥<text class="text-red">{{canUseMoney}}</text> 
					<button class="ss-m-l-10 all-btn " @click="useAllPonints">全部</button>
				</view>
			</view>
			
			
			<!-- 工具 -->
			
			<view class="modal-footer ss-flex ss-row-center ss-col-center ss-m-t-80 ss-m-b-40 ss-flex-5">
				<button class="ss-reset-button save-btn" @tap="submit"  :disabled="state.disabled" :class="{ 'disabled-btn': state.disabled  }"
					>
					确定
				</button>
			</view>
		</view>
	</s-layout>
</template>
<script setup>
	import {
		computed,
		reactive,
		watchEffect,
		nextTick, 
		onUnmounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import { clone } from 'lodash';
	import {
		fen2yuan,
		points2point
	} from '@/sheep/hooks/useGoods';
	import md5 from 'blueimp-md5';
	import PayWalletApi from '@/sheep/api/pay/wallet';
	import { showAuthModal, showShareModal } from '@/sheep/hooks/useModal';
	const userWallet = computed(() => sheep.$store('user').userWallet);
	const userInfo = computed(() => sheep.$store('user').userInfo);
	const canUseMoney = computed(() => points2point(userWallet.value.integralDO.currentQuota));
	const alipayAccount = (account) => {
		// let account = state.model.alipayAccount;
		if (!account) {
			return false
		}
		// 手机号脱敏
		if (/^\d{11}$/.test(account)) { // 检查是否是11位数字的手机号
			return `${account.substring(0, 3)}****${account.substring(7)}`;
		} else if (/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(account)) {
			const atIndex = account.indexOf('@');
			// 邮箱用户名长度小于等于3位时，不脱敏
			if (atIndex <= 3) {
				return account;
			}
			const username = account.substring(0, Math.ceil(atIndex / 2)); // 取邮箱用户名的一半
			const domain = account.substring(atIndex); // 邮箱域名部分
			return `${username}***${domain}`;
		}
	}
	const bankAccount = (account) => {
		if (!account) {
			return false
		}
		if (account.length === 8) {
			return account.substring(0, 2) + '********' + account.substr(-2);
		} else {
			return account.substring(0, 4) + '******' + account.substr(-4);
		}
	}
	const state = reactive({
		model: {},
		orderType: 'goods', // 订单类型; goods - 商品订单, recharge - 充值订单
		outMent: '',
		outMoney:undefined,
		disabled:true,
		outMethods: [
			// {
			// 	title: "提现到微信",
			// 	value: '1'
			// },
			{
				title: "提现到支付宝",
				value: '2',
				account:''
			},
			{
				title: "提现到银行卡",
				value: '3',
				account:''
			}
		]
	});
	
	const handleBind = async (type) => {
		// console.log(type)
		if(type === '2'){
			showAuthModal('alipayAccount');
		}else if(type === '3'){
			showAuthModal('bankAccount');
		}
	}
	const submit = async () => {
		if (state.outMent === '') {
			sheep.$helper.toast('请选择提现方式');
			return;
		}
		if (!state.outMoney) {
			sheep.$helper.toast('请输入提现金额');
			return;
		}
		if (state.outMent === '2' && !userInfo.value.alipayAccount){
			// 没绑定支付宝
			uni.showModal({
				title: '提示',
				content: '未绑定支付宝账号',
				confirmText:'去绑定',
				success: async function(res) {
					if (!res.confirm) {
						return;
					}
					showAuthModal('alipayAccount');
				},
			});
			return;
		}
		if (state.outMent === '3' && !userInfo.value.bankAccount){
			// 没绑定银行卡
			uni.showModal({
				title: '提示',
				content: '未绑定银行卡',
				confirmText:'去绑定',
				success: async function(res) {
					if (!res.confirm) {
						return;
					}
					showAuthModal('bankAccount');
				},
			});
			return;
		}
		
		let {
			code,
			data
		} = await PayWalletApi.createWithdrawal({
			amount:state.outMoney,
			withdrawalType:state.outMent
		});
		if(code === 0){
			uni.showToast({
				icon: 'success',
				title: "申请成功",
			});
			sheep.$router.go('/pages/user/wallet/withdrawalLog')
			uni.$emit('createWithDrawComplete');
		}
	};
	// 切换提现方式
	function onTapOut(e) {
		state.outMent = e.detail.value;
	}
	// 提现全部积分
	async function useAllPonints(){
		const {code,data} = await PayWalletApi.getDuserInfo();
		const userCanUsePoints = parseFloat(points2point(data.integralDO.currentQuota));
		state.outMoney = parseInt(userCanUsePoints);
		state.disable = false;
	}
	watchEffect(() => {
		// 提现金额不能大于可用积分
		if (state.outMoney > canUseMoney.value) {
			// 使用 nextTick 确保 DOM 更新
			nextTick(() => {
				state.outMoney = canUseMoney.value;
			});
		}
		// 如果计算出来的当前可以使用的最大积分等于小于0 则不给输入
		if(canUseMoney.value == 0 || canUseMoney.value < 0){
			state.disabled = true
		}
		if(canUseMoney.value > 0){
			state.disabled = false
		}
	})
	
	// 获得用户信息
	const getUserInfo = async () => {
		// 个人信息
		const userInfo = await sheep.$store('user').getInfo();
		state.model = clone(userInfo);
		state.outMethods.forEach(item=>{
			
			if(item.value === '2'){
				item.account = alipayAccount(state.model.alipayAccount);
			}else if(item.value === '3'){
				item.account = bankAccount(state.model.bankAccount);
			}
			// console.log(item)
		})
	};
	onLoad(async(options) => {
		await getUserInfo();
		// refresh()
		uni.$on('alipayAccountChangeComplete', getUserInfo);
		uni.$on('bankAccountChangeComplete', getUserInfo);
	});
</script>

<style lang="scss" scoped>
	.all-btn{
		height: 60rpx;
		line-height: 60rpx;
		min-width: 80rpx;
		padding: 0 30rpx;
		border-radius: 30rpx;
		font-size: 26rpx;
		margin-right: 10rpx;
		border: 2rpx solid var(--ui-BG-Main);
		color: var(--ui-BG-Main);
	}
	.out-icon {
		width: 36rpx;
		height: 36rpx;
		margin-right: 26rpx;
	}
	
	.ss-modal-box {
		height: calc(100vh - 88rpx);
		// max-height: 1000rpx;
		.input-money {
			width:90% ;
			padding:0 10rpx;
			// text-indent: 20rpx;
			height: 80rpx;
			border: 1px solid #bbbbbb;
			border-radius: 10rpx;
			margin: 15rpx auto;
			font-size: 28rpx;
			input{
				width: 100%;
				height: 100%;
				font-size: 28rpx;
			}
		}
		.modal-header {
			position: relative;
			padding: 60rpx 20rpx 40rpx;


			.money-text {
				color: $red;
				font-size: 46rpx;
				font-weight: bold;
				font-family: OPPOSANS;

				&::before {
					content: '￥';
					font-size: 30rpx;
				}
			}

			.time-text {
				font-size: 26rpx;
				color: $gray-b;
			}

			.close-icon {
				position: absolute;
				top: 10rpx;
				right: 20rpx;
				font-size: 46rpx;
				opacity: 0.2;
			}
		}

		.modal-content {
			overflow-y: auto;

			.out-title {
				font-size: 26rpx;
				font-weight: 500;
				color: #333333;
			}

			.out-tip {
				font-size: 26rpx;
				color: #bbbbbb;
			}

			.out-item {
				height: 86rpx;
			}

			.disabled-out-item {
				.out-title {
					color: #999999;
				}
			}

			.userInfo-money {
				font-size: 26rpx;
				color: #bbbbbb;
				line-height: normal;
			}
		}

		.save-btn {
			width: 710rpx;
			height: 80rpx;
			border-radius: 40rpx;
			background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
			color: $white;
		}

		.disabled-btn {
			background: #e5e5e5;
			color: #999999;
		}

		.past-due-btn {
			width: 710rpx;
			height: 80rpx;
			border-radius: 40rpx;
			background-color: #999;
			color: #fff;
		}
	}
</style>