<template>
	<view class="box" @click="chooseImage">
		<image class="sfsb" mode="widthFix" :src="bSrc"></image>
	</view>
</template>

<script>
	let convert = require('./common/base64.js')
	import {
		translate
	} from '@/common/image.js'
	import config from '@/config.js'
	export default {
		data() {
			return {
				preSrc: '',
				bSrc: this.src,
				size: 0
			};
		},
		props: {
			src: {
				type: String,
				default: '/static/images/sfsb.png'
			},
			disabled: {
				type: Array,
				default: () => []
			}
		},
		mounted() {},
		methods: {
			// 选择本地图片
			chooseImage() {
				if (this.disabled.length > 0) return;
				uni.chooseImage({
					count: 1,
					mediaType: ['image'],
					sizeType: ['compressed'],
					sourceType: ['camera'],
					success: (res) => {
						uni.showLoading({
							title: '正在识别中...'
						})
						this.$emit('start', {
							animal: true,
							img: res.tempFilePaths[0]
						})

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

						translate(res.tempFilePaths[0], scale, 'blob', this.setSrc)
					}
				})
			},
			setSrc(e, blobUrl) {
				this.preSrc = blobUrl
				uni.getFileInfo({
					filePath: blobUrl,
					success: (res) => {
						this.size = res.size / 1024 / 1024
						let size = res.size
						let scale = 1
						if (size / 1024 / 1024 > 0.8) {
							scale = 0.6
							translate(this.preSrc, scale, 'blob', this.setSrc)
						} else {
							e = e.replace('data:image/jpeg;base64,', "");
							this.getAccessToken(e)
						}
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			setFace(e) {

			},
			// 获取AccessToken
			getAccessToken(path) {
				uni.request({
					url: '/baiduApi/oauth/2.0/token',
					data: {
						grant_type: 'client_credentials',
						client_id: config.ocr_client_id,
						client_secret: config.ocr_client_secret
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						this.bSrc = this.preSrc
						this.uploadImage(path, res.data.access_token)
					}
				})
			},
			// 身份证识别
			uploadImage(path, token) {
				uni.request({
					url: '/baiduApi/rest/2.0/ocr/v1/idcard',
					data: {
						image: path,
						access_token: token,
						id_card_side: 'front',
						detect_photo: true,
						detect_risk: true,
						detect_card: true,
					},
					timeout: 30000,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.hideLoading()
						this.$emit('end', res.data, this.bSrc)
					}
				})
			},
		}
	}
</script>

<style>
	.box {
		width: 100%;
		/* height: 100%; */
	}

	.sfsb {
		width: 100%;
		/* width: 180px; */

	}
</style>