<!-- 提现 -->
<template>
	<s-layout :title="t('wallet.withdraw')">
		<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">{{ t('wallet.select_withdrawal_method') }}</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)">{{ t('wallet.not_bound_click_to_bind') }}&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="t('wallet.withdrawal_amount')" :required="true">
							<uni-easyinput v-model="state.outMoney" type="number"
								:placeholder="t('wallet.enter_withdrawal_amount')" :inputBorder="false" :clearable="false"  />
						</uni-forms-item>
						<uni-forms-item name="quota" :label="t('wallet.actual_amount_received')">
							<view class="ss-flex ss-h-100">
								{{commission}}
							</view>
						</uni-forms-item>
						<uni-forms-item name="quota" :label="t('wallet.consumption_points')">
							<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">
					{{ t('wallet.current_exchangeable_amount') }}<text class="text-red">{{canUseMoney}}</text> 
					<button class="ss-m-l-10 all-btn " @click="useAllPonints">{{ t('common.all') }}</button>
					
				</view>
				<view class="ss-flex ss-row-center ss-col-center ss-m-t-30 text-red text-center">{{ t('wallet.note',{commission:withdrawCommission,consumption:withdrawConsumption}) }}</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  }"
					>
					{{ t('common.confirm') }}
				</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';
	import { t } from '@/locale'
	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: t('wallet.withdraw_to_wechat'),
			// 	value: '1'
			// },
			{
				title: t('wallet.withdraw_to_alipay'),
				value: '2',
				account:''
			},
			{
				title: t('wallet.withdraw_to_bank_card'),
				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(t('wallet.please_select_withdrawal_method'));
			return;
		}
		if (!state.outMoney) {
			sheep.$helper.toast(t('wallet.enter_withdrawal_amount'));
			return;
		}
		if (state.outMent === '2' && !userInfo.value.alipayAccount){
			// 没绑定支付宝
			uni.showModal({
				title: t('setting.prompt'),
				content: t('wallet.alipay_not_bound'),
				confirmText:t('wallet.go_bind'),
				success: async function(res) {
					if (!res.confirm) {
						return;
					}
					showAuthModal('alipayAccount');
				},
			});
			return;
		}
		if (state.outMent === '3' && !userInfo.value.bankAccount){
			// 没绑定银行卡
			uni.showModal({
				title: t('setting.prompt'),
				content: t('wallet.bank_card_not_bound'),
				confirmText:t('wallet.go_bind'),
				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: t('wallet.application_successful'),
			});
			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>