<template>
	<s-layout class="set-wrap" title="消费分转让" :bgStyle="{ color: '#FFF' }">
		<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="recipientUserName" label="接收人" :required="true"
					:error-message="state.usernameErrorMsg">
					<uni-easyinput v-model="state.model.recipientUserName" type="recipientUserName"
						placeholder="请输入接收人用户名" :inputBorder="false" :clearable="false" @blur="verifyUsername">
						<template v-slot:right>
							<view v-if="state.verifyUsername" class="icon">
								<image style :src="sheep.$url.static('/static/images/shibai.png')" />
							</view>
							<view v-else class="icon">
								<image :src="sheep.$url.static('/static/images/chenggong.png')" />
							</view>
						</template>
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="recipientUserPhone" label="接收人手机号" :required="true"
					:error-message="state.mobileErrorMsg">
					<uni-easyinput v-model="state.model.recipientUserPhone" type="number"
						placeholder="请输入接收人手机号" :inputBorder="false" :clearable="false"
						@blur="verifyPhone" >
						<template v-slot:right>
							<view v-if="state.verifyMobile" class="icon">
								<image style :src="sheep.$url.static('/static/images/shibai.png')" />
							</view>
							<view v-else class="icon">
								<image :src="sheep.$url.static('/static/images/chenggong.png')" />
							</view>
						</template>
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="mobile" label="手机号" class="mobile loginUniFormItem ss-p-t-10"
					>
					<uni-easyinput v-model="state.model.smsCodeUseReqDTO.mobile" type="smsCodeUseReqDTO"
						placeholder="请输入验证码" :inputBorder="false" :clearable="false" :disabled="true">
						<template v-slot:right>
							<button class="ss-reset-button code-btn code-btn-start" :disabled="verifyUsername == true || state.verifyMobile == true"
								:class="{ 'disabled': verifyUsername == true || state.verifyMobile == true }"
								@tap="getSmsCode('consumptionTransfers', state.model.smsCodeUseReqDTO.mobile)">
								{{ getSmsTimer('consumptionTransfers') }}
							</button>
						</template>
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="smsCodeUseReqDTO.code" label="验证码" :required="true">
					<uni-easyinput v-model="state.model.smsCodeUseReqDTO.code" type="number"
						placeholder="请输入验证码" :inputBorder="false" :clearable="false" >
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="consumptionPoints" label="转让金额" :required="true">
					<uni-easyinput v-model="state.model.consumptionPoints" type="number"
						placeholder="请输入转让金额" :inputBorder="false" :clearable="false" @input="validateInput" />
				</uni-forms-item>


			</view>
		</uni-forms>
		<view class="ss-flex ss-row-center ss-col-center ss-m-t-30">
			您当前可转让的金额:<text class="text-red">{{canUseConsumptionPoints}}</text>
			<!-- <button class="ss-m-l-10 all-btn " @click="useAllPonints">全部</button> -->

		</view>
		<su-fixed bottom placeholder bg="none">
			<view class="footer-box ss-p-20 ss-flex">
				<button class="ss-rest-button btn" @tap="onSubmit">确定</button>
			</view>
		</su-fixed>

	</s-layout>
</template>


<script setup>
	import {
		computed,
		reactive,
		onBeforeMount,
		ref,
		unref,
		watch,
		nextTick
	} from 'vue';
	import sheep from '@/sheep';
	import {
		clone
	} from 'lodash';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		points2point
	} from '@/sheep/hooks/useGoods';
	import {
		email
	} from '@/sheep/validate/form';

	import AuthUtil from '@/sheep/api/member/auth';
	import ConsumptionApi from '@/sheep/api/distri/consumption';
	import {
		showAuthModal,
		closeAuthModal,
		getSmsCode,
		getSmsTimer,
		showWalletModal,
		colseWalletModal
	} from '@/sheep/hooks/useModal';
	const userInfo = computed(() => sheep.$store('user').userInfo);
	const userWallet = computed(() => sheep.$store('user').userWallet);
	const state = reactive({
		verifyUsername: true,
		verifyMobile:true,
		usernameErrorMsg: '',
		mobileErrorMsg: '',
		model: {
			recipientUserName: undefined,
			recipientUserId: undefined,
			recipientUserPhone: undefined,
			consumptionPoints: undefined,
			smsCodeUseReqDTO: {
				mobile: undefined,
				scene: 11,
				code: undefined
			}
		},
		rules: {
			recipientUserName: {
				rules: [{
					required: true,
					errorMessage: '接收人不能为空',
				}, ],
			},
			recipientUserPhone: {
				rules: [{
					required: true,
					errorMessage: '接收人手机号不能为空',
				}, ],
			},
			"smsCodeUseReqDTO.code": {
				rules: [{
					required: true,
					errorMessage: '验证码不能为空',
				}, ],
			},
			consumptionPoints: {
				rules: [{
					required: true,
					errorMessage: '转让金额不能为空',
				}, 
				{
				  validateFunction: function (rule, value, data, callback) {

				    if (value<=0) {
				      callback('转让金额不能小于等于0');
				    }
				    return true;
				  },
				},
				],
			},
		}
	});
	const canUseConsumptionPoints = computed(() => points2point(userWallet.value.integralDO.consumptionPoints));
	let lastUsername = ref('')
	async function verifyUsername(e) {
		const username = e.detail.value;
		if(username == lastUsername.value) return;
		if (username == '') {
			state.verifyUsername = true
			return false;
		}else if (username === userInfo.value.username) {
			state.usernameErrorMsg = '接收人不能为自己'
			return false;
		}
		lastUsername.value = username
		// 提交数据
		const {
			data
		} = await AuthUtil.verifyUsername(username);
		if (data) {
			state.usernameErrorMsg = '用户不存在!'
		} else {
			state.usernameErrorMsg = ''
		}
		state.verifyUsername = data
	}
	
	async function verifyPhone(e) {
		const phone = e.detail.value;
		if (phone == ''  || !state.model.recipientUserName) {
			// 为空或者没输入用户名，不调校验
			state.verifyMobile = true
			return false;
		}
		
		// 提交数据
		const {
			data
		} = await AuthUtil.verifyPhone(state.model.recipientUserName, phone);
		// false就是已经有这个用户名，可以登录，true是没有，不可以登录
		if (!data || data.mobile !== phone ) {
			state.mobileErrorMsg = '接收人用户名与手机号不匹配!'
			state.verifyMobile = true
		} else {
			state.mobileErrorMsg = ''
			state.model.recipientUserId = data.id
			state.verifyMobile = false
		}
	}
	
	async function validateInput(value) {
		// 确保输入是整数
		const intValue = parseInt(value);
		const strPoints = value.toString()
		const [integerPart, decimalPart] = strPoints.split('.')
		if (decimalPart) {
			const points = parseFloat(`${integerPart}.${decimalPart.slice(0, 2)}`);
			// 使用 nextTick 确保 DOM 更新
			nextTick(() => {
				state.model.consumptionPoints = integerPart;
			});
		}
		
		if (intValue > parseInt(canUseConsumptionPoints.value)) {
			nextTick(() => {
				state.model.consumptionPoints = parseInt(canUseConsumptionPoints.value); 
			});

		} else {
			nextTick(() => {
				state.model.consumptionPoints = intValue; 
			});
		}
	}

	// 提交审核
	const FormRef = ref(null);
	const onSubmit = async () => {
		
		if(state.model.recipientUserName === userInfo.value.username){
			uni.showToast({
				title: '不能给自己转账',
				icon: 'none',
				duration: 2000
			})
			return;
		}else if (state.verifyUsername ) {
			return;
		}else if(state.verifyMobile ){
			return;
		}
		// 参数校验
		const validate = await unref(FormRef)
			.validate()
			.catch((error) => {
				console.log('error: ', error);
			});
		if (!validate) {
			return;
		}
		const {
			data,
			code
		} = await ConsumptionApi.createConsumptionLog(state.model);
		if (code === 0) {
			showWalletModal({msg:"转账成功"})
			uni.$emit('consumptionTransfersComplete');
			sheep.$router.redirect('/pages/user/wallet/score')
		}
	}

	const isLogin = computed(() => sheep.$store('user').isLogin);
	// 监听到在这个页面登陆，并刷新页面
	watch(
		() => isLogin.value,
		(newVal) => {
			if (newVal) {
				window.location.reload()
			}
		}, {
			deep: true, // 深度监听
		},
	);
	
	onLoad(async (options) => {
		if (!isLogin.value) {
			showAuthModal();
		}
		state.model.smsCodeUseReqDTO.mobile = userInfo.value.mobile
	});
</script>

<style lang="scss" scoped>
	.code-btn-start {

		width: 158rpx;
		height: 56rpx;
		line-height: normal;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		border-radius: 28rpx;
		font-size: 26rpx;
		font-weight: 500;
		color: #fff;

	}

	.disabled {
		border: 1px solid #f7f7f7;
		background: gainsboro !important;
	}

	.icon {
		display: flex;
		align-items: center;
		margin-right: 7rpx
	}

	.icon image {
		width: 35rpx;
		height: 35rpx;
	}

	:deep() {

		.file-picker__progress {
			height: 0 !important;
		}

		.uni-list-item__content-title {
			font-size: 28rpx !important;
			color: #333333 !important;
			line-height: normal !important;
		}

		.uni-icons {
			font-size: 40rpx !important;
		}

		.is-disabled {
			color: #333333;
		}
	}

	:deep(.disabled) {
		opacity: 1;
	}

	.gender-name {
		font-size: 28rpx;
		font-weight: 500;
		line-height: normal;
		color: #333333;
	}

	.title-box {
		font-size: 28rpx;
		font-weight: 500;
		color: #666666;
		line-height: 100rpx;
	}

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

	.btn-two {
		width: 310rpx;
		height: 80rpx;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		border-radius: 40rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: $white;
	}

	.radio-dark {
		filter: grayscale(100%);
		filter: gray;
		opacity: 0.4;
	}

	.content-img {
		border-radius: 50%;
	}

	.header-box-content {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		overflow: hidden;
		border-radius: 50%;
	}

	.avatar-action {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 0;
		z-index: 1;
		width: 160rpx;
		height: 46rpx;
		background: rgba(#000000, 0.3);

		.avatar-action-btn {
			width: 160rpx;
			height: 46rpx;
			font-weight: 500;
			font-size: 24rpx;
			color: #ffffff;
		}
	}

	// 绑定项
	.account-list {
		background-color: $white;
		height: 100rpx;
		padding: 0 20rpx;

		.list-img {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10rpx;
		}

		.list-name {
			font-size: 28rpx;
			color: #333333;
		}

		.info {
			.avatar {
				width: 38rpx;
				height: 38rpx;
				border-radius: 50%;
				overflow: hidden;
			}

			.name {
				font-size: 28rpx;
				font-weight: 400;
				color: $dark-9;
			}
		}

		.bind-box {
			width: 100rpx;
			height: 50rpx;
			line-height: normal;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;

			.bind-btn {
				width: 100%;
				height: 100%;
				border-radius: 25rpx;
				background: #f4f4f4;
				color: #999999;
			}

			.relieve-btn {
				width: 100%;
				height: 100%;
				border-radius: 25rpx;
				background: var(--ui-BG-Main-opacity-1);
				color: var(--ui-BG-Main);
			}
		}
	}

	.list-border {
		font-size: 28rpx;
		font-weight: 400;
		color: #333333;
		border-bottom: 2rpx solid #eeeeee;
	}

	image {
		width: 100%;
		height: 100%;
	}
</style>