<template>
    <view class="upImg row justify-center items-center" @click="chooseImg">
        <view v-if="img" style="width: 100%;height: 100%;">
            <image @click.stop="previewImage" :src="img" mode="aspectFit"/>
            <view class="row justify-center items-center">
                <view class="shangc">重新上传</view>
            </view>
        </view>
        <view v-else style="width: 100%;height: 100%;opacity: 0;">
            <text>1</text>
        </view>
    </view>
</template>
<script>
export default {
    props: ['img','type'],
    components: { },
    data() {
        return {
            action: this.host2 + "/api/File/UploadTencent",
            access_token: '',
        }
    },
    onLoad(options) {
        
    },
    onShow() {

    },
    mounted() {
       
    },
    methods: {
        //获取百度ai平台token
        getAccess_token() {
            let that = this;
            uni.request({
                url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=8gjFAsKQBmkRXwWIWkstlQew&client_secret=SBUAtyEBTQpVmA81W4u2vS5ScPwfRNBS", // 百度获取token接口地址
                data: {
                    grant_type: "client_credentials", // 固定写死
                    client_id: "8gjFAsKQBmkRXwWIWkstlQew", // by:chaoxuekeji
                    client_secret: "SBUAtyEBTQpVmA81W4u2vS5ScPwfRNBS",
                },
                method: "POST",
                success(res) {
                    console.log("获取token成功", res);
                    that.access_token = res.data.access_token;
                },
                fail(e) {
                },
            });
        },
        previewImage() {
            uni.previewImage({
                urls: [this.img],
                current: this.img,
                longPressActions: {
                    itemList: ["发送给朋友", "保存图片", "收藏"],
                    success: function(data) {},
                    fail: function(err) {
                        console.log(err.errMsg);
                    },
                },
            });
        },
        chooseImg() {
            this.getAccess_token()
            let that = this;
            uni.chooseImage({
                count: 1, //默认9
                sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ["album"], //从相册选择
                success: function (res) {
                    wx.getFileSystemManager().readFile({
                        filePath: res.tempFilePaths[0],
                        encoding: "base64", //编码格式
                        success: (ans) => {
                            uni.showLoading({
                                title: "上传中",
                            });
                            if(that.type){
                                that.getImgInfo(ans.data, that.access_token, (_res) => {
                                    if (_res.data.direction == 1) {
                                        //未定义，图片类型错误
                                        wx.showToast({
                                            title: "图片类型错误!",
                                            icon: "none",
                                            duration: 1000,
                                        });
                                    } else {
                                        let datas = _res.data.words_result;
                                        that.upFile(res.tempFilePaths[0], (uploadRes) => {
                                            let BusinessLicense = JSON.parse(
                                                uploadRes.data
                                            ).data;
                                            let infor = {}
                                            infor.BusinessLicense = BusinessLicense
                                            if(that.type == '1'){
                                                infor.CompanyName = datas.单位名称.words
                                                infor.LegalPerson = datas.法人.words
                                                infor.UnifiedCode = datas.社会信用代码.words
                                                infor.Addres = datas.地址.words 
                                            }else if(that.type == '2'){
                                                infor.LegalIdCardNumber = datas.公民身份号码.words 
                                            }else if(that.type == '3'){
                                                let y = datas.失效日期.words.substring(0, 4)
                                                let m = datas.失效日期.words.substring(4, 6)
                                                let d = datas.失效日期.words.substring(6, 8)
                                                infor.LegalIdCardTime = `${y}-${m}-${d}`
                                            }
                                            console.log(datas,"infor", infor);
                                            that.$emit('onSuccess', infor);
                                        });
                                    }
                                });
                            }else{
                                that.upFile(res.tempFilePaths[0], (uploadRes) => {
                                let BusinessLicense = JSON.parse(
                                    uploadRes.data
                                ).data;
                                let infor = {}
                                infor.BusinessLicense = BusinessLicense
                                console.log("infor", infor);
                                that.$emit('onSuccess', infor);
                            });
                                console.log("res.tempFilePaths[0]",res.tempFilePaths[0]);
                            }
                        },
                    });
                },
            });
        },
        //图片上传
        upFile(filePath,resCall) {
            let that = this;
            uni.uploadFile({
                url: that.action,
                filePath: filePath,
                name: 'file',
                formData: {
                    user: 'tesdt'
                },
                success: (uploadFileRes) => {
                    if (uploadFileRes.statusCode == 200) {
                        uni.hideLoading()
                        resCall(uploadFileRes);
                    }else{
                        wx.showToast({
                            title: uploadFileRes.message,
                            icon: 'none',
                            duration: 1000
                        })
                    }

                },
                fail: function(res) {
                    console.log(res)
                    wx.showToast({
                        title: '上传失败!',
                        icon: 'none',
                        duration: 1000
                    })
                }
            });
        },
        //提取营业执照信息
        getImgInfo(data, token, resCall) {
            let that = this;
            let url = "";
            let id_card_side = ""
            if(that.type==1) url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?"
            else if(that.type==2||that.type==3) {
                url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?"
                id_card_side = that.type==2?"front":"back"
            }
            console.log(`${url}access_token=${token}`,"url---");
            uni.request({
                url:`${url}access_token=${token}`,
                method: "POST",
                header: {
                 "Content-Type": "application/x-www-form-urlencoded",
                },
                data: {
                    image: data,
                    id_card_side,
                },
                success(res) {
                    resCall(res);
                },
                fail(res) {
                    wx.showToast({
                        title: "图片类型错误!",
                        icon: "none",
                        duration: 1000,
                    });
                },
            });
        },
    }
}
</script>
<style lang="scss" scoped>
@import url("@/asset/css/flex.css");
.upImg{
    width: 100%;
    height: 100%;
}
.upImg image{
    width: 100%;
    height: 100%;
}
.upImg view{
    position: absolute;
    left: 0;
    right: 0;
    z-index: 2;
    bottom: 10rpx;
}
.shangc{
    width: 252rpx;
    border-radius: 50rpx;
    border: 1rpx solid #0399FF;
    color: #0399FF;
    background: #F3F5F9;
    font-size: 32rpx;
    font-weight: 800;
    margin: auto;
    line-height: 80rpx;
    padding: 0 31rpx;
    text-align: center;
}
</style>
