package com.heyu.api.controller.idcard;


import com.heyu.api.data.annotation.EbAuthentication;
import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.dto.IdCardAddressModel;
import com.heyu.api.data.utils.ApiR;
import com.heyu.api.data.utils.IDCardValidatorUtils;
import com.heyu.api.data.utils.R;
import com.heyu.api.request.certificate.ApiIdentityCardSecondRequest;
import com.heyu.api.resp.card.IdCardOCRVerificationResp;
import com.heyu.api.tencent.handle.TIdCardOCRVerificationHandle;
import com.heyu.api.tencent.handle.ThirdTIdCardVerificationHandle;
import com.heyu.api.tencent.request.TTIdCardOCRVerificationRequest;
import com.heyu.api.tencent.resp.ThirdIdCardResp;
import com.tencentcloudapi.faceid.v20180301.models.IdCardOCRVerificationResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/***
 *
 *
 * https://console.cloud.tencent.com/api/explorer?Product=faceid&Version=2018-03-01&Action=IdCardOCRVerification
 *
 *
 *
 *身份证识别及信息核验
 *
 *
 * 二要素
 *
 *
 *
 */
@Slf4j
@RestController
@RequestMapping("/idcard")
public class IdCardOCRVerificationController {

    public final static String SUCCESS_MSG = "姓名和身份证号一致";
    public final static String FAILED_MSG = "姓名和身份证号不一致";

    public final static String SUCCESS_CODE = "1";
    public final static String FAILED_CODE = "0";

    @Autowired
    private TIdCardOCRVerificationHandle tIdCardOCRVerificationHandle;


    @Autowired
    private ThirdTIdCardVerificationHandle thirdTIdCardVerificationHandle;


    // http://localhost:8888/idcard/verification?idCardNumber=430529199209255030&realName=瞿贻晓
    // https://api.1024api.com/api-interface/bank/card/2/verify?bankCardNumber=6214855713516769&realName=瞿贻晓
    @EbAuthentication(tencent = ApiConstants.TENCENT_AUTH)
    @RequestMapping("/verification")
    public R certification(ApiIdentityCardSecondRequest apiIdentityCardRequest) {
        return doCertification(apiIdentityCardRequest);
    }





    public R doCertification(ApiIdentityCardSecondRequest apiIdentityCardRequest){
        // 构建基本的返回参数
        IdCardOCRVerificationResp idCardOCRVerificationResp = new IdCardOCRVerificationResp();
        idCardOCRVerificationResp.setIdCardNumber(IDCardValidatorUtils.maskIdCard(apiIdentityCardRequest.getIdCardNumber()));
        idCardOCRVerificationResp.setRealName(IDCardValidatorUtils.maskRealName(apiIdentityCardRequest.getRealName()));

        // 封装请求参数
        TTIdCardOCRVerificationRequest ttIdCardOCRVerificationRequest = new TTIdCardOCRVerificationRequest();
        ttIdCardOCRVerificationRequest.setIdCard(apiIdentityCardRequest.getIdCardNumber());
        ttIdCardOCRVerificationRequest.setName(apiIdentityCardRequest.getRealName());

        // 请求腾讯云的第三方平台
        ApiR<ThirdIdCardResp> thirdIdCardRespApiR = thirdTIdCardVerificationHandle.handle(ttIdCardOCRVerificationRequest);
        /***
         *
         * {
         *          "msg": "成功",
         *          "success": true,
         *          "code": 200, //code为200 data才会有值，400参数格式错误
         *          "data": {
         *          "birthday": "19840816",
         *          "result": 1,//1.不一致 0.一致
         *          "address": "浙江省杭州市淳安县",//地址
         *          "orderNo": "202406271440416095174",//订单编号
         *          "sex": "男",//性别
         *          "desc": "不一致"//描述
         *          }
         * }
         */
        if (thirdIdCardRespApiR.isSuccess()) {
            ThirdIdCardResp thirdIdCardResp = thirdIdCardRespApiR.getData();
            if (thirdIdCardResp != null) {
                ThirdIdCardResp.DataDTO resultDTO = thirdIdCardResp.getData();
                if (resultDTO.getResult() == 0 && thirdIdCardResp.getCode() == 200) {
                    // 封装请求成功的返回参数
                    fillBaseIdCard(apiIdentityCardRequest.getIdCardNumber(), idCardOCRVerificationResp);
                    idCardOCRVerificationResp.setDesc(SUCCESS_MSG);
                    idCardOCRVerificationResp.setCode(SUCCESS_CODE);
                } else {
                    idCardOCRVerificationResp.setCode(FAILED_CODE);             //其他情况
                    idCardOCRVerificationResp.setDesc(resultDTO.getDesc());             //其他情况
                }
                return R.ok().setData(idCardOCRVerificationResp);
            }
        }



        ApiR<IdCardOCRVerificationResponse> apiR = tIdCardOCRVerificationHandle.handle(ttIdCardOCRVerificationRequest);
        if (apiR.isSuccess()) {
            IdCardOCRVerificationResponse idCardOCRVerificationResponse = apiR.getData();
            if (idCardOCRVerificationResponse != null) {
                /***
                 * 认证结果码，收费情况如下。
                 * - 收费结果码：
                 * 0: 姓名和身份证号一致。
                 * -1: 姓名和身份证号不一致。
                 * - 不收费结果码：
                 * -2: 非法身份证号（长度、校验位等不正确）。
                 * -3: 非法姓名（长度、格式等不正确）。
                 * -4: 证件库服务异常。
                 * -5: 证件库中无此身份证记录。
                 * -6: 权威比对系统升级中，请稍后再试。
                 * -7: 认证次数超过当日限制。
                 * 示例值：0
                 */
                if ("0".equals(idCardOCRVerificationResponse.getResult())) {

                    // 封装请求成功的返回参数
                    fillBaseIdCard(apiIdentityCardRequest.getIdCardNumber(),idCardOCRVerificationResp);
                    idCardOCRVerificationResp.setDesc(SUCCESS_MSG);
                    idCardOCRVerificationResp.setCode(SUCCESS_CODE);             // 姓名和身份证号一致。

                } else if ("-1".equals(idCardOCRVerificationResponse.getResult())) {
                    // 姓名和身份证号不一致, 则返回失败
                    idCardOCRVerificationResp.setCode(FAILED_CODE);
                    idCardOCRVerificationResp.setDesc(FAILED_MSG);

                } else if ("-4".equals(idCardOCRVerificationResponse.getResult())               // -4: 证件库服务异常。
                        || "-6".equals(idCardOCRVerificationResponse.getResult())               // -6: 权威比对系统升级中，请稍后再试。
                        || "-7".equals(idCardOCRVerificationResponse.getResult())               // -7: 认证次数超过当日限制。
                ) {
                    return R.error("服务异常，不会收费");
                } else {
                    //其他失败情况
                    idCardOCRVerificationResp.setCode(FAILED_CODE);
                    idCardOCRVerificationResp.setDesc(idCardOCRVerificationResponse.getDescription());             //其他情况
                }

                return R.ok().setData(idCardOCRVerificationResp);

            }
        }
        return R.error(apiR.getErrorMsg());
    }



    public void fillBaseIdCard(String idCardNumber,IdCardOCRVerificationResp idCardOCRVerificationResp) {
        IdCardAddressModel idCardAddressModel = IDCardValidatorUtils.getAddrInfo(idCardNumber);
        // 封装地址信息
        idCardOCRVerificationResp.setCountry(idCardAddressModel.getCountry());
        idCardOCRVerificationResp.setProvince(idCardAddressModel.getProvince());
        idCardOCRVerificationResp.setCity(idCardAddressModel.getCity());
        idCardOCRVerificationResp.setArea(idCardAddressModel.getCounty());
        idCardOCRVerificationResp.setDetailAddress(idCardAddressModel.getProvince() + idCardAddressModel.getCity() + idCardAddressModel.getCounty());

        idCardOCRVerificationResp.setBirthday(idCardAddressModel.getBirthday());
        idCardOCRVerificationResp.setSex(idCardAddressModel.getSex());
        idCardOCRVerificationResp.setSexChar(idCardAddressModel.getSexChar());
    }
}