package com.jeequan.jeepay.thirdparty.service.ocr;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.jeequan.jeepay.core.interfaces.IOCRApiService;
import com.jeequan.jeepay.core.model.DBOCRConfig;
import com.jeequan.jeepay.core.model.OCRImgParams;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.util.OCRUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 阿里OCR接口
 *
 * @author xiaoyu
 *
 * @date 2022/1/11 15:31
 */
@Slf4j
@Service
public class AliOCRApiService implements IOCRApiService {

    @Autowired private SysConfigService sysConfigService;

    private DBOCRConfig getocrConfig() {
        DBOCRConfig dbocrConfig = sysConfigService.getOcrConfig();
        return dbocrConfig;
    }

    /**
     * @author: xiaoyu
     * @date: 2022/1/12 11:16
     * @describe: 身份证识别信息
     */
    @Override
    public OCRImgParams getIdCardInfo(String imgUrl){
        RecognizeIdcardRequest request = new RecognizeIdcardRequest();
        OCRImgParams ocrImgParams = new OCRImgParams();
        try {
            Client client = createClient();
            // 图片地址
            request.setUrl(imgUrl);

            // 发起请求
            log.info("【OCR识别】请求的图片地址：{}", imgUrl);
            RecognizeIdcardResponse response = client.recognizeIdcard(request);

            // 阿里云OCR返回JSON数据参数
            JSONObject jsonResult = JSONObject.parseObject(response.getBody().getData());
            log.info("【OCR识别】response-header：{}, response-body：{}", response.getHeaders(), jsonResult);

            JSONObject dataJson = jsonResult.getJSONObject("data");
            // 正面照数据
            JSONObject faceJson = dataJson.getJSONObject("face");
            JSONObject backJson = dataJson.getJSONObject("back");
            if (faceJson != null) {
                JSONObject paramsJson = faceJson.getJSONObject("data");
                // 姓名
                ocrImgParams.setIdcardName(paramsJson.getString("name"));
                // 性别
                ocrImgParams.setIdcardSex(paramsJson.getString("sex"));
                // 地址
                ocrImgParams.setIdcardAddress(paramsJson.getString("address"));
                // 身份证号
                ocrImgParams.setIdcardNo(paramsJson.getString("idNumber"));
            }
            if (backJson != null) {
                JSONObject paramsJson = backJson.getJSONObject("data");
                // 签发机关
                String issueAuthority = paramsJson.getString("issueAuthority");
                // 有效日期 [日期格式转换]
                String validPeriod = paramsJson.getString("validPeriod");
                OCRUtil.setIdCardDate(validPeriod, ocrImgParams);
            }
        }catch (Exception e) {
            log.info("【阿里云OCR】身份证识别异常", e);
        }
        return ocrImgParams;
    }

    @Override
    public OCRImgParams getBusinessLicenceInfo(String imgUrl) {
        RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
        OCRImgParams ocrImgParams = new OCRImgParams();
        try {
            Client client = createClient();
            // 图片地址
            request.setUrl(imgUrl);

            // 发起请求
            log.info("【OCR识别】请求的图片地址：{}", imgUrl);
            RecognizeBusinessLicenseResponse response = client.recognizeBusinessLicense(request);
            JSONObject jsonResult = JSONObject.parseObject(response.getBody().getData());
            log.info("【OCR识别】response-header：{}, response-body：{}", response.getHeaders(), jsonResult);

            // 阿里云OCR返回JSON数据参数
            JSONObject dataJson = jsonResult.getJSONObject("data");
            // 社会统一信用代码
            ocrImgParams.setLicenseNo(dataJson.getString("creditCode"));
            // 公司名称
            ocrImgParams.setMchFullName(dataJson.getString("companyName"));
            // 有效期
            OCRUtil.setLicenseDateAli(dataJson, ocrImgParams);
            // 公司地址
            ocrImgParams.setLicenseAddress(dataJson.getString("businessAddress"));
            // 法人
            ocrImgParams.setLicensePerson(dataJson.getString("legalPerson"));
            // 经营范围
            ocrImgParams.setLicenseBusiness(dataJson.getString("businessScope"));
        }catch (Exception e) {
            log.info("【阿里云OCR】营业执照识别异常", e);
        }
        return ocrImgParams;
    }

    @Override
    public OCRImgParams getBankCardInfo(String imgUrl) {
        RecognizeBankCardRequest request = new RecognizeBankCardRequest();
        OCRImgParams ocrImgParams = new OCRImgParams();
        try {
            Client client = createClient();
            // 图片地址
            request.setUrl(imgUrl);

            // 发起请求
            log.info("【OCR识别】请求的图片地址：{}", imgUrl);
            RecognizeBankCardResponse response = client.recognizeBankCard(request);
            JSONObject jsonResult = JSONObject.parseObject(response.getBody().getData());
            log.info("【OCR识别】response-header：{}, response-body：{}", response.getHeaders(), jsonResult);

            // 阿里云OCR返回JSON数据参数
            JSONObject dataJson = jsonResult.getJSONObject("data");
            ocrImgParams.setSettAccountBankName(dataJson.getString("bankName"));
            ocrImgParams.setSettAccountNo(dataJson.getString("cardNumber"));
        }catch (Exception e) {
            log.info("【阿里云OCR】银行卡识别异常", e);
        }
        return ocrImgParams;
    }


    /**
     * @author: xiaoyu
     * @date: 2022/1/11 15:50
     * @describe: 初始化账号Client
     */
    private Client createClient() {
        try {
            Config config = new Config();
            String accessKeyId = getocrConfig().getAliAccessKeyId();
            String accessKeySecret = getocrConfig().getAliAccessKeySecret();
            config.setAccessKeyId(accessKeyId);
            config.setAccessKeySecret(accessKeySecret);
            config.setEndpoint("ocr-api.cn-hangzhou.aliyuncs.com");
            return new Client(config);
        }catch (Exception e) {
            log.error("阿里云OCR初始化Client异常", e);
        }
        return null;
    }
}
