<template>
	<div class="container">
		<!-- <u-modal v-model="show" :content="content"></u-modal> -->
		<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="white-content">
			<view class="content-title">
				<view class="shu"></view>
				<view class="content-weight">营业执照</view>
			</view>
			<view class="white-photo" @click="selectphoto">
				<view class="photo-left">
					<view class="photo-weight">营业执照</view>
					<view class="photo-font">请上传营业执照</view>
				</view>
				<view style="position: relative;">
					<image class="photo"
						:src="headImge ? headImge : `https://www.focusnu.com/media/directive/index/zhizhao.png`" />
					<image v-if="!headImge"
						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">
				<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 class="one-right">{{textArray[index] ? textArray[index] : "自动获取" }}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="gray-font">
			<view style="color: #333333;margin-bottom: 30rpx;">注意事项:</view>
			<view class="gray-text">
				1. 运用企业、个体工商户、政府、事业单位、学校、组织等，账号归属企业。
			</view>
			<view class="gray-text">
				2.一个企业信息主体默认可认证1个账号。
			</view>
			<view class="gray-text">
				3.所有上传信息均会被妥善保管，不会用于其他商业用途或传输给其他第三方。
			</view>
		</view>
		<view style="display: flex;width: 100%;padding: 0 20rpx;">
			<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 {
		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 nameArray = ["企业名称", "注册地址", "信用代码", "法人"];
	const textArray = reactive(["", "", "", ""]);
	const bottomlist = [{
		text: '拍摄图片',
		fontSize: 40
	}, {
		text: '图片预览',
		fontSize: 40
	}]
	const bottomshow = ref(false)
	// 本地保存的临时文件路径
	const tempImagePath = ref('')
	const selectphoto = (number) => {

		if (!uping.value) {
			return
		}

		if (headImge.value) {
			bottomshow.value = true;
		} else {
			getMessage()
		}
	}
	const photoclick = (element) => {
		if (element) {
			uni.previewImage({
				urls: [headImge.value], // 必填，所有要预览的图片地址数组
				current: headImge.value, // 可选，当前显示图片的地址，默认是 urls[0]
				indicator: 'default', // 可选，指示器样式，H5/App 有效，值为 'default'（圆点）或 'number'（数字）
				longPressActions: { // 可选，仅 App 支持，长按图片时弹出的操作项
					itemList: ['保存图片到相册'],
				},
			});
		} else {
			getMessage()
		}

	}
	// 拍照并上传
	function getMessage() {

		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&size=1`
				});
				// uploadImage(tempImagePath.value)
			},
			fail: err => {
				console.error('拍照失败：', err)
			}
		})
	}

	const headImge = ref("");
	const backImge = ref("");
	const uping = ref(true);
	// 上传图片到服务器
	function uploadImage(filePath) {
		uping.value = false;
		uni.showLoading()

		uni.uploadFile({
			url: `${base_url}/api/ocr/businessLicense`, // 替换为您的POST接口地址
			filePath,
			name: 'file', // 后端接收时的字段名
			header: {
				'X-Access-Token': uni.getStorageSync('token') || '',
			},
			formData: {},
			success: uploadRes => {
				if (!JSON.parse(uploadRes.data).success) {
					uni.hideLoading()
					uni.showToast({
						title: '识别失败',
						icon: 'error',
						duration: 2000
					})
					uping.value = true;

					return
				}
				console.log("营业执照", JSON.parse(JSON.parse(uploadRes.data).result.data).data)
				if (JSON.parse(JSON.parse(uploadRes.data).result.data).data.companyName) {
					let father = JSON.parse(JSON.parse(uploadRes.data).result.data).data;
					textArray[0] = father.companyName;
					textArray[1] = father.businessAddress;
					textArray[2] = father.creditCode;
					textArray[3] = father.legalPerson;
					headImge.value = filePath;
					savephoto(filePath);
				} else {
					// 普通文本提示（自动消失，默认 1500ms）
					uni.showToast({
						title: '识别失败',
						icon: 'error',
						duration: 2000
					})
					uping.value = true;
					uni.hideLoading()
				}
				// if (JSON.parse(JSON.parse(uploadRes.data).result.data).data.face) {

				uni.hideLoading()
				// 	textArray[4] = father.birthDate;
				// 	textArray[5] = father.address;
				// 	uni.showToast({
				// 		title: '识别成功',
				// 	})
				// 	
				// 	uni.hideLoading()
				// } else {
				// 	let father = JSON.parse(JSON.parse(uploadRes.data).result.data).data.back.data;
				// 	textArray[6] = father.issueAuthority;
				// 	textArray[7] = father.validPeriod;
				// 	uni.showToast({
				// 		title: '识别成功',
				// 	})
				// 	backImge.value = filePath;
				// 	uni.hideLoading()
				// }
			},
			fail: err => {
				uni.showToast({
					title: '上传出错',
					icon: 'error'
				})
				uni.hideLoading()
			}
		})
	}
	const fontphoto = ref("");
	const savephoto = (filePath) => {
		uni.uploadFile({
			url: `${base_url}/sys/common/upload`, // 替换为您的POST接口地址
			filePath,
			name: 'file', // 后端接收时的字段名
			header: {
				'X-Access-Token': uni.getStorageSync('token') || '',
			},
			formData: {
				biz: `temp`
			},
			success: uploadRes => {
				fontphoto.value = JSON.parse(uploadRes.data).message;
				uping.value = true;
			},
			fail: err => {
				uni.showToast({
					title: '上传出错',
					icon: 'error'
				})
				uni.hideLoading()
			}
		})
	}

	function isAtLeastEightChars(str) {
		return typeof str === 'string' && str.length >= 8;
	}
	const openLook = (res) => {
		if (isAtLeastEightChars(res)) {
			content.value = res;
			show.value = true
		}
	}
	const next = () => {
		if (!uping.value) {
			return
		}
		const allNonEmpty = textArray[0] && textArray[1]&& textArray[2]&&textArray[3]&&fontphoto.value;
		if (allNonEmpty) {
			let data = uni.getStorageSync('backhuancun')
			data.comName = textArray[0]
			data.comRegisterAddress = textArray[1]
			data.comCreditCode = textArray[2]
			data.comLegalPerson = textArray[3]
			data.comBusinessLicense = fontphoto.value
			uni.setStorageSync("backhuancun", data)
			uni.navigateTo({
				url: "/pages/addjigou/where"
			});
			// let pushMessage = {
			// 	id: uni.getStorageSync('specicalid') || "",
			// 	tel: uni.getStorageSync('tel'),
			// 	comName: textArray[0],
			// 	comRegisterAddress: textArray[1],
			// 	comCreditCode: textArray[2],
			// 	comLegalPerson: textArray[3],
			// 	comBusinessLicense: fontphoto.value,
			// }
			// // console.log("????",pushMessage)
			// changemessage(pushMessage).then(res => {
			// 	if (res.success) {
			// 		if (res.message == `保存成功！`) {
			// 			uni.navigateTo({
			// 				url: "/pages/addjigou/where"
			// 			});
			// 		} else {
			// 			uni.navigateTo({
			// 				url: "/pages/addjigou/where"
			// 			});
			// 		}

			// 	} else {
			// 		uni.showToast({
			// 			title: res.message,
			// 			icon: 'error'
			// 		})
			// 	}
			// })
		} else {
			uni.showToast({
				title: '请上传清晰的营业执照',
				icon: 'error'
			})
		}
	}
	onLoad(() => {
		if (uni.getStorageSync('backhuancun').comName) {
			let data = uni.getStorageSync('backhuancun');
			if (data.comName) {
				textArray[0] = data.comName;
				textArray[1] = data.comRegisterAddress;
				textArray[2] = data.comCreditCode;
				textArray[3] = data.comLegalPerson;
				if (data.comBusinessLicense) {
					headImge.value = `${base_url}/sys/common/static/${data.comBusinessLicense}`;
					fontphoto.value = data.comBusinessLicense
				}
			}
		} else if (uni.getStorageSync('baddata')) {
			let data = uni.getStorageSync('baddata');
			if (data.comName) {
				textArray[0] = data.comName;
				textArray[1] = data.comRegisterAddress;
				textArray[2] = data.comCreditCode;
				textArray[3] = data.comLegalPerson;
				let data0 = uni.getStorageSync('backhuancun')
				data0.comName = data.id


				uni.setStorageSync("backhuancun", data)
				if (data.comBusinessLicense) {
					headImge.value = `${base_url}/sys/common/static/${data.comBusinessLicense}`;
					fontphoto.value = data.comBusinessLicense
				}
			}
		}
	})
	const goBack = () => {
		if (!uping.value) {
			return
		}
		if (textArray[0]) {
			let data = uni.getStorageSync('backhuancun')
			data.comName = textArray[0]
			data.comRegisterAddress = textArray[1]
			data.comCreditCode = textArray[2]
			data.comLegalPerson = textArray[3]
			data.comBusinessLicense = fontphoto.value
			uni.setStorageSync("backhuancun", data)
		}

		uni.navigateBack()
	}
	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;
		// box-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);

		.white-content {
			width: 90%;
			margin-left: 5%;
			// margin-top: 10rpx;
			// height: 1200rpx;
			border-radius: 35rpx;
			// background-color: rgb(245, 251, 254);

			.content-title {
				display: flex;
				align-items: center;
				height: 110rpx;
				position: relative;

				.content-weight {
					font-size: 32rpx;
					font-weight: 600;
					margin-left: 20rpx;
					// margin-top: 20rpx;
				}

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

		.white-photo {
			width: 100%;
			// margin-left: 5%;
			// margin-top: 30rpx;
			height: 300rpx;
			border-radius: 35rpx;
			background-color: #fff;
			// box-shadow: 4rpx 4rpx 8rpx rgba(0, 0, 0, 0.1);
			justify-content: space-around;
			align-items: center;
			display: flex;

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

		.white-message {
			width: 100%;
			// margin-left: 5%;
			// margin-top: 30rpx;
			margin-bottom: 30rpx;
			padding-top: 30rpx;
			padding-bottom: 30rpx;
			// height: 800rpx;
			border-radius: 35rpx;
			background-color: #fff;
			// box-shadow: 4rpx 4rpx 8rpx rgba(0, 0, 0, 0.1);
			justify-content: space-around;
			// align-items: center;
			display: flex;
			flex-direction: column;

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

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

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

			.one {
				width: 90%;
				margin-left: 5%;
				// border-bottom: 1rpx solid #F7F7F7;
				height: 100rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 10rpx;

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

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

	.photo-left {
		.photo-weight {
			font-size: 30rpx;
			font-weight: 600;
		}

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

	}

	.gray-font {
		padding: 30rpx 60rpx;
		color: #999999;
	}

	.finish-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 44%;
		height: 90rpx;
		margin: 0rpx auto;
		margin-bottom: 80rpx;
		color: #fff;
		background: linear-gradient(to right, #00C9FF, #0076FF);
		border-radius: 37rpx;
		font-size: 35rpx;
	}

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

	.gray-text {
		margin: 10rpx 0;
		font-size: 28rpx;
	}

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

	.title-back {
		margin-top: 100rpx;
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

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

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