<template>
    <view>
        <!-- subpages/OCRCard/pages/index/index.wxml -->
        <view class="header">
            <!-- <image class="header-bg" src="/static/subpages/OCRCard/image/headerBg.png" mode="widthFix" /> -->
            <image src="/static/images/back.png" class="back" @tap="back" :style="' top: ' + statusHeight + 'px;width: 50rpx;height: 50rpx;'" mode="" />
            <view class="navigation" :style="'height: ' + navigationHeight + 'px; top: ' + statusHeight + 'px;'">身份证识别</view>
        </view>
        <view class="body">
            <image src="/static/images/card.png" mode="" />
            <view>
                <b>身份识别：</b>
                是在居民出示身份证原件或图片的场合下，通过OCR技术拍摄识别身份证信息。
            </view>
                <button hover-class="color" @click="chooseImage">开始识别</button>
        </view>
    </view>
</template>

<script>
// subpages/OCRCard/pages/index/index.js
const app = getApp();
import { getResidentBaseInfo } from '../../../../utils/api';

let convert = require('./common/base64.js')

export default {
    components: {},
    data() {
        return {
            statusHeight: '',
            navigationHeight: '',
            tableData: '',
            keyWord: '',
            dataObj: {
					client_id: 'MBPxJXn7rCKGt05XwWCU7DSa',
					client_secret: 'mdZAHO09pBr8RwDlGDR7G3vWE9i082h3',
			}
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            statusHeight: app.globalData.deviceInfo.statusHeight,
            navigationHeight: app.globalData.deviceInfo.navigationHeight
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        chooseImage() {
				console.log(1111111)
				let self = this
				uni.chooseImage({
					count: 1,
					success: (ress) => {
						uni.showLoading({
							title: '正在识别中...'
						})
						// this.$emit('start', {
						// 	animal: true,
						// 	img: res.tempFilePaths[0]
						// })
						// 下面将图片本地路径转base64
						convert.toBase64(ress.tempFilePaths[0]).then((res) => {
							self.getAccessToken(res, ress)
						})
					},
					fail(err) {
						uni.hideLoading()
						console.log(err)
					}
				})
			},
            getAccessToken(path, ress) {
				let self = this
				uni.request({
					url: '/api-proxy/oauth/2.0/token',//生产https://aip.baidubce.com/oauth/2.0/token 测试 /api/oauth/2.0/token
					data: {
						grant_type: 'client_credentials',
						client_id: self.dataObj.client_id,
						client_secret: self.dataObj.client_secret
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
                        self.uploadImage(path, res.data.access_token, ress)
						uni.hideLoading()
					},
					fail(err) {
						uni.hideLoading()
						console.log(err)
					}
				})
			},
            uploadImage(path, token, ress) {
				let self = this
				uni.request({
					url: '/api-proxy/rest/2.0/ocr/v1/idcard',//生产https://aip.baidubce.com/rest/2.0/ocr/v1/idcard 测试 /api/rest/2.0/ocr/v1/idcard
					data: {
						image: path,
						access_token: token,
						id_card_side: 'back'
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.hideLoading()
						self.$emit('end', {
							path: ress,
							animal: false,
							words: res.data
						})
                        if(res.data.words_result.公民身份号码){
                            self.cardSuccess(res.data.words_result.公民身份号码.value)
                        }else{
                            uni.showToast({
                                title:'未识别到身份信息，请重新上传！',
                                duration:3000,
                                icon:'none'
                            })
                        }
					},
					fail(err) {
						uni.hideLoading()
						console.log(err)
					}
				})
			},
        getTable: async function (type) {
            let parm = {
                searchKey: this.keyWord,
                pageSize: 10,
                pageNo: 1
            };
            let { data, code, msg } = await getResidentBaseInfo(parm);
            if (code == 0) {
                this.setData({
                    tableData: this.tableData.concat(data.list)
                });
            } else {
            }
        },

        cardSuccess: async function (e) {
            this.setData({
                keyWord: e,
                tableData: []
            });
            // 跳转至居民详情页
            await this.getTable('card');
            if (this.tableData.length != 0) {
                uni.navigateTo({
                    url: `/subpages/searchResult/pages/resiInfo/resiInfo?resiId=${this.tableData[0].resiId}`
                });
            } else {
                uni.showToast({
                    title: '未查询到该居民，请录入居民信息',
                    duration: 3000,
                    icon: 'none',
                    success: function () {
                        setTimeout(() => {
                            uni.navigateTo({
                                url: `/subpages/addResi/pages/addResi/addResi?type=add&name=${e.detail.name.text}&idCard=${e.detail.id.text}&gender=${e.detail.gender.text}&birth=${e.detail.birth.text}`
                            });
                        }, 3000);
                    }
                });
            }
        },

        back() {
            uni.navigateBack({
                delta: 1
            });
        }
    }
};
</script>
<style>
/* subpages/OCRCard/pages/index/index.wxss */
page {
    width: 100%;
    min-height: 100vh;
    overflow-y: scroll;
    background-color: #f7f7f7;
}
.top20 {
    margin-top: 20rpx;
}
.header {
    width: 100%;
    height: 550rpx;
    overflow: hidden;
    background-image: url('/static/subpages/OCRCard/image/headerBg.png');
    background-size: 100% 100%;
}
.blue {
    color: #3a80e7;
}
.red {
    color: #ff502e;
}
.header .header-bg {
    width: 100%;
    height: 444rpx;
    position: absolute;
    height: 100%;
    z-index: -997;
}
.header .navigation {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #333333;
    font-size: 32rpx;
    position: relative;
    z-index: 100;
}
.gray {
    color: #999;
    font-size: 28rpx;
}
.font32 {
    font-size: 32rpx;
}
.back {
    width: 30rpx;
    height: 30rpx;
    margin-left: 20rpx;
    position: absolute;
    margin-top: 20rpx;
    border-radius: 0rpx;
    z-index: 101;
}

.body {
    position: relative;
    top: -200rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 70rpx;
    align-items: center;
}
button {
    height: 84rpx;
    line-height: 84rpx;
    width: 100% !important;
    padding: 0;
    text-align: center;
    color: #fff;
    font-size: 33rpx;
    border-radius: 84rpx;
    background: linear-gradient(to right, #82b4fd, #3e93fe);
    margin: 160rpx 0 0 !important;
}
.ocr {
    width: 100%;
}
.color {
    color: #fff;
}
</style>
