<template>
	<navBar title="ETC开户新办申请-单位" navbgClass="nav-bgXin" fontColor='#fff' :scrollTop="scrollTop"></navBar>
	<navBgCar :activeNum='3'></navBgCar>
	<view class="content-wrap">
		<view class="t-card">
			<view class="item-tips">
				<view class="title"> 上传后请核对识别信息 </view>
				<view class="tip"> 如有错误请及时手动修改 </view>
			</view>
			<view class="picture-wrapper" @click="cardImageOcrYY()">
				<view class="bg">
					<view class="">
						<view class="name"> 营业执照 </view>
						<view class="value"> 上传企业的营业执照 </view>
						<view class="tip">
							<view class="tip-value"> 拍摄规范 </view>
						</view>
					</view>
					<image v-if="!state.form.posImgUrl" class="icon" :src="`${$imgUrl}applyCard/zhizhao.png`"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}">
					</image>
					<image v-else class="icon" :src="strReplace(state.form.posImgName)"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}"></image>
				</view>
			</view>
			<view class="picture-wrapper" @click="takePhotoMode('1')">
				<view class="bg">
					<view class="">
						<view class="name"> 人像面 </view>
						<view class="value"> 上传身份证的人像面 </view>
						<view class="tip">
							<view class="tip-value"> 拍摄规范 </view>
						</view>
					</view>
					<image v-if="!state.form.agentPosImgUrl" class="icon" :src="`${$imgUrl}issuance/sfz.png`"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}">
					</image>
					<image v-else class="icon" :src="strReplace(state.form.agentPosImgUrl)"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}"></image>
				</view>
			</view>
			<view class="picture-wrapper" @click="takePhotoMode('2')">
				<view class="bg">
					<view class="">
						<view class="name"> 国徽面 </view>
						<view class="value"> 上传身份证的国徽面 </view>
						<view class="tip">
							<view class="tip-value"> 拍摄规范 </view>
						</view>
					</view>
					<image v-if="!state.form.agentNegImgUrl" class="icon" :src="`${$imgUrl}issuance/sff.png`"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}">
					</image>
					<image v-else class="icon" :src="strReplace(state.form.agentNegImgUrl)"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}"></image>
				</view>
			</view>
			<view class="picture-wrapper" @click="cardFileImageUpdate(99)">
				<view class="bg">
					<view class="">
						<view class="name"> 委托书 </view>
						<view class="value"> 上传文字清晰的委托书 </view>
						<view class="tip">
							<view class="tip-value"> 拍摄规范 </view>
						</view>
						<view class="down" @click="downAuthD">模板下载</view>
					</view>
					<image v-if="!state.form.proxyUrlName" class="icon" :src="`${$imgUrl}issuance/weituo.png`"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}">
					</image>
					<image v-else class="icon" :src="strReplace(state.form.proxyUrlName)"
						:style="{'--bgimg':`url(${$imgUrl}issuance/bg-border.png)`}"></image>
				</view>
			</view>
		</view>
		<view class="shibie-wrapper">
			<view class="title"> 识别内容如下 </view>
			<u-form label-width="220" :model="state.form" ref="uForm" :label-style='labelStyle'>
				<u-form-item label="公司名称" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入公司名称' v-model="state.form.userName"
						maxlength="50" />
				</u-form-item>
				<u-form-item label="部门名称" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入部门名称' v-model="state.form.department"
						maxlength="50" />
				</u-form-item>
				<u-form-item label="社会信用代码" :left-icon='`${$imgUrl}issuance/point-form.png`'
					:left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入社会信用代码' v-model="state.form.userIdNum"
						maxlength="50" />
				</u-form-item>
				<u-form-item label="营业执照地址" :left-icon='`${$imgUrl}issuance/point-form.png`'
					:left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入营业执照地址' v-model="state.form.userAddress"
						maxlength="50" />
				</u-form-item>
				<u-form-item label="经办人姓名" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入经办人姓名' v-model="state.form.agentName"
						maxlength="20" />
				</u-form-item>
				<u-form-item label="经办人身份证号" :left-icon='`${$imgUrl}issuance/point-form.png`'
					:left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入经办人身份证号' v-model="state.form.agentIdNum"
						maxlength="18" />
				</u-form-item>
				<u-form-item label="经办人地址" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入经办人地址' v-model="state.form.agentAddress"
						maxlength="40" />
				</u-form-item>
				<u-form-item label="经办人联系方式" :left-icon='`${$imgUrl}issuance/point-form.png`'
					:left-icon-style='leftIcon'>
					<u-input inputAlign="right" class="clearBg" placeholder='请输入经办人联系方式' v-model="state.form.agentTel"
						maxlength="11" />
				</u-form-item>
			</u-form>
		</view>


		<view class="action">
			<view class="btn-tip">
				如识别信息有误，请手动修改，确认无误后，点击下一步！
			</view>
			<button type="default" class="ui-btn" @click="savaHandle()">
				下一步
			</button>
		</view>
		<view class="choice-takePhoto-wrap" v-if="state.isTakePhotoModeShow" @click="cancle">
			<view class="choice-takePhoto">
				<view @click.stop="takePhoto(state.choiceIndex)" style="border-radius: 20rpx 20rpx 0 0;">拍照</view>
				<view @click.stop="xiangce(state.choiceIndex)">从手机相册选择</view>
				<view @click.stop="cancle">取消</view>
			</view>
		</view>
		<viewfinder v-if="state.phoneType" :phoneType="state.phoneType" :images="state.images"
			:showStartPhoto="state.showImg" @confirmReturn="confirmReturn" @camera="camera"></viewfinder>
	</view>
</template>

<script setup lang="ts">
	import {
		reactive, ref
	} from "vue";
	import navBgCar from "./components/nav-bg-car1";
	import navBar from "@/components/nav-bar/nav-bar2.vue";
	import viewfinder from "../../components/viewfinder.vue"
	import {
		ocrAllQuery, getUserMsg,
		idCardOcr, registerFull, userUpload
	} from "@/utils/network/api.js";
	import { navTo } from "@/utils/utils";
	import {

		requestNew
	} from "@/utils/network/request.js";

	import {
		stringToJson
	} from "@/utils/network/encryption";
	import {
		onLoad,
		onPageScroll,
	} from "@dcloudio/uni-app";
	import {
		setItem,
		getItem,
	} from "@/utils/storage";
	import {
		msg,
		checkStr,
		strReplace,
		uploadFile,
		compressImage,
		chooseImageCompress,
		compareDates
	} from "@/utils/utils";

	const scrollTop = ref(0);//滚动距离
	const labelStyle = {
		color: "#004576",
		fontSize: "28rpx",
	}
	const leftIcon = {
		height: '100%',
		width: '8rpx',
		display: 'flex',
		'align-items': 'center',
		'margin-right': '4rpx',
	}
	const state = reactive({
		phoneType: 0,  // 1 身份证正面  2 身份证反面  3行驶证正面 4行驶证反面
		choiceIndex: 1,  // 1 身份证正面  2 身份证反面
		isTakePhotoModeShow: false,  //选择拍照方式是否出来
		images: '',
		showImg: true,
		form: {
			orderId: "", //订单ID
			//营业执照信息
			userName: "", //开户名称/账户名称
			userIdType: "203", //用户证件类型 203//营业执照
			userIdNum: "", //营业执照号码
			mobile: "", //营业执照号码

			posImgUrl: "", //营业执照证明
			posImgName: "", //营业执照证明
			department: '本部', //不超过50个字符，若单位仅开一个账户，填写“本部”
			userAddress: "", //单位地址
			//经办人信息
			agentName: "",
			agentIdType: "101",
			agentIdNum: "",
			agentAddress: "",
			agentPhone: "",
			agentIdVld: '',
			agentTel: '',
			agentGender: '',
			agentPosImgUrl: "",
			agentPosImgUrlName: "",
			agentNegImgUrl: "",
			agentNegImgUrlName: "",
			negImgUrl: "", //这个参数和国徽面一样的，都要传
			proxyUrl: "",
			proxyUrlName: "",
			sceneType: "", //用户协议支撑服务场景（发行服务机构和用户签订的协议）
			channelId: "", //渠道id
			opId: '',
			orderSource: 'WECHAT',
			isAgent: true,  //经办人办理
			userNegImgUrl: "",
			userPosImgUrl: "",
			tel: ""
		},
		orderId: "",
		vehiclePlateColor: '',
		isSign: '',
		vanType: 1,
		vehicleId: "",
		jsCode: ""
	});

	const savaHandle = () => {
		if (state.form.agentGender === '男') {
			state.form.agentGender = 'MAN'
		} else {
			state.form.agentGender = 'WOMAN'
		}
		if (!state.form.posImgUrl) {
			msg('请上传营业执照');
			return;
		}
		if (!state.form.agentPosImgUrl) {
			msg('请上传身份证的人像面');
			return;
		}
		if (!state.form.agentNegImgUrl) {
			msg('请上传身份证的国徽面');
			return;
		}
		if (!state.form.proxyUrl) {
			msg('请上传身份证的委托书');
			return;
		}
		if (!state.form.userName) {
			msg('请输入公司名称');
			return;
		}
		if (!state.form.department) {
			msg('请输入部门名称');
			return;
		}
		if (!state.form.userIdNum) {
			msg('请输入社会信用代码');
			return;
		}
		if (!state.form.userAddress) {
			msg('请输入营业执照地址');
			return;
		}
		if (!state.form.agentName) {
			msg('请输入经办人姓名');
			return;
		}
		if (!checkStr(state.form.agentIdNum, 'card')) {
			msg('请输入正确的经办人身份证号');
			return;
		}
		if (!checkStr(state.form.agentTel, 'mobile')) {
			msg('请输入正确的经办人联系方式');
			return;
		}
		state.form.tel = state.form.agentTel
		// registerRequest().then((result : any) => {
		// 	console.log("result", result)
		// 	if (!getItem('openId')) {
		// 		setItem('token', result.accessToken)
		// 		setItem('openId', result.openId)
		// 		setItem('mobile', state.form.tel)
		// 		state.form.opId = getItem('openId') ? getItem('openId') : '';
		// 	}
			var data = {
				...state.form,
				orderNo: state.orderId,
				userPosImgUrl: state.form.posImgUrl
			};
			const options = {
				type: 2,
				data: data,
				method: "POST",
				showLoading: true,
			};
			requestNew(userUpload, options).then((res) => {
				const data = res;
				navTo(
					`/subpackage/orders/car-release?orderId=${state.orderId}&vehiclePlateColor=${state.vehiclePlateColor}&vanType=${state.vanType}&vehicleId=${state.vehicleId}`,
				);
			});
		// })
	};


	onLoad((option : any) => {
		state.form.orderId = option.orderId;
		state.orderId = option.orderId;
		state.vehiclePlateColor = option.vehiclePlateColor;
		state.form.opId = getItem('openId') ? getItem('openId') : '';
		state.isSign = option.isSign;
		state.vanType = option.vanType;
		state.vehicleId = option.vehicleId;
		console.log("state.type", option)
		uni.login({
			provider: "weixin",
			success: function (e) {
				console.log("jsCode", e.code)
				state.jsCode = e.code

			},
		});
		queryUserMsg();
	});

	// 通过opneId查询用户信息
	const queryUserMsg = () => {
		const options = {
			type: 2,
			data: {
				// "openId": getItem('openId')
				customerId: "",
			},
			method: "POST",
			showLoading: true,
		};
		requestNew(getUserMsg, options).then((res) => {
			console.log("通过opneId查询用户信息", res)
			const data = res;
			state.form.agentPosImgUrl = data.userPosImgUrl;
			state.form.agentNegImgUrl = data.userNegImgUrl;
			state.form.agentName = data.userName;
			state.form.agentIdNum = data.userIdNum;
			state.form.agentAddress = data.userAddress;
			state.form.agentTel = data.mobile;
			state.form.agentIdVld = data.customerIdVld;
		})
	}

	//监听页面滚动
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop;
	});

	//营业执照Orc接口调用
	const cardImageOcrYY = () => {
		uni.chooseImage({
			count: 1, //只能选取一张照片
			sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ["camera", "album"], //从相册选择
			success: function (res) {
				state.form.posImgName = res.tempFilePaths[0];
				uploadFile(res.tempFilePaths[0], "5").then((data : any) => {
					console.log('state.form输出内容', data)
					state.form.userName = data.unitName;
					state.form.userIdNum = data.screditCode;
					state.form.userAddress = data.adress
					state.form.posImgUrl = data.imageUrl;
					state.form.posImgName = data.imageName;
					// state.form.userPosImgUrl = data.imageUrl;
					// uploadFile(res.tempFilePaths[0], "", "").then((data: any) => {
					// 	state.form.posImgUrl = data; pos
					// 	state.form.userNegImgUrl = data;
					// 	state.form.userPosImgUrl = data;
					// })
				})
			},
		});
	};

	const camera = () => {
		state.phoneType = 0
	}
	const cardFileImageUpdate = (val) => {
		uni.chooseImage({
			count: 1, //只能选取一张照片
			sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ["camera", "album"], //从相册选择
			success: function (res) {
				console.log("上传本地",res);
				state.form.proxyUrlName = res.tempFilePaths[0];
				uploadFile(res.tempFilePaths[0], val).then((data) => {
					// state.form.proxyUrl = data;
					state.form.proxyUrl = data.imageUrl;
					// state.form.proxyUrlName = data.imageUrl;
				})
			},
		});
	};
	const takePhotoMode = (index) => {
		console.log("index", index)
		state.isTakePhotoModeShow = true
		state.choiceIndex = index
	}
	const xiangce = (val) => {
		console.log("val", val)
		var imageType = val;
		chooseImageCompress((res) => {
			state.images = res.tempFilePath ? res.tempFilePath : res.tempFilePaths[0]
			state.showImg = false
			state.phoneType = state.choiceIndex
			state.isTakePhotoModeShow = false
		})
		// uni.chooseImage({
		// 	count: 1, //只能选取一张照片
		// 	sizeType: ["original"], //可以指定是原图还是压缩图，默认二者都有
		// 	sourceType: ["album"], //从相册选择
		// 	success: function (res) {
		// 		let scall=res.tempFiles[0].size/1024/1024/2
		// 		console.log("scall",scall)
		// 		console.log("res.tempFiles[0].size", res.tempFilePaths[0], res.tempFiles[0].size)
		// 		if(scall>1){
		// 			console.log("压缩")
		// 			compressImage(res.tempFilePaths[0], (res) => {
		// 				state.images = res.tempFilePath
		// 				state.showImg = false
		// 				state.phoneType = state.choiceIndex
		// 				state.isTakePhotoModeShow = false
		// 			})
		// 		}else{
		// 			state.images = res.tempFilePaths[0]
		// 			state.showImg = false
		// 			state.phoneType = state.choiceIndex
		// 			state.isTakePhotoModeShow = false
		// 		}
		// 	},
		// })
	}
	const takePhoto = (val) => {
		console.log("拍照", val)
		state.showImg = true
		state.phoneType = val;
	}
	const confirmReturn = (val) => {
		state.phoneType = 0
		state.isTakePhotoModeShow = false
		var imageType = state.choiceIndex;
		console.log("图片地址val", val.tempImagePath)
		uploadFile(val.tempImagePath, imageType).then((data : any) => {
			console.log("身份证上传", data)
			if (state.choiceIndex == 1) {
				state.form.agentName = data.name;
				state.form.agentIdNum = data.idno;
				state.form.agentPosImgUrl = data.imageName;
				// state.form.agentPosImgUrlName = data.imageName;
				state.form.agentAddress = data.address;
				state.form.agentGender = data.gender;
			} else {
				state.form.agentIdVld = data.enddate;
				state.form.agentNegImgUrl = data.imageName;
				state.form.negImgUrl = data.imageUrl;
				// state.form.agentNegImgUrlName = data.imageName;
				compareDates(data.enddate)
			}
			state.isTakePhotoModeShow = false
		})
	}
	const cancle = () => {
		state.isTakePhotoModeShow = false
	}
	const downAuthD = () => {
		uni.downloadFile({
			url: "https://qtzl.etcjz.cn/default-bucket/20240311/单位委托书.docx",
			filePath: uni.env.USER_DATA_PATH + '/' + '单位委托书.docx',
			success(res) {
				const filePath = res.filePath
				uni.openDocument({
					filePath: filePath,
					fileType: 'docx',
					showMenu: true, //关键点
					success: function (res) {
					},
					fail: function (err) {
						msg("打开文档失败");
					}
				});
			},
			fail: function (err) {
				msg("下载文档失败");
				console.log("err", err)
			},
			complete(res) {

			}
		})
	}
	// 无感注册
	const registerRequest = () => {
		let data = {
			userType: "ENTERPRISE",
			idNum: state.form.userIdNum,
			idType: state.form.userIdType,
			mobile: state.form.agentTel,
			userName: state.form.userName,
			gender: 'UNKOWN',
			certifyChannel: "BAIDUOCR",
			address: state.form.userAddress,
			agentIdNum: state.form.agentIdNum,
			agentIdType: state.form.agentIdType,
			agentName: state.form.agentName,
			department: state.form.department,
			userIdImgUrl: state.form.posImgUrl,
			userIdImgBase64: "",
			jsCode: state.jsCode
		}
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await requestNew(registerFull, options);
			const data = res;
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	}
</script>

<style lang="scss" scoped>
	.content-wrap {
		position: absolute;
		top: 370rpx;
		width: 100%;
		min-height: calc(100% - 370rpx);
		box-sizing: border-box;
		padding: 0 30rpx 210rpx;

		.t-card {
			width: 100%;
			background-color: #fff;
			border-radius: 12rpx;
			padding: 40rpx 30rpx 30rpx;
			box-sizing: border-box;
		}

		.action {
			position: absolute;
			bottom: 0rpx;
			left: 0;
			height: 188rpx;
			background-color: #fff;
			border-radius: 30rpx 30rpx 0 0;
			width: 100vw;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;

			.btn-tip {
				font-family: SourceHanSansSC, SourceHanSansSC;
				font-weight: 400;
				font-size: 24rpx;
				color: #CCB375;
				margin-bottom: 14rpx;
			}
		}

		.item-tips {
			.title {
				font-size: 30rpx;
				font-family: Microsoft YaHei;
				font-weight: 500;
				color: #01243A;
				line-height: 30rpx;
			}

			.tip {
				margin-top: 16rpx;
				font-size: 24rpx;
				font-family: Microsoft YaHei;
				font-weight: 400;
				color: #999999;
				line-height: 24rpx;
			}
		}

		.picture-wrapper {
			margin-top: 30rpx;

			.bg {
				background: #F5F9FB;
				border-radius: 10rpx;
				padding: 40rpx 30rpx;
				display: flex;
				// align-items: center;
				justify-content: space-between;

				.name {
					padding-top: 30rpx;
					font-size: 32rpx;
					font-family: SourceHanSansSC, SourceHanSansSC;
					font-weight: 500;
					color: #111;
					line-height: 34rpx;
				}

				.value {
					margin-top: 20rpx;
					font-size: 22rpx;
					font-family: SourceHanSansSC, SourceHanSansSC;
					font-weight: 400;
					color: #999999;
					line-height: 24rpx;
				}

				.tip {
					margin-top: 20rpx;
					text-align: center;
					width: 100rpx;
					height: 30rpx;
					// background: rgba(204, 179, 117);
					border-radius: 6rpx;
					border: 1rpx solid #CCB375;

					.tip-value {
						font-size: 20rpx;
						font-family: Microsoft YaHei;
						font-weight: 400;
						color: #CCB375;
						line-height: 30rpx;
						opacity: 1;
					}
				}
			}

			.icon {
				width: 304rpx;
				height: 190rpx;
				background-image: var(--bgimg);
				background-size: 100% 100%;
				background-repeat: no-repeat;
			}
		}

		.shibie-wrapper {
			margin-top: 30rpx;
			border-radius: 12rpx;
			background-color: #fff;
			width: 100%;
			padding: 30rpx 30rpx 0;
			box-sizing: border-box;

			.title {
				font-size: 30rpx;
				font-family: Microsoft YaHei;
				font-weight: 500;
				color: #01243A;
				line-height: 30rpx;
			}
		}
	}

	::v-deep .u-input__input {
		background: transparent;
	}

	::v-deep .u-form-item--left .u-form-item--left__content {
		padding-right: 0px;
	}

	.choice-takePhoto {
		position: absolute;
		bottom: 0;
		background-color: white;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
	}

	.choice-takePhoto>view:first-child {
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		border-bottom: 1rpx solid rgba(127, 127, 127, 0.3);
		background-color: white;
	}

	.choice-takePhoto>view:last-child {
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		border-top: 6rpx solid rgba(127, 127, 127, 0.1);
		background-color: white;
	}

	.choice-takePhoto>view {
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		background-color: white;
	}

	.choice-takePhoto-wrap {
		width: 100%;
		height: 100vh;
		background-color: rgba(127, 127, 127, 0.2);
		position: fixed;
		left: 0;
		top: 0;
		z-index: 11111;
	}

	.down {
		background: #CCB375;
		color: #fff;
		border-radius: 5rpx;
		font-size: 20rpx;
		margin-top: 10rpx;
		width: 100rpx;
		height: 30rpx;
		text-align: center;
		line-height: 30rpx;
	}
</style>