<template>
	<view class="container">
		<!-- <up-notify type="success" ref="uNotifyRef" duration="0" :show="true" message="Hi uview-plus"
			:safeAreaInsetTop="true">审核中</up-notify> -->
		
		<view class="upload-section">
			<!-- 状态展示 -->
			<view v-if="verifyInfo" class="verify-status">
				<view>认证状态：{{ statusText }}</view>
			</view>
			<!-- 身份证正面上传 -->
			<view class="upload-box">
				<view class="upload-title">上传身份证</view>
				<view class="upload-box-list">
					<up-upload width="335rpx" height="208rpx" :fileList="frontImageList" @afterRead="afterReadFront"
						@delete="deletePicFront" :deletable="deletable" :previewImage="true" imageMode="aspectFill" name="front"
						:maxCount="1">
						<template #trigger>
							<view class="upload-block">
								<image mode="" v-if="frontImageList.length === 0" src="/static/img/IDFront.png" class="IDFront" />

							</view>
						</template>
					</up-upload>
					<up-upload width="335rpx" height="208rpx" :fileList="backImageList" @afterRead="afterReadBack"
						@delete="deletePicBack" :previewImage="true" :deletable="deletable" imageMode="aspectFill" name="back"
						:maxCount="1">
						<template #trigger>
							<view class="upload-block">
								<image mode="aspectFill" v-if="backImageList.length === 0" src="/static/img/IDReverse.png"
									class="IDBack" />
							</view>
						</template>
					</up-upload>
				</view>
			</view>
			<!-- 身份信息输入 -->
			<view class="info-section">

				<view class="info-title">身份信息</view>
				<view class="info-form">
					<view class="form-item">
						<up-input v-model="realName" placeholder="请输入真实姓名" border="surround" clearable :customStyle="inputStyle"
							:disabled="isReadonly" inputAlign="right">
							<template #prefix>
								<view class="">姓名</view>
							</template>
						</up-input>
					</view>
					<view class="form-item">
						<up-input v-model="idCardNumber" placeholder="请输入身份证号码" border="surround" clearable
							:customStyle="inputStyle" type="idcard" @change="onIdCardChange" maxlength="18" :disabled="isReadonly"
							inputAlign="right">
							<template #prefix>
								<view class="">身份证号</view>
							</template>
						</up-input>
					</view>
				</view>
			</view>
			<view class="info-tips">
				<image src="/static/img/tips@2x.png" mode=""></image>
				<view class="">
					<view class="">上传说明:</view>
					<view class="">1.请确保身份证信息清晰可见</view>
					<view class="">2.请上传真实的身份证照片</view>
					<view class="">3.请确保光线充足，避免反光</view>
					<view class="">4.请确保姓名和身份证号与身份证照片一致</view>
				</view>
			</view>
		</view>
		<view class="kong"></view>
		<view class="footer">
			<up-button class="btn" @click="submitDetect" :disabled="!canSubmit || isProcessing || isReadonly">
				{{
          isProcessing ? "认证中..." : isRejected ? "重新提交认证" : "提交认证"
        }}
			</up-button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		init,
		query
	} from "@/api/faceVerify.js";
	import {
		useToast
	} from "@/hooks/useToast";
	import {
		useImageUpload
	} from "@/hooks/useImageUpload";
	import {
		faceVerify,
		getFaceVerify
	} from "@/api/user";
	import {
		useAppStore
	} from "@/stores/app";

	const {
		Toast
	} = useToast();
	const appStore = useAppStore();
	const idCardPicUrl = ref("");
	const isProcessing = ref(false);
	const realName = ref("");
	const idCardNumber = ref("");
	const emit = defineEmits(["fetchUserInfo"]);
	const verifyInfo = ref(null);
	const deletable = ref(true);

	// #ifdef APP
	const aliyunVerify = uni.requireNativePlugin("AP-FaceDetectModule");
	// #endif



	const certifyId = ref("");
	const metaInfo = ref("");

	// 正面上传
	const {
		imageList: frontImageList,
		afterRead: afterReadFront,
		deletePic: deletePicFront,
	} = useImageUpload({
		pid: 7,
		model: "user",
	});
	console.log("frontImageList", frontImageList.value);
	// 反面上传
	const {
		imageList: backImageList,
		afterRead: afterReadBack,
		deletePic: deletePicBack,
	} = useImageUpload({
		pid: 5,
		model: "user",
	});

	// 输入框样式
	const inputStyle = {
		backgroundColor: "#F9F7F0",
		borderRadius: "16rpx",
		padding: "28rpx 16rpx",
		fontSize: "28rpx",
		border: 'none'
	};

	const isReadonly = computed(() => {
		return (
			verifyInfo.value &&
			(verifyInfo.value.status === 0 || verifyInfo.value.status === 1)
		);
	});
	const showUploadImg = computed(() => {
		// 如果是被拒绝状态，不显示已上传的图片，允许重新上传
		if (isRejected.value) {
			return false;
		}
		return verifyInfo.value || frontImageList.value[0]?.info?.url;
	});
	const isRejected = computed(() => {
		return verifyInfo.value && verifyInfo.value.status === 2;
	});
	const statusText = computed(() => {
		if (!verifyInfo.value) return "";
		switch (verifyInfo.value.status) {
			case 0:
				return "审核中";
			case 1:
				return "已通过";
			case 2:
				return verifyInfo.value?.approveMsg || "认证被拒绝，请重新提交";
			default:
				return "";
		}
	});

	// 计算是否可以提交（基础校验）
	const canSubmit = computed(() => {
		return (
			frontImageList.value.length > 0 &&
			backImageList.value.length > 0 &&
			realName.value.trim() &&
			idCardNumber.value.trim()
		);
	});

	onLoad(() => {
		fetchFaceVerify();
	});

	// 获取实名状态
	async function fetchFaceVerify() {
		try {
			const {
				data
			} = await getFaceVerify({
				uid: appStore.uid
			});
			if (data?.list.length > 0) {
				verifyInfo.value = data.list[0];
				realName.value = verifyInfo.value.realName || "";
				idCardNumber.value = verifyInfo.value.cardId || "";
				frontImageList.value[0] = {
					url: verifyInfo.value.idCardFront,
				};
				backImageList.value[0] = {
					url: verifyInfo.value.idCardBack,
				};
				if (verifyInfo.value.status === 0 || verifyInfo.value.status === 1) {
					deletable.value = false;
				}
				// 如果是被拒绝状态，清空上传列表，允许重新上传
				// if (verifyInfo.value.status === 2) {
				//   frontImageList.value = [];
				//   backImageList.value = [];
				// }
			} else {
				verifyInfo.value = null;
				realName.value = "";
				idCardNumber.value = "";
				frontImageList.value = [];
				backImageList.value = [];
			}
		} catch (error) {
			console.error("getFaceVerify", error);
		}
	}

	function submitDetect() {
		if (isReadonly.value) {
			Toast({
				title: "当前状态不可提交"
			});
			return;
		}
		if (!frontImageList.value.length || !backImageList.value.length) {
			Toast({
				title: "请先上传身份证正反面照片"
			});
			return;
		} else if (!realName.value.trim()) {
			Toast({
				title: "请输入真实姓名"
			});
			return;
		} else if (!idCardNumber.value.trim()) {
			Toast({
				title: "请输入身份证号码"
			});
			return;
		} else if (!validateIdCard(idCardNumber.value.trim())) {
			Toast({
				title: "请输入正确的身份证号码"
			});
			return;
		}
		// 检查图片上传状态
		const frontImage = frontImageList.value[0];
		const backImage = backImageList.value[0];
		console.log(frontImage, backImage);
		if (!frontImage || !backImage) {
			Toast({
				title: "请先上传身份证正反面照片"
			});
			return;
		}
		if (frontImage?.status === "failed" || backImage?.status === "failed") {
			Toast({
				title: "有图片上传失败，请重新上传"
			});
			return;
		}
		if (frontImage?.status === "uploading" || backImage?.status === "uploading") {
			Toast({
				title: "图片正在上传中，请稍候"
			});
			return;
		}
		try {
			isProcessing.value = true;
			uni.showLoading({
				title: "开始认证"
			});
			console.log("frontImage?.info", frontImage?.info);
			const frontImageUrl = frontImage.info?.url || frontImage.url;
			const backImageUrl = backImage.info?.url || backImage.url;
			if (!frontImageUrl || !backImageUrl) {
				Toast({
					title: "图片上传失败，请重新上传"
				});
				uni.hideLoading();
				isProcessing.value = false;
				return;
			}
			const params = {
				uid: appStore.uid,
				idCardFront: frontImageUrl,
				idCardBack: backImageUrl,
				realName: realName.value.trim(),
				cardId: idCardNumber.value.trim(),
			};
			faceVerify(params)
				.then((res) => {
					uni.hideLoading();
					Toast({
						title: "认证已提交，正在审核..."
					});
					emit("fetchUserInfo");
					// 认证成功后清空所有数据
					frontImageList.value = [];
					backImageList.value = [];
					realName.value = "";
					idCardNumber.value = "";
					isProcessing.value = false;
					fetchFaceVerify(); // 重新拉取状态
				})
				.catch((err) => {
					console.log("submitDetect-err", err);
					uni.hideLoading();
					isProcessing.value = false;
					Toast({
						title: err?.msg || "认证失败，请重试"
					});
				});
		} catch (err) {
			console.log("submitDetect-err", err);
			uni.hideLoading();
			isProcessing.value = false;
			Toast({
				title: "认证失败，请重试"
			});
		}
	}

	// 身份证号码验证
	function validateIdCard(idCard) {
		const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		return reg.test(idCard);
	}
	// 身份证号码输入处理
	function onIdCardChange(value) {
		if (value) {
			idCardNumber.value = value.toUpperCase();
		}
	}
	// 重试上传
	function retryUpload(type) {
		if (type === "front") {
			frontImageList.value = [];
		} else if (type === "back") {
			backImageList.value = [];
		}
	}

	// 重新上传（清空后重新选择）
	function reUpload(type) {
		if (type === "front") {
			frontImageList.value = [];
		} else if (type === "back") {
			backImageList.value = [];
		}
	}

	//调用getMetaInfo获取MetaInfo数据
	function startVerify() {
		try {
			console.log("aliyunVerify", aliyunVerify);
			metaInfo.value = aliyunVerify.getMetaInfo();
			let p = uni.getSystemInfoSync().platform;
			if (p === "ios") {
				metaInfo.value = JSON.stringify(metaInfo);
			}
			console.log("metaInfo", metaInfo.value);
			initFn();
		} catch (error) {
			console.log("startVerify-error", error);
		}
	}

	function initFn() {
		console.log("initFn-start");
		try {
			uni.showLoading({
				title: "开始认证"
			});
			init({
					idCardPicUrl: idCardPicUrl.value,
					metaInfo: metaInfo.value,
				})
				.then((res) => {
					console.log("initFn-----", res);
					certifyId.value = res.data.certifyId || "";
					uni.hideLoading();
					aliyunVerify.verify({
							certifyId: certifyId.value,
							extParams: {},
						},
						function(response) {
							console.log("aliyunVerify", response, response?.code);
							if (response?.code == 1000) {
								queryFn();
							}
						}
					);
				})
				.catch((err) => {
					console.log("initFn-err", err);
					certifyId.value = "";
				});
		} catch (err) {
			console.log("initFn-err", err);
		}
	}

	function queryFn() {
		console.log("initFn-start");
		query({
				certifyId: certifyId.value,
			})
			.then((res) => {
				const passed = res.data && res.data.passed;
				if (passed == "T") {
					Toast({
						title: "认证成功"
					});
					emit("fetchUserInfo");
				} else {
					Toast({
						title: "认证失败，请确认身份证和人脸信息是否一致？"
					});
				}
				console.log("queryFn", res);
			})
			.catch((err) => {
				console.log("queryFn-err", err);
			});
	}

	defineExpose({
		startVerify,
	});
</script>

<style lang="scss" scoped>
	page {
		background-color: #F9F7F0;
	}

	.upload-section {
		padding: 16rpx;
	}

	.upload-box {
		padding: 16rpx;
		border-radius: 16rpx;
		background: #FFFFFF;

		&:last-child {
			margin-bottom: 0;
		}

		::v-deep .u-upload__wrap {
			// width: 100%;

			.u-upload__wrap__preview {
				// width: 100%;
				margin: 0;

				.u-upload__wrap__preview__image {
					// width: 100% !important;
				}
			}

			view:last-child {
				flex: 1;
			}
		}
	}

	.upload-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

	.upload-box-list {
		display: flex;
	}

	.upload-block {
		width: 335rpx;

	}

	.IDFront,
	.IDBack {
		width: 100%;
		height: 206rpx;
		object-fit: cover;
		border-radius: 8rpx;
	}


	.status-text {
		font-size: 22rpx;
		font-weight: 500;

		&.uploading {
			color: #fa8013;
		}

		&.failed {
			color: #ff4444;
		}

		&.success {
			color: #52c41a;
		}
	}

	.retry-btn {
		color: #fa8013;
		text-decoration: underline;
		margin-left: 10rpx;
		font-size: 20rpx;
	}

	.upload-show {
		padding: 15rpx;
		background-color: #f8f9fa;
		border-radius: 12rpx;
	}

	.info-section {
		margin: 16rpx 0;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 16rpx;
	}

	.info-tips {
		padding: 10rpx 16rpx;
		display: flex;
		background: #FEF2CE;
		border-radius: 16rpx;
		border: 1rpx solid #F8C008;

		image {
			top: 4rpx;
			width: 32rpx;
			height: 32rpx;
			margin-right: 8rpx;
		}

		view {
			flex: 1;
			color: #333333;
			font-size: 24rpx;
			line-height: 40rpx;
		}
	}

	.info-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

	.info-form {
		.form-item {
			margin-bottom: 16rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	.verify-status {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 16rpx;
		font-size: 28rpx;
		font-weight: 600;
		color: #F8C008;
		margin-bottom: 16rpx;
	}

	
.kong {
		height: calc(132rpx + constant(safe-area-inset-bottom));
		height: calc(132rpx + env(safe-area-inset-bottom));
	}
	.footer {
		width: 100%;
		background: #FFFFFF;
		box-shadow: inset 0rpx 1rpx 0rpx 0rpx #F1F3F8;
		padding: 22rpx 32rpx calc(22rpx + constant(safe-area-inset-bottom));
		padding: 22rpx 32rpx calc(22rpx + env(safe-area-inset-bottom));position: fixed;
		bottom: 0;

		.btn {
			font-size: 32rpx;
			color: #333333;
			font-weight: bold;
			background-color: #F8C008;
			border-radius: 16rpx;
			text-align: center;
			line-height: 88rpx;

			&:disabled {
				background-image: linear-gradient(to right, #ccc 0%, #ccc 100%);
				color: #999;
			}
		}
	}
</style>