<template>
	<view>
		<uni-card>
			<uni-section title="基本信息" type="line">
				<uni-forms ref="baseForm" :modelValue="baseFormData" :rules="rules"
					style="margin-top: 3vh;margin-left: 3vw;">
					<uni-forms-item label="证件照" required name="lrXm">
						<lzcOCR class="lzcOCR" :src="zjcaijianSrc" @end="idcardEnd"></lzcOCR>
					</uni-forms-item>
					<uni-forms-item label="姓名" required name="lrXm">
						<uni-easyinput ref="xm" type="text" v-model="baseFormData.lrXm" placeholder="请输入姓名"
							:inputBorder="false"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="手机号" required name="lrCydh">
						<uni-easyinput type="text" v-model="baseFormData.lrCydh" placeholder="请输入手机号"
							:inputBorder="false"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="住址" required name="lrHjbcxx">
						<uni-easyinput type="text" v-model="baseFormData.lrHjbcxx" placeholder="请输入住址"
							:inputBorder="false"></uni-easyinput>
					</uni-forms-item>
					<!-- <uni-forms-item label="分数">
						<uni-easyinput type="text" v-model="score"
							:inputBorder="false"></uni-easyinput>
					</uni-forms-item> -->
					<uni-forms-item label="人像" required>
						<image :src="src" @click="takePhoto" mode="widthFix" style="width: 150px;"></image>
					</uni-forms-item>
					<view v-if="show">
						<uni-forms-item label="直接保存">
							<uni-data-checkbox v-model="radio" :localdata="radioData"></uni-data-checkbox>
						</uni-forms-item>
						<text>注意：由于人脸比对不成功可以直接保存人工审核！</text>
					</view>

					<view>
						<button cursor-spacing="22px" class="buttonClass" @click="save()">保存</button>
					</view>
				</uni-forms>
			</uni-section>
		</uni-card>

	</view>
</template>

<script>
	import lzcOCR from '@/components/lzc-OCR/lzc-OCR.vue';
	import {
		decryptRowData_ECB,
		decryptData_ECB
	} from '@/common/sm4.js'
	import {
		showConfirm,
		getDictInfo,
		toast,
		toBase64
	} from '@/common/common.js'
	import {
		UploadOne
	} from '@/api/upload.js'
	import {
		updateKhjbxx,
		infoKhjbxx,
		GetLrByZjhm,
		SaveKhjbxx
	} from '@/api/kh.js'
	import {
		getUser
	} from '@/common/auth.js'
	import {
		setToken,
		setOpenid,
		getOpenid,
		setUser
	} from '@/common/auth.js'
	import CryptoJS from 'crypto-js';
	import config from '@/config.js';
	import idCardNoUtil from '@/common/idcard.js'
	import {
		translate,
		base64ToUrl
	} from '@/common/image.js'
	import {
		Register
	} from '@/api/login.js'
	export default {
		components: {
			lzcOCR
		},
		data() {
			return {
				show: false,
				radio: 0,
				radioData: [{
					text: '否',
					value: 0
				}, {
					text: '是',
					value: 1
				}],
				// 字典
				dicts: {
					// 民族
					C0009: [],
					// 性别
					C0007: [],
				},
				// 百度云access_token
				token: '',
				client_id: config.face_client_id,
				client_secret: config.face_client_secret,
				// 人像地址
				src: "/static/images/head.png",
				// 身份拍摄地址
				zjSrc: "",
				// 身份证裁剪地址
				zjcaijianSrc: "/static/images/sfsb.png",
				showSrc: "",
				// 人员信息
				userInfo: {},
				// 组
				groupId: '',
				// 身份证号加密
				idcardMD5: '',
				// 人像base64
				face: '',
				// 身份证base64
				idcardFace: '',
				idcardFaceUrl: '',
				// 对比份数
				score: 0,
				// ocrXm
				ocrXm: '',
				isSearch: false,
				updateFlag: false,
				baseFormData: {
					lrXm: '',
					lrZjhm: '',
					lrHjbcxx: '',
					lrCydh: '',
				},
				rules: {
					lrHjbcxx: {
						rules: [{
							required: true,
							errorMessage: '住址不能为空'
						}]
					},
					lrXm: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					photo: {
						rules: [{
							required: true,
							errorMessage: '请采集人像'
						}]
					},
					lrCydh: {
						rules: [{
								required: true,
								errorMessage: '手机号不能为空'
							},
							{
								format: 'number',
								errorMessage: '请输入正确的手机号',
							},
							{
								pattern: '^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\\d{8})$',
								errorMessage: '请输入正确的手机号',
							}
						]
					}
				},
			}
		},
		created() {},
		onLoad(o) {
			this.getDictList(Object.keys(this.dicts), this.dicts)
			this.userInfo = getUser()
			this.baseFormData.lrHjdz = this.userInfo.dept.locationCode
			this.groupId = this.userInfo.dept.locationCode.substring(0, 6)
			if (this.userInfo.userType == '07') {
				this.updateFlag = true
				let info = JSON.parse(o.info)
				this.baseFormData.lrHjdz = info.lrHjdz
				this.groupId = info.lrHjdz.substring(0, 6)
				this.baseFormData = info
				this.src = config.baseUrl + info.lrTx
			}
		},
		methods: {
			getAccessToken() {
				uni.request({
					url: '/baiduApi/oauth/2.0/token',
					data: {
						grant_type: 'client_credentials',
						client_id: this.client_id,
						client_secret: this.client_secret
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						if (res.statusCode == 200) {
							this.token = res.data.access_token
							this.match()
						}
					},
					error: (err) => {
						uni.hideLoading()
					}
				})
			},
			// 人脸对比
			match() {
				let face = this.face
				let idcardFace = this.idcardFace
				let data = [{
					image: face,
					image_type: 'BASE64',
					liveness_control: 'NORMAL',
				}, {
					image: idcardFace,
					image_type: 'BASE64'
				}]
				uni.request({
					url: '/baiduApi/rest/2.0/face/v3/match?access_token=' + this.token,
					data: data,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						if (res.data.error_msg == 'SUCCESS') {
							this.score = res.data.result.score;

							this.baseFormData.lrTxdb = JSON.stringify({
								"lrJmzjhm": this.idcardMD5,
								"xsfs": this.score
							})
							if (this.score >= config.score) {
								this.show = false
								this.baseFormData.lzzt = 3
								this.baseFormData.lrSpyj = '同意'
								this.baseFormData.prelrZjz = this.idcardFaceUrl
								this.faceSearch()
							} else {
								// 低于80选项是否人工审核，是的话进记录表
								// 身份证头像保存后端
								// 人脸库注册人脸、身份证md5
								// 修改的时候去人脸库搜索，搜索不到不允许修改
								// 修改成功替换原始人脸库照片
								// 首次修改搜索身份证
								// 后端没入库，人脸库相应删除
								// ocr失败身份证原版入库，ocr成功人脸入库
								// showConfirm('人像与身份证不符，请重新上传')
								this.baseFormData.lzzt = 1
								this.baseFormData.lrSpyj = ''
								this.show = true
								this.baseFormData.prelrZjz = this.zjcaijianSrc
								this.faceSearch()
							}

						} else {
							showConfirm(res.data.error_msg)
							uni.hideLoading()
						}

					},
					error: (err) => {
						uni.hideLoading()
					}
				})
			},
			createGroup() {
				uni.request({
					url: '/baiduApi/rest/2.0/face/v3/faceset/group/add?access_token=' + this.token,
					data: {
						group_id: this.groupId,
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						if (res.statusCode == 200) {
							this.faceAdd()
						}
					},
					error: (err) => {
						uni.hideLoading()
					}
				})
			},
			// 人脸注册
			faceAdd() {
				// https://cloud.baidu.com/doc/FACE/s/Gk37c1uzc#%E4%BA%BA%E8%84%B8%E6%B3%A8%E5%86%8C
				let face = this.face
				let data = {
					image: face,
					image_type: 'BASE64',
					group_id: this.groupId,
					user_id: this.idcardMD5,
					action_type: 'REPLACE', // 操作方式 APPEND: 当user_id在库中已经存在时，对此user_id重复注册时，新注册的图片默认会追加到该user_id下 REPLACE : 当对此user_id重复注册时,则会用新图替换库中该user_id下所有图片 默认使用APPEND
				}
				uni.request({
					url: '/baiduApi/rest/2.0/face/v3/faceset/user/add?access_token=' + this.token,
					data: data,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						uni.hideLoading()
						if (res.data.error_msg != 'SUCCESS') {
							showConfirm(res.data.error_msg)
						}
					},
					error: (err) => {
						uni.hideLoading()
					}
				})
			},
			// 人脸搜索
			faceSearch() {
				let face = this.face
				let data = {
					image: face,
					image_type: 'BASE64',
					group_id_list: this.groupId,
					match_threshold: config.score,
					max_user_num: 50
				}
				uni.request({
					url: '/baiduApi/rest/2.0/face/v3/search?access_token=' + this.token,
					data: data,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						if (res.data.error_msg == 'SUCCESS') {
							// this.isSearch = true
							if (res.data.result.user_list.length < 1) {
								this.createGroup()
							} else {
								if (res.data.result.user_list[0].score >= config.score) {
									let xs = []
									res.data.result.user_list.forEach(e => {
										if (e.user_id != this.idcardMD5) {
											xs.push({
												"lrJmzjhm": e.user_id,
												"xsfs": e.score
											})
											this.baseFormData.lzzt = 2
											this.baseFormData.lrSpyj = ''
										}

									})
									this.baseFormData.xslrZjhm = JSON.stringify(xs)
								}
								// this.faceAdd()
								uni.hideLoading()
							}
						} else {
							// this.isSearch = false
							// uni.hideLoading()
							this.faceAdd()
						}

					},
					error: (err) => {
						uni.hideLoading()
					}
				})
			},
			save() {
				if (this.src == '/static/images/head.png') {
					showConfirm('请采集人像')
					return
				} else {
					if (!this.ocrXm) {
						showConfirm('修改信息请重新识别身份证人像面')
						return
					}
					if (this.ocrXm != this.baseFormData.lrXm) {
						showConfirm('姓名与真实姓名不符，请重新识别身份证人像面')
						return
					}
					// if (!this.isSearch) {
					// 	showConfirm('当前区县暂未开放，请联系相关人员')
					// 	return
					// }
					if ((this.score >= config.score) || (this.score < config.score && this.radio == '1')) {
						uni.showLoading({
							title: '正在保存中...'
						})
						this.$refs['baseForm'].validate().then(res => {
							UploadOne(this.baseFormData.prelrZjz, {}).then(re => {
								this.baseFormData.lrZjz = re.data.url
								UploadOne(this.src, {}).then(re => {
									this.baseFormData.lrTx = re.data.url
									if (this.userInfo.userType == '07') this.baseFormData.id = this
										.userInfo.userId

									if (this.updateFlag) {
										updateKhjbxx(this.baseFormData).then(r => {
											uni.hideLoading()
											if (r.code == 200) {
												toast('保存成功')
												setTimeout(function() {
													uni.switchTab({
														url: '/pages/index/index'
													})
												}, 1000)
											}
										})
									} else {
										SaveKhjbxx(this.baseFormData).then(r => {
											uni.hideLoading()
											if (r.code == 200) {
												toast('保存成功')
												// setOpenid(r.data.openId)
												// setUser(r.data.sysUser)
												// setToken(r.data.token.access_token)
												setTimeout(function() {
													uni.switchTab({
														url: '/pages/index/index'
													})
												}, 1000)
											}
										})
									}

								})
							})
						}).catch(err => {
							uni.hideLoading()
						})
					} else {
						showConfirm('请重新采集人像')
						return
					}
				}

			},
			takePhoto() {
				if (!this.zjSrc) {
					showConfirm('请先识别身份证人像面')
					return
				}
				uni.chooseImage({
					count: 1,
					mediaType: ['image'],
					sizeType: ['compressed'],
					sourceType: ['camera'],
					success: (res) => {
						uni.showLoading({
							title: '正在识别中...'
						})

						let size = res.tempFiles[0].size
						let scale = 1
						if (size / 1024 / 1024 > 0.9) scale = 0.6

						translate(res.tempFilePaths[0], scale, 'blob', this.setSrc)
					}
				})
			},
			setSrc(e, blobUrl) {
				this.src = blobUrl
				uni.getFileInfo({
					filePath: blobUrl,
					success: (res) => {
						let size = res.size
						let scale = 1
						if (size / 1024 / 1024 > 0.9) {
							scale = 0.6
							translate(this.src, scale, 'blob', this.setSrc)
						} else {
							e = e.replace('data:image/jpeg;base64,', "");
							this.face = e
							this.getAccessToken()
						}
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			// 身份证识别
			idcardEnd(words, src) {
				if (words.image_status == "other_type_card") {
					showConfirm('请识别正确的身份证人像面')
					return
				}
				// 身份证号校验  性别  出生日期
				// 修改之后的姓名和ocr返回校验，重新ocr
				let id = words.words_result['公民身份号码'].words
				let csrq = words.words_result['出生'].words
				let sex = words.words_result['性别'].words
				let info = idCardNoUtil.getIdCardInfo(id)
				if (!idCardNoUtil.checkIdCardNo(id)) {
					showConfirm('身份证号识别有误，请重新识别')
					return
				}
				if (this.userType == '07' && this.baseFormData.lrZjhm != id) {
					showConfirm('请使用本人身份证重新识别')
					return
				}
				if (info.birthday != csrq) {
					showConfirm('身份证出生日期识别有误，请重新识别')
					return
				}
				if (info.gender != sex) {
					showConfirm('身份证性别识别有误，请重新识别')
					return
				}
				if (words.image_status == "reversed_side") {
					showConfirm('请识别身份证人像面')
					return
				}
				if (words.risk_type != "normal") {
					// normal-正常身份证；copy-复印件；temporary-临时身份证；screen-翻拍；unknown-其他未知情况
					showConfirm('请识别正确的身份证人像面')
					return
				}

				this.baseFormData.lrXb = getDictInfo(this.dicts.C0007, words.words_result['性别'].words)[0].value
				this.baseFormData.lrMz = getDictInfo(this.dicts.C0009, words.words_result['民族'].words)[0].value

				this.idcardFace = words.photo
				this.idcardFaceUrl = base64ToUrl(words.photo);
				this.baseFormData.lrZjhm = id
				this.baseFormData.lrCsrq = csrq
				this.idcardMD5 = CryptoJS.MD5(this.baseFormData.lrZjhm).toString()
				this.baseFormData.lrXm = words.words_result['姓名'].words
				this.ocrXm = words.words_result['姓名'].words
				this.zjSrc = src
				this.zjcaijianSrc = base64ToUrl(words.card_image);

				if (this.userInfo.userType != '07') {
					GetLrByZjhm({
						lrJmzjhm: this.idcardMD5
					}).then(res => {
						if (res.data) this.baseFormData = decryptData_ECB(res.data, ["lrZjhm", "lrXm", "lrHjbcxx",
							"lrXjdzBcxx",
							"lrCydh", "lrPoxm", "lrPoZjmh", "jhrXm", "jhrSjhm", "zlrXm", "zlrDh", "cjzh",
							"yhzh", "khmc"
						], [2, 1, 4, 4, 3, 1, 2, 1, 2, 1, 3, 5, 5, 5]);
						if (res.data && res.data.lrHjdz) this.baseFormData.lrHjdz = res.data
							.lrHjdz
						if (this.baseFormData.lrTx) this.src = config.baseUrl + this.baseFormData.lrTx
						if (res.data) this.updateFlag = true
					})
				}

			},
		}
	}
</script>

<style scoped>
	.lzcOCR {
		/* 	width: 77%;
		display: flex;
		justify-content: center; */
	}

	.buttonClass {
		margin-top: 4vh;
		margin-left: 4vw;
		width: 280px;
		/* height: 5vh; */
		border-radius: 5.8vw;
		/* border: 1px solid rgba(176, 179, 199, 1); */
		background: #28d87d;
		color: white;
		height: 5vh;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow:0rpx 4rpx 10rpx 1rpx rgba(40, 216, 125,0.4);
	}
</style>