<template>
  <view class="page">
    <u-navbar class="u-navbar" title="身份证识别" placeholder @leftClick="leftClick" leftIconColor="#fff"  bgColor="#00337A"  :titleStyle="{ color: '#FFF', fontSize: '32rpx' }"/>
	<scroll-view class="content" scroll-y="true">
	<view class="img-view">
		<view class="view-item" style="display: flex;justify-content: space-between;align-items: center;">
			<view>拍摄识别身份证(正面)</view>
			<view style="margin-left: 40rpx;" class="btn" @click="distinguish">点击识别</view>
		</view>
		<view class="view-item">
			<view>请确认您的个人信息，若有误请点击修改</view>
		</view>
		<u--form class="addForm" :model="aFormData" ref="aForm">
			<view class="form-input-box">
				<view style="width:20%;height: 100%;">
					<text>姓名</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='bankCard' style="width:75%;height: 100%;" >
					<u--input v-model="aFormData.name" type="text" placeholder="请输入" maxlength="25"  border="surround" clearable></u--input>
				</u-form-item>
			</view>
			<view class="form-input-box">
				<view style="width:20%;height: 100%;">
					<text>身份证号</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='idNumber' style="width:75%;height: 100%;" >
					<u--input v-model="aFormData.idNumber" type="text" placeholder="请输入" maxlength="18"  border="surround" @input="getBorth"></u--input>
				</u-form-item>
			</view>
			<view class="form-input-box">
				<view style="width:20%;height: 100%;">
					<text>性别</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='sex' style="width:75%;height: 100%;" >
					<u--input
						v-model="aFormData.sex" readonly type="text" placeholder="自动计算带入" maxlength="15"  border="surround" clearable></u--input>
				</u-form-item>
			</view>
			<view class="form-input-box"> 
				<view style="width:20%;height: 100%;">
					<text>民族</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='ethnic' style="width:75%;height: 100%;" >
					<u--input v-model="aFormData.ethnic" type="text" placeholder="请输入" maxlength="15"  border="surround" clearable></u--input>
				</u-form-item>
			</view>
			<view class="form-input-box">
				<view style="width:20%;height: 100%;">
					<text>住址</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='address' style="width:75%;height: 100%;" >
					<u--input v-model="aFormData.address" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
				</u-form-item>
			</view>
			<view class="view-item" style="display: flex;justify-content: space-between;align-items: center;">
				<view>拍摄识别身份证(背面)</view>
				<view style="margin-left: 40rpx;" class="btn" @click="distinguishCard">点击识别</view>
			</view>
			<view class="form-input-box">
				<view style="width:20%;height: 100%;">
					<text>签发机关</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='issuance' style="width:75%;height: 100%;" >
					<u--input v-model="aFormData.issuance" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
				</u-form-item>
			</view>
			<view class="form-input-box">
				<view style="width:25%;height: 100%;">
					<text>开始有效期</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='signDate' style="width:70%;height: 100%;" >
					<uni-datetime-picker type="date" :clear-icon="false" format="YYYY-MM-DD" v-model="aFormData.signDate"/>
				</u-form-item>
			</view>
			<view class="form-input-box">
				<view style="width:25%;height: 100%;">
					<text>结束有效期</text><text style="color: red;">*</text>
				</view>
				<u-form-item prop='expiryDate' style="width:70%;height: 100%;" >
					<uni-datetime-picker type="date" :clear-icon="false" format="YYYY-MM-DD" v-model="aFormData.expiryDate"/>
				</u-form-item>
			</view>
			
			
		</u--form>
	</view>  
	<view class="sumbit-btn" @click="sumbit">确 定</view>
	
	</scroll-view>
	
  </view>
</template>

<script>
import { pathToBase64, base64ToPath } from 'image-tools';
import config from '@/config'
export default {
  data() {
    return { 
		idNumber:uni.getStorageSync('realNameUser').idNumber,  
		aFormData:{
			"name": "",
			"idNumber": "",
			"sex": "",
			"birthday": "",
			"ethnic": "",//民族
			"address": "",//住址
			"signDate": "",//生效日期
			"expiryDate": "",//失效日期
			"issuance": "",//签发机关
		},
		cardData:{},   
    }
  },
  onLoad() {
    console.log('?? ~ mounted ~ mounted-index:');
  },
  onShow() {
	  
  },
  methods: {
	//正面面识别采集
	distinguish(){
		console.log('正面识别')
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['camera'],
			success: res => {
				console.log('?? ~ res-拍照:', res)
				this.imgToBase64(res.tempFilePaths[0]).then(base64 => {
					let param={
						type:'1',
						recognitionFrontData:base64.split(',')[1]
					}
					console.log(param)
					uni.request({
					  url: config.realIdCardUrl+'/recognition',
					  method: 'post',
					  data: param,
					  header: {
						'Content-Type': 'application/Json',
						Authorization: uni.getStorageSync('realNameToken')
					  },
					  success: res => {
						console.log(res)
						res = JSON.parse(res.data); 
						this.aFormData.name=res.data.name;
						this.aFormData.idNumber=res.data.idNumber;
						this.getBorth(this.aFormData.idNumber)
						this.aFormData.sex=res.data.gender;
						this.aFormData.ethnic=res.data.ethnicity;
						this.aFormData.address=res.data.address;
						 
					  },
					  fail: err => {
						console.log(err)
					  }
					})
	 
				})
			},
			fail: err => { 
			  console.log('?? ~ err:', err)
			}
		})
	},
	//背面识别采集
	distinguishCard(){
		console.log('背面识别')
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['camera'],
			success: res => {
				console.log('?? ~ res-拍照:', res)
				this.imgToBase64(res.tempFilePaths[0]).then(base64 => {
					let param={
						type:'1',
						recognitionBackData:base64.split(',')[1]
					}
					console.log(param)
					uni.request({
					  url: config.realIdCardUrl+'/recognition',
					  method: 'post',
					  data: param,
					  header: {
						'Content-Type': 'application/Json',
						Authorization: uni.getStorageSync('realNameToken')
					  },
					  success: res => {
						console.log(res)
						res = JSON.parse(res.data); 
						this.aFormData.issuance=res.data.issuingAuthority;
						this.aFormData.signDate=res.data.validTime.split("-")[0];
						this.aFormData.expiryDate=res.data.validTime.split("-")[1];
					  },
					  fail: err => {
						console.log(err)
					  }
					})
 
				})
			},
			fail: err => { 
			  console.log('?? ~ err:', err)
			}
		})
	},
 
	imgToBase64(data) {
	  return new Promise((resolve, reject) => {
		pathToBase64(data)
		  .then(base64 => {
			resolve(base64)
		  })
		  .catch(error => {
			console.error(error)
			reject(error)
		  })
	  })
	}, 
	
	sumbit(){
		if(this.aFormData.name==''){
			uni.$u.toast('请填写姓名');
		}else if(this.aFormData.idNumber==''){
			uni.$u.toast('请填写身份证号');
		}else if(!this.verifyidNumber(this.aFormData.idNumber)){
			uni.$u.toast('请填写正确身份证号');
		}else if(this.aFormData.ethnic==''){
			uni.$u.toast('请填写民族');
		}else if(this.aFormData.address==''){
			uni.$u.toast('请填写住址');
		}else if(this.aFormData.signDate==''){
			uni.$u.toast('请选择生效日期');
		}else if(this.aFormData.expiryDate==''){
			uni.$u.toast('请选择失效日期');
		}else if(this.aFormData.issuance==''){
			uni.$u.toast('请填写签发机关');
		}else{
			console.log(1)
			var pages = getCurrentPages();
			var prevPage = pages[pages.length - 2]; //上一个页面
			prevPage.$vm.idCardDataBack(this.aFormData);
			uni.navigateBack({
				delta: 1
			})
		}
	},
	//身份证校验
	verifyidNumber(idNumber) {
		console.log(2)
		console.log(idNumber.length)
	  // 校验长度
	  if (idNumber.length !== 18) {
	    return false;
	  }
	  // 校验前17位是否为数字
	  if (!/^\d{17}$/.test(idNumber.substr(0, 17))) {
	    return false;
	  }
	  
	  // 校验最后一位
	  var weightFactor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
	  var checkCodeList = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
	  var checkSum = 0;
	  for (var i = 0; i < 17; i++) {
	    checkSum += parseInt(idNumber.charAt(i)) * weightFactor[i];
	  }
	  var checkCodeIndex = checkSum % 11;
	  if (idNumber.charAt(17).toUpperCase() !== checkCodeList[checkCodeIndex]) {
	    return false;
	  }
	  
	  return true;
	},
	getBorth(e){
		if(e.length==18){
			if (parseInt(this.aFormData.idNumber.substr(16, 1)) % 2 == 1) {
				this.aFormData.sex = "男";
			} else {
				this.aFormData.sex = "女";
			}
			this.aFormData.birthday=this.aFormData.idNumber.substring(6, 14)
		}
	},
    // 返回
    leftClick() {
      console.log('返回')
      uni.navigateBack({
      	delta: 1 // 返回
      });
    },
	timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
		let date
		// 若传入时间为假值，则取当前时间
		if (!dateTime) {
			date = new Date()
		}
		// 若为unix秒时间戳，则转为毫秒时间戳（逻辑有点奇怪，但不敢改，以保证历史兼容）
		else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
			date = new Date(dateTime * 1000)
		}
		// 若用户传入字符串格式时间戳，new Date无法解析，需做兼容
		else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
			date = new Date(Number(dateTime))
		}
		// 处理平台性差异，在Safari/Webkit中，new Date仅支持/作为分割符的字符串时间
		// 处理 '2022-07-10 01:02:03'，跳过 '2022-07-10T01:02:03'
		else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
			date = new Date(dateTime.replace(/-/g, '/'))
		}
		// 其他都认为符合 RFC 2822 规范
		else {
			date = new Date(dateTime)
		}
	
		const timeSource = {
			'y': date.getFullYear().toString(), // 年
			'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
			'd': date.getDate().toString().padStart(2, '0'), // 日
			'h': date.getHours().toString().padStart(2, '0'), // 时
			'M': date.getMinutes().toString().padStart(2, '0'), // 分
			's': date.getSeconds().toString().padStart(2, '0') // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		}
	
		for (const key in timeSource) {
			const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
			if (ret) {
				// 年可能只需展示两位
				const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
				formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
			}
		}
		return formatStr
	},
	uuid() {
		var s = [];
		var hexDigits = "0123456789abcdef";
		for (var i = 0; i < 32; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}
		s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
		s[8] = s[13] = s[18] = s[23];
		var uuid = s.join("");
		return uuid;
	},
  },

}
</script>

<style lang="scss">
.page {
	width: 100vw;
	height: 100vh;
	background-color: #EFEFEF;
	box-sizing: border-box;
	font: 24rpx;
	.content{
		width: 100%;
		height: 92vh;
		margin-top: 20rpx;
		background-color: #EFEFEF;
		padding-bottom: 40rpx;
	}
	.img-view{
		width: 94%;
		margin: 20rpx auto;
		background-color: #FFF;
		border-radius: 10rpx;
	}
	.btn{
		background-color:#00337A;
		color: #FFF;
		padding:10rpx 20rpx;
		border-radius: 10rpx;
	}
	.view-item{
		width: 94%;
		margin: 0rpx auto;
		padding:20rpx;
		display: flex;
		border-bottom: 1rpx solid #EFEFEF;
		font-size: 26rpx;
	}
	.img-box{
		width: 94%;
		height: auto;
		margin: 0rpx auto;
		padding:20rpx;
		display: flex;
		border-bottom: 1rpx solid #EFEFEF;
		.img-item {
			float: left;
			width: 200upx;
			height: 200upx;
			border: 1px solid #ddd;
			margin: 0 22rpx 20upx 0upx;
			position: relative;
			box-sizing: border-box;
			background: #eee;
			.img {
				display: block;
				width: 100%;
				height: 100%;
			}
			.remove-btn {
				position: absolute;
				top: -18upx;
				right: -18upx;
				width: 44upx;
				height: 44upx;
				z-index: 2;
			}
		}
		.upload-btn {
					display: flex;
					justify-content: center;
					align-items: center;
				.img {
					width: 60upx;
					height: 60upx;
					margin: unset;
				}
			}
	}

	.btn2{
		color: #999;
		margin-top: 20rpx;
		margin-left: 20rpx;
		padding: 20rpx;
	}
	.popup-header{
		width: 100%;
		height: 80rpx;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #fff;
	}
	.popup-content{
		width: 100%;
		height: 15vh;
		background-color: #fff;
	}
	.addForm{
		width: 100%;
		height: auto;
		font-size: 26rpx;
		.form-input-box{
			padding: 0 20rpx;
			display: flex;
			align-items: center;
			border-bottom: 1rpx solid #eee;
		}
	}
	.sumbit-btn{
		width: 94%;
		height: 80rpx;
		margin: 0 auto;
		margin-bottom: 100rpx;
		display: flex;align-items: center;justify-content: center;
		background: #00337A;
		color: #FFF;
		border-radius: 10rpx;
	}
	
}
</style>
