<!-- 提现 -->
<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 ss-m-t-30">
				<uni-forms :model="state.model" :rules="state.rules" validateTrigger="bind" labelPosition="left" border
					class="form-box" labelWidth='200' ref="FormRef">
					<view class="bg-white ss-p-x-30">
						<uni-forms-item name="quota" label="提现金额" :required="true">
							<uni-easyinput v-model="state.outMoney" type="number"
								placeholder="请输入金额" :inputBorder="false" :clearable="false"  />
						</uni-forms-item>
						<uni-forms-item name="quota" label="实到金额">
							<view class="ss-flex ss-h-100">
								{{commission}}
							</view>
						</uni-forms-item>
						<uni-forms-item name="quota" label="消费分">
							<view class="ss-flex ss-h-100">
								{{consumption}}
							</view>


						</uni-forms-item>
					</view>
				</uni-forms>
				<!-- <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="请输入金额"  />
				</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 class="ss-flex ss-row-center ss-col-center ss-m-t-30 text-red text-center">备注：实际到账金额{{withdrawCommission}}，消费分{{withdrawConsumption}}。<br>免提现手续费</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 WithdrawalApi from '@/sheep/api/distri/withdrawal';
	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,
		withdrawalPercentage:{
			withdrawCommission:0,
			withdrawConsumption:0
		},
		outMethods: [
			// {
			// 	title: "提现到微信",
			// 	value: '1'
			// },
			{
				title: "提现到支付宝",
				value: '2',
				account:''
			},
			{
				title: "提现到银行卡",
				value: '3',
				account:''
			}
		]
	});
	const withdrawCommission = computed(() => {
		return state.withdrawalPercentage.withdrawCommission * 100 + '%';
	});
	const withdrawConsumption = computed(() => {
		return state.withdrawalPercentage.withdrawConsumption * 100 + '%';
	});
	const commission = computed(() => {
		if(!state.outMoney){
			return 0;
		}
		let result = parseFloat(state.withdrawalPercentage.withdrawCommission) * state.outMoney;
		// 地板除到小数点后两位
		result = Math.floor(result * 100) / 100;
		return result;
	});
	const consumption = computed(() => {
		if(!state.outMoney){
			return 0;
		}
		let result = parseFloat(state.withdrawalPercentage.withdrawConsumption) * state.outMoney;
		// 地板除到小数点后两位
		result = Math.floor(result * 100) / 100;
		return result;
	});
	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({
			amountTotal:state.outMoney,
			withdrawalType:state.outMent
		});
		if(code === 0){
			uni.showToast({
				icon: 'success',
				title: "申请成功",
			});
			sheep.$router.redirect('/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 (parseFloat(state.outMoney) > parseFloat(canUseMoney.value)) {
			// 使用 nextTick 确保 DOM 更新
			nextTick(() => {
				state.outMoney = parseInt(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);
			}
		})
	};
	const getWithdrawalPercentage = async () => {
		const {code,data} = await WithdrawalApi.getWithdrawalPercentage();
		if(code === 0){
			state.withdrawalPercentage = data;
		}
	}

	onLoad(async(options) => {
		await getUserInfo();
		await getWithdrawalPercentage();
		// 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>