<template>
	<view>
		<u-navbar :back-text="t('withdraw.title')" :back-text-style="{color: '#FFFFFF'}"
			:background="{backgroundColor: '#4E55AF'}" back-icon-color="#FFFFFF">
			<view class="flex justify-end w-full pr-[20rpx] relative">
				<navigator hover-class="none" url="/packages/pages/withdraw/record">
					<u-icon size="40" name="/static/images/common/record.png"></u-icon>
				</navigator>
			</view>
		</u-navbar>
		<view class="mx-[30rpx] pt-[20rpx]">
			<u-form :border-bottom="false" :label-width="150" label-position="top">
				<u-form-item :itemStyle="{'background':'#3d4277'}" :border-bottom="false" :label="t('withdraw.mainNet')">
					<u-input v-model="formData.method_name" type="select" :placeholder="t('withdraw.mainNetPlaceholder')" @click="showAtionSheet" />
				</u-form-item>
				<u-form-item :itemStyle="{'background':'#3d4277'}" :border-bottom="false" :label="t('withdraw.waddress')">
					<u-input v-model="formData.address" :border="false" :placeholder="t('withdraw.waddressPlaceholder')" />
				</u-form-item>
				<u-form-item :itemStyle="{'background':'#3d4277'}" :border-bottom="false"
					:label="t('withdraw.withdrawMoney')">
					<u-input type="number" v-model="formData.money" @input="checkMoney" :border="false"
						:placeholder="t('withdraw.withdrawMoneyPlaceholder')" />
				</u-form-item>
				<view class="py-[25rpx]">
					<view class="text-[#00D2E0] mb-[10rpx]">
						{{t('withdraw.userMoney')}} {{getCurrency()}}{{formatMoney(data.config.balance)}} {{getCurrency2()}}
					</view>
					<view class="text-[#00D2E0]" v-if="formData.money >0">
						<view class=" mb-[10rpx]" v-if="data.method_rate !=1">
							{{t('withdraw.rate')}} {{data.method_rate}}
						</view>
						<view class=" mb-[10rpx]" v-if="data.charge > 0.01">
							{{t('withdraw.charge')}}
							{{formatMoney(data.charge,data.method_symbol,data.method_rate,data.method_precision)}}
						</view>
						<view class="">
							{{t('withdraw.actMoney')}}
							{{formatMoney(data.act_money,data.method_symbol,data.method_rate,data.method_precision)}}
						</view>
					</view>
				</view>
			</u-form>
		</view>

		<view class="mt-[30rpx] mx-[30rpx] max-w-[750px]">
			<u-button type="primary" @click="submitHandle" :disabled="formData.method_id=='' || formData.address=='' || formData.money==''"> {{t('common.submit')}} </u-button>
		</view>

		<view class="mt-[50rpx] mx-[30rpx] pb-[30rpx]">
			<view class="font-bold flex justify-start items-center mb-[20rpx]">
				<u-icon size="32" name="info-circle-fill"></u-icon>
				<view class="ml-[10rpx]">
					{{t('withdraw.withdrawWarm')}}
				</view>
			</view>
			<view class="p-[20rpx] bg-[#3d4277] leading-loose rounded-lg" v-html="data.content"></view>
		</view>

		<u-keyboard class="max-w-[750px]" ref="uKeyboard1" mode="number" :dot-enabled="false" :tips="t('pwd.payPwd')"
			confirm-text="" cancel-text="" v-model="show_keyboard" @change="keyboardChange" @backspace="backspace"
			:show-input-val="true" :input-value="formData.pay_pwd"></u-keyboard>

		<u-action-sheet class="max-w-[750px]" :list="data.methods" v-model="show" @click="handleClick"
			:safe-area-inset-bottom="true" :cancel-text="t('common.cancel')"></u-action-sheet>
	</view>
</template>

<script lang="ts" setup>
	import { onShow } from '@dcloudio/uni-app'
	import { reactive, ref, nextTick } from 'vue'
	import { withdraw, withdrawConfig, getWithdrawMethod } from '@/api/finance'
	import { getHintDetail } from '@/api/news'
	import { formatDate, getCurrency,getCurrency2, formatMoney } from '@/utils/util'
	import { t } from '@/utils/util'

	uni.setNavigationBarTitle({ title: t('withdraw.title') })
	const formData = reactive({
		address: '',
		money: '',
		method_id: 0,
		method_name: '',
		pay_pwd: '',
		date: formatDate(Math.round(Date.now() / 1000))
	})

	const data = reactive<{
		config : any,
		methods : any,
		charge : number,
		act_money : number,
		method_charge : number,
		method_symbol : string,
		method_rate : number,
		method_precision : number,
		content : string
	}>({
		config: {
			balance: 0,
			noused_money: 0,
			min: 0,
			max: 0,
			num: 0,
			is_withdraw: false,
			need_realname: 0
		},
		methods: [],
		charge: 0,
		act_money: 0,
		method_charge: 0,
		method_symbol: '',
		method_rate: 0,
		method_precision: 2,
		content: ''
	})

	const show_keyboard = ref(false)
	const show = ref(false)
	const getData = async () => {
		data.config = await withdrawConfig({ date: formatDate(Math.round(Date.now() / 1000)) })
		if (data.config.need_realname == 1) {
			uni.redirectTo({
				url: '/pages/auth/realname'
			})
			return
		}
		if (data.config.need_set_pwd == 1) {
			uni.$u.toast(t('pwd.pwdSetFirstTips'))
			uni.redirectTo({
				url: '/pages/change_password/set_password_pay'
			})
			return
		}

		data.methods = await getWithdrawMethod()
		if (data.methods.length > 0) {
			let index = 0
			//预输入
			if (data.config.ahead.method_id != 0) {
				index = data.methods.findIndex(item => item.id === data.config.ahead.method_id)
				formData.address = data.config.ahead.address
				console.log(index)
			}

			formData.method_id = data.methods[index]['id']
			formData.method_name = data.methods[index]['text']
			data.method_charge = data.methods[index]['charge']
			data.method_symbol = data.methods[index]['symbol']
			data.method_rate = parseFloat(data.methods[index]['rate'])
			data.method_precision = data.methods[index]['precision']
		}

		const res = await getHintDetail({ id: 12 })
		data.content = res.content;
	}

	const keyboardChange = (val : string) => {
		formData.pay_pwd += val;
		if (formData.pay_pwd.length == 6) {
			show_keyboard.value = false;
			submit();
		}
	}
	const backspace = () => {
		// 删除value的最后一个字符
		if (formData.pay_pwd.length) formData.pay_pwd = (formData.pay_pwd).substr(0, (formData.pay_pwd.length) - 1);
	}

	const showAtionSheet = () => {
		show.value = true;
	}


	const handleClick = (index : number) => {
		formData.method_id = data.methods[index]['id'];
		formData.method_name = data.methods[index]['text'];
		data.method_charge = data.methods[index]['charge'];
		data.method_symbol = data.methods[index]['symbol'];
		data.method_rate = parseFloat(data.methods[index]['rate']);
		data.method_precision = data.methods[index]['precision'];
	}

	const checkMoney = (money : string) => {
		var precision = uni.getStorageSync('precision')
		// 使用正则表达式匹配小数
		var decimalMatch = money.match(/\.(\d+)/);
		if (decimalMatch) {
			if (decimalMatch[1].length >= precision) {
				nextTick(() => {
					formData.money = parseFloat(money).toFixed(precision);
				})
			}
		}
		money = parseFloat(money).toFixed(precision);
		data.charge = parseFloat(money) * data.method_charge / 100;

		data.charge = parseFloat((data.charge).toFixed(precision));
		data.act_money = parseFloat((parseFloat(money) - data.charge).toFixed(precision));
	}

	const submitHandle = async () => {
		//提现金额判断
		if (parseFloat(formData.money) - data.config.balance > 0) return uni.$u.toast(t('common.InsufficientBalance'));

		if (parseFloat(formData.money) < data.config.min) return uni.$u.toast(t('withdraw.moneyMin') + getCurrency() + data.config.min + ' ' +  getCurrency2())
		if (parseFloat(formData.money) > data.config.max) return uni.$u.toast(t('withdraw.moneyMax') + getCurrency() + data.config.max + ' ' +  getCurrency2())
		//判断提现次数
		if (!data.config.is_withdraw) return uni.$u.toast(t('withdraw.withdrawNum') + data.config.num)

		formData.pay_pwd = '';
		show_keyboard.value = true;
	}
	const submit = async () => {
		await withdraw(formData)

		uni.redirectTo({
			url: '/pages/common/successful?type=1'
		})
	}
	getData()
</script>

<style lang="scss">
	.u-tooltip-tips {
		flex: none !important;
	}
</style>