<template>
	<div class="container">
		<model :show="show" @close="show=false" :content="content" />
		<!-- <view class="title-back">
			<view class="left-father" @click="goBack">
				<image class="back-img" src="https://www.focusnu.com/media/directive/index/left.png" />
				<view style="font-size: 30rpx;">入职登记表</view>
			</view>
		</view> -->
		<view class="title-back" :style="{height:`${uni.getStorageSync('moveHeight')+40}px`}">
			<view class="left-father" @click="uni.navigateBack({delta:3})">
				<image class="back-img" src="https://www.focusnu.com/media/directive/index/left.png" />
				<view style="font-size: 30rpx;">入职登记表</view>
			</view>
		</view>
		<view :style="{height:`${uni.getStorageSync('moveHeight') + 30}px`}"></view>
		<view class="white-content">
			<view class="content-title">
				<view class="shu"></view>
				<view class="content-weight">银行卡</view>
				<view style="margin-top: 8rpx;margin-left: 12rpx;;font-size: 23rpx;">(选填)</view>
			</view>
			<view class="white-photo" @click="selectphoto(0)">
				<view class="photo-left">
					<view class="photo-weight">银行卡正面</view>
					<view class="photo-font">请上传银行卡正面</view>
				</view>
				<view style="position: relative;">
					<image class="photo"
						:src="fontphoto ? `${media_base_url}${fontphoto}` : `https://www.focusnu.com/media/directive/index/bankfront.png`" />
					<image style="width: 100%;height: 100%;top: 0;left: 0;z-index: 1;position: absolute;"
						:src="fontphoto ? `` : `https://www.focusnu.com/media/directive/index/bian.png`" />
					<image v-if="!fontphoto"
						style="position: absolute;top: 50%;left: 50%;width: 70rpx;height: 60rpx;transform: translate(-50%,-50%);"
						src="https://www.focusnu.com/media/directive/index/takephoto.png" />
				</view>

			</view>
			<view class="white-photo" style="margin-top: 30rpx;" @click="selectphoto(1)">
				<view class="photo-left">
					<view class="photo-weight">银行卡反面</view>
					<view class="photo-font">请上传银行卡反面</view>
				</view>
				<view style="position: relative;">
					<image class="photo"
						:src="endphoto ? `${media_base_url}${endphoto}` : `https://www.focusnu.com/media/directive/index/bankend.png`" />
					<image style="width: 100%;height: 100%;top: 0;left: 0;z-index: 1;position: absolute;"
						:src="endphoto ? `` : `https://www.focusnu.com/media/directive/index/bian.png`" />
					<image v-if="!endphoto"
						style="position: absolute;top: 50%;left: 50%;width: 70rpx;height: 60rpx;transform: translate(-50%,-50%);"
						src="https://www.focusnu.com/media/directive/index/takephoto.png" />
				</view>

			</view>
			<view class="content-title" style="margin: 20rpx 0;">
				<view class="shu"></view>
				<view class="content-weight">确认银行卡信息</view>
			</view>
			<view class="white-message">
				<view>
					<view v-for="(item,index) in nameArray" :key="index" class="one"
						@click="openLook(textArray[index])">
						<view class="one-left">{{item}}</view>
						<view class="one-right">{{textArray[index] ? textArray[index] : "自动获取" }}</view>
					</view>
				</view>
			</view>
		</view>
		<view style="display: flex;width: 100%;padding: 0 10%;justify-content: space-between;">
			<view class="back-button" @click="goBack">
				返回上一步
			</view>
			<view class="finish-button" @click="next">
				确认并继续
			</view>
		</view>
		<u-action-sheet :list="bottomlist" @click="photoclick" v-model="bottomshow"></u-action-sheet>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		media_base_url,
		base_url
	} from '@/request/index.js';
	import {
		changemessage
	} from './api/addjigou.js'
	import model from "@/compontent/public/model.vue"

	const show = ref(false);
	const content = ref("");

	const bottomshow = ref(false);
	const bottomlist = [{
		text: '拍照',
		fontSize: 40
	}, {
		text: '从相册选择',
		fontSize: 40
	}, {
		text: '图片预览',
		fontSize: 40
	}]
	const nameArray = ["开户行", "开户行卡号"];
	const textArray = reactive(["", ""]);
	const states = ["审核中", "审核未通过", "审核通过"];

	const fontphoto = ref("");
	const endphoto = ref("");

	const statesTarget = ref(0);
	const shenhe = () => {
		if (statesTarget.value == 2) {
			statesTarget.value = 0
		} else {
			statesTarget.value++
		}
	}
	const photoclick = (element) => {
		if (element==2) {
			uni.previewImage({
				urls: [headImge.value, backImge.value], // 必填，所有要预览的图片地址数组
				current: targetphoto.value ? backImge.value : headImge.value, // 可选，当前显示图片的地址，默认是 urls[0]
				indicator: 'default', // 可选，指示器样式，H5/App 有效，值为 'default'（圆点）或 'number'（数字）
				longPressActions: { // 可选，仅 App 支持，长按图片时弹出的操作项
					itemList: ['保存图片到相册'],
				},
			});
		} else {
			uni.chooseImage({
				count: 1,
				sourceType: element == 0 ? ['camera'] : ['album'],
				success: chooseRes => {
					tempImagePath.value = chooseRes.tempFilePaths[0]
					// 拍照成功后，调用上传函数
					uni.navigateTo({
						url: `/compontent/public/camera?url=${chooseRes.tempFilePaths[0]}&type=0`
					});
				},
				fail: err => {
					console.error('拍照失败：', err)
				}
			})
		}

	}
	// 本地保存的临时文件路径
	const tempImagePath = ref('')

	const targetphoto = ref(0)
	const selectphoto = (number) => {
		if (!uping.value) {
			return
		}
		targetphoto.value = number
		console.log("????", backImge.value, headImge.value)
		if (backImge.value && headImge.value) {
			// targetphoto.value = number
			bottomshow.value = true;
		} else {
			getMessage()
		}
	}

	// 拍照并上传
	function getMessage() {
		// 使用 UniApp 的 API 调用摄像头
		uni.chooseImage({
			count: 1,
			sourceType: ['album', 'camera'],
			success: chooseRes => {
				tempImagePath.value = chooseRes.tempFilePaths[0]
				// 拍照成功后，调用上传函数
				uni.navigateTo({
					url: `/compontent/public/camera?url=${chooseRes.tempFilePaths[0]}&type=0`
				});
			},
			fail: err => {
				console.error('拍照失败：', err)
			}
		})
	}

	const headImge = ref("");
	const backImge = ref("");
	// 日期转换
	function formatChineseDate(chineseDate) {
		return chineseDate.replace(/(\d+)年(\d+)月(\d+)日/, (_, y, m, d) => {
			return `${y}.${m}.${d}`;
		});
	}

	function toIsoDate(dateStr) {
		return dateStr.replace(
			/(\d{2,4})\.(\d{1,2})\.(\d{1,2})/,
			(_, y, m, d) => {
				// 月日补齐两位
				const mm = m.padStart(2, '0');
				const dd = d.padStart(2, '0');
				return `${y}-${mm}-${dd}`;
			}
		);
	}
	// 上传图片到服务器
	function uploadImage(filePath) {
		uping.value = false;
		uni.showLoading()
		uni.uploadFile({
			url: `${base_url}/api/ocr/bankCard`, // 替换为您的POST接口地址
			filePath,
			name: 'file', // 后端接收时的字段名
			header: {
				'X-Access-Token': uni.getStorageSync('token') || '',
			},
			formData: {},
			success: uploadRes => {

				if (!JSON.parse(uploadRes.data).success) {
					uni.hideLoading()
					// uping.value = true;
					savephoto(filePath, targetphoto.value);
					return
				}

				if (JSON.parse(JSON.parse(uploadRes.data).result.data).data.bankName) {
					let father = JSON.parse(JSON.parse(uploadRes.data).result.data).data;
					textArray[0] = father.bankName;
					textArray[1] = father.cardNumber;
					savephoto(filePath, targetphoto.value);
					// uping.value = true;
				} else {
					uni.hideLoading()
					uping.value = true;
				}
			},
			fail: err => {
				uni.showToast({
					title: '上传出错',
					icon: 'error'
				})
				uni.hideLoading()
			}
		})
	}
	const uping = ref(true)
	const savephoto = (filePath, type) => {
		// category: 'jg' | 'yg' | 'zz' | 'jhr'
		const now = new Date();
		const yyyy = now.getFullYear();
		const mm = String(now.getMonth() + 1).padStart(2, '0'); // 补0
		let path = '';

		switch ('yg') {
			case 'jg': // 机构
				path = `${yyyy}/${mm}/jgxx/jg`;
				break;
			case 'yg': // 员工
				path = `${yyyy}/${mm}/ygxx/yg`;
				break;
			case 'zz': // 长者
				path = `${yyyy}/${mm}/zzxx/zz`;
				break;
			case 'jhr': // 监护人
				path = `${yyyy}/${mm}/zzxx/jhr`;
				break;
			default:
				path = `${yyyy}/${mm}/temp`;
		}
		uni.uploadFile({
			url: `${base_url}/sys/common/upload`, // 替换为您的POST接口地址
			filePath,
			name: 'file', // 后端接收时的字段名
			header: {
				'X-Access-Token': uni.getStorageSync('token') || '',
			},
			formData: {
				biz: path
			},
			success: uploadRes => {
				if (!type) {
					fontphoto.value = JSON.parse(uploadRes.data).message
					headImge.value = filePath;
				} else {
					endphoto.value = JSON.parse(uploadRes.data).message
					backImge.value = filePath;
				}
				uni.hideLoading()
				if (JSON.parse(uploadRes.data).code == 401) {
					uni.uploadFile({
						url: `${base_url}/sys/common/upload`, // 替换为您的POST接口地址
						filePath,
						name: 'file', // 后端接收时的字段名
						header: {
							'X-Access-Token': uni.getStorageSync('token') || '',
						},
						formData: {
							biz: path
						},
						success: uploadRes => {
							if (!type) {
								fontphoto.value = JSON.parse(uploadRes.data).message
							} else {
								endphoto.value = JSON.parse(uploadRes.data).message
							}
							uping.value = true;
						},
						fail: err => {
							uni.showToast({
								title: '上传出错',
								icon: 'error'
							})
							uni.hideLoading()
						}
					})
				}
				uping.value = true;
			},
			fail: err => {
				uni.showToast({
					title: '上传出错',
					icon: 'error'
				})
				uni.hideLoading()
			}
		})
	}

	function isAtLeastEightChars(str) {
		return typeof str === 'string' && str.length >= 12;
	}
	const openLook = (res) => {
		if (isAtLeastEightChars(res)) {
			content.value = res;
			show.value = true
		}
	}

	const next = () => {
		// if (!fontphoto.value) {
		// 	uni.showToast({
		// 		title: '请上银行卡正面',
		// 		icon: 'none'
		// 	})
		// 	return
		// } else if (!endphoto.value) {
		// 	uni.showToast({
		// 		title: '请上传银行卡背面',
		// 		icon: 'none'
		// 	})
		// 	return
		// }
		// const allNonEmpty = textArray.every(item => {
		// 	// 如果想忽略前后空格，可用 item.trim() !== ''
		// 	return item !== '';
		// });
		if (!uping.value) {
			return
		}

		// if (allNonEmpty) {
		let data = uni.getStorageSync('backhuancun')
		data.openingBank = textArray[0]
		data.bankCard = textArray[1]
		data.bankZmPath = fontphoto.value
		data.bankFmPath = endphoto.value
		uni.setStorageSync("backhuancun", data)
		uni.navigateTo({
			url: "/pages/addstaff/healthcertificate"
		});
		// } else {
		// 	uni.showToast({
		// 		title: '请上传清晰的身份证',
		// 		icon: 'error'
		// 	})
		// }
	}
	const goBack = () => {
		if (!uping.value) {
			return
		}
		if (textArray[0]) {
			let data = uni.getStorageSync('backhuancun')
			data.openingBank = textArray[0];
			data.bankCard = textArray[1];
			data.bankZmPath = fontphoto.value;
			data.bankFmPath = endphoto.value;

			uni.setStorageSync("backhuancun", data)
		}
		uni.navigateBack()
	}

	onLoad(() => {
		if (uni.getStorageSync('backhuancun').openingBank) {
			let data = uni.getStorageSync('backhuancun');
			textArray[0] = data.openingBank;
			textArray[1] = data.bankCard;
			fontphoto.value = data.bankZmPath
			endphoto.value = data.bankFmPath
		} else if (uni.getStorageSync('baddata')) {
			let data = uni.getStorageSync('baddata');
			textArray[0] = data.openingBank;
			textArray[1] = data.bankCard;
			fontphoto.value = data.bankZmPath
			endphoto.value = data.bankFmPath
		}

	})
	onShow(() => {
		const img = uni.getStorageSync('imgkey0')
		if (img) {
			uploadImage(img)
			uni.removeStorageSync('imgkey0')
		}
	})
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		width: 100%;
		background-color: #F7F7F7;
		position: relative;

		.white-content {
			width: 90%;
			margin-left: 5%;
			border-radius: 35rpx;

			.content-title {
				display: flex;
				align-items: center;
				height: 100rpx;
				position: relative;
				font-weight: 600;

				.content-weight {
					font-size: 32rpx;
				}

				.content-img {
					position: absolute;
					right: 0;
					top: 0;
					width: 400rpx;
					height: 100%;
				}
			}
		}

		.white-photo {
			width: 100%;
			height: 300rpx;
			border-radius: 35rpx;
			background-color: #fff;
			justify-content: space-around;
			align-items: center;
			display: flex;

			.photo {
				width: 300rpx;
				height: 200rpx;
			}
		}

		.white-message {
			width: 100%;
			margin-top: 20rpx;
			padding-top: 20rpx;
			padding-bottom: 20rpx;
			margin-bottom: 30rpx;
			border-radius: 35rpx;
			background-color: #fff;
			justify-content: space-around;
			display: flex;
			flex-direction: column;

			.message-title {
				width: 100%;
				height: 100rpx;
				align-items: center;
				display: flex;

				.message-weight {
					font-size: 30rpx;
				}
			}

			.one {
				width: 90%;
				margin-left: 5%;
				height: 100rpx;
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;

				.one-left {
					margin-left: 10rpx;
					font-size: 30rpx;
					width: 250rpx;
				}

				.one-right {
					margin-right: 10rpx;
					font-size: 30rpx;
					color: #999999;
					overflow: hidden;
					/* 隐藏超出内容 */
					white-space: nowrap;
					/* 不换行 */
					text-overflow: ellipsis;
					max-width: 330rpx;
				}
			}
		}
	}

	.photo-left {
		.photo-weight {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}

		.photo-font {
			font-size: 28rpx;
			margin-top: 10rpx;
			color: #666;
		}

	}

	.gray-font {
		padding: 20rpx 60rpx;
		padding-bottom: 35rpx;
		color: #999999;
	}

	// .finish-button {
	// 	display: flex;
	// 	justify-content: center;
	// 	align-items: center;
	// 	width: 80%;
	// 	height: 90rpx;
	// 	margin: 0rpx auto;
	// 	margin-bottom: 80rpx;
	// 	margin-top: 20rpx;
	// 	color: #fff;

	// 	border-radius: 35rpx;
	// 	font-size: 33rpx;
	// }

	.title-back {
		background-color: #F7F7F7;
		width: 100%;
		height: 70rpx;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #cbd1d2;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9999;
	}

	.left-father {
		display: flex;
		align-items: center;

		.back-img {
			width: 45rpx;
			height: 40rpx;
			margin-left: 40rpx;
			margin-right: 15rpx;
		}
	}

	.shu {
		width: 14rpx;
		height: 36rpx;
		background-color: #0097FF;
		border-radius: 10rpx;
		margin: 3rpx 20rpx 0 30rpx;
	}

	.line {
		margin: 10rpx 0;
	}

	.finish-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 44%;
		height: 90rpx;
		// margin: 0rpx auto;
		margin-bottom: 80rpx;
		background: linear-gradient(to bottom, #e7f4ff, #c5e5ff);
		border: 2rpx solid #9AD1FF;
		color: #007CFF;
		border-radius: 37rpx;
		font-size: 33rpx;
	}

	.back-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 44%;
		height: 90rpx;
		margin-bottom: 80rpx;
		border: 2rpx solid #c3cacd;
		background: linear-gradient(to bottom, #f3f3f5, #dee4e9);
		border-radius: 37rpx;
		font-size: 33rpx;
	}
</style>