package shop.alien.store.util.ali;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.store.service.*;
import shop.alien.store.util.ali.ocr.OcrStrategy;
import shop.alien.store.util.ali.ocr.OcrStrategyFactory;
import shop.alien.util.common.RandomCreateUtil;
import shop.alien.util.common.UniqueRandomNumGenerator;
import shop.alien.util.common.UrlEncode;
import shop.alien.util.system.OSUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

/**
 * 支付宝相关组件
 *
 * @author ssk
 * @version 1.0
 * @date 2024/12/10 8:49
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class AliApi {

    private final StoreUserService storeUserService;

    private final StoreAliPayLogService storeAliPayLogService;

    private final LifeUserService lifeUserService;

    private final StoreAliPayErrorLogService storeAliPayErrorLogService;

    private final StoreAliPayRefundLogService storeAliPayRefundLogService;

    private final OcrStrategyFactory ocrStrategyFactory;

    /**
     * 商家端appId
     */
    @Value("${app.business.appId}")
    private String businessAppId;

    /**
     * 商家端app私钥
     */
    @Value("${app.business.appPrivateKey}")
    private String businessAppPrivateKey;

    /**
     * 商家端app公钥
     */
    @Value("${app.business.appPublicKey}")
    private String businessAppPublicKey;

    /**
     * windows应用公钥证书文件路径
     */
    @Value("${app.business.win.appCertPath}")
    private String businessWinAppCertPath;

    /**
     * windows支付宝公钥证书文件路径
     */
    @Value("${app.business.win.alipayPublicCertPath}")
    private String businessWinAlipayPublicCertPath;

    /**
     * windows支付宝根证书文件路径
     */
    @Value("${app.business.win.alipayRootCertPath}")
    private String businessWinAlipayRootCertPath;

    /**
     * linux应用公钥证书文件路径
     */
    @Value("${app.business.linux.appCertPath}")
    private String businessLinuxAppCertPath;

    /**
     * linux支付宝公钥证书文件路径
     */
    @Value("${app.business.linux.alipayPublicCertPath}")
    private String businessLinuxAlipayPublicCertPath;

    /**
     * linux支付宝根证书文件路径
     */
    @Value("${app.business.linux.alipayRootCertPath}")
    private String businessLinuxAlipayRootCertPath;

    /**
     * 支对称加密算法密钥
     */
    @Value("${ali.aes.encryptKey}")
    private String encryptKey;


    /**
     * 填写阿里配置
     *
     * @return AlipayConfig
     */
    private AlipayConfig setAlipayConfig(String type) {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(businessAppId);
        alipayConfig.setPrivateKey(businessAppPrivateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        if ("windows".equals(OSUtil.getOsName())) {
            alipayConfig.setAppCertPath(businessWinAppCertPath);
            alipayConfig.setAlipayPublicCertPath(businessWinAlipayPublicCertPath);
            alipayConfig.setRootCertPath(businessWinAlipayRootCertPath);
        } else {
            alipayConfig.setAppCertPath(businessLinuxAppCertPath);
            alipayConfig.setAlipayPublicCertPath(businessLinuxAlipayPublicCertPath);
            alipayConfig.setRootCertPath(businessLinuxAlipayRootCertPath);
        }
        if ("aes".equals(type)) {
            alipayConfig.setEncryptType("AES");
            alipayConfig.setEncryptKey(encryptKey);
        }
        return alipayConfig;
    }

    public JSONObject promotionPackagePay(String price, String subject) {
        try {
            JSONObject jsonObject = new JSONObject();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String orderNo = UniqueRandomNumGenerator.generateUniqueCode(19);
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setOutTradeNo(orderNo);
            model.setTotalAmount(price);
            model.setSubject(subject);
            model.setPassbackParams(UrlEncode.getUrlEncode(dateFormat.toString()));
            request.setBizModel(model);
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            String orderStr = "";
            if (response.isSuccess()) {
                orderStr = response.getBody();
            } else {
                System.out.println("调用失败 response：" + response);
                orderStr = "调用失败";
            }
            jsonObject.put("orderStr", orderStr);
            jsonObject.put("orderNo", orderNo);
            return jsonObject;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 退款
     *
     * @param outTradeNo
     * @param refundAmount
     * @param refundReason
     * @return
     */

    public String processRefund(String outTradeNo, String refundAmount, String refundReason, String partialRefundCode) {
        try {
            // TODO 部分退款支付宝接口修改
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(outTradeNo);
            model.setRefundAmount(refundAmount);
            model.setRefundReason(refundReason);
            if (StringUtils.isNotBlank(partialRefundCode)) {
                model.setOutRequestNo(partialRefundCode);
            }
            request.setBizModel(model);
            AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
            String refundReslut = "";
            if (response.isSuccess()) {
                refundReslut = "调用成功";
                // 保存退款信息进入到退款记录表
                JSONObject responseBody = JSONObject.parseObject(response.getBody());
                JSONObject refundResponse = responseBody.getJSONObject("alipay_trade_refund_response");
                
                StoreAliPayRefundLog refundLog = new StoreAliPayRefundLog();
                // 响应基本信息
                refundLog.setResponseCode(refundResponse.getString("code"));
                refundLog.setResponseMsg(refundResponse.getString("msg"));
                // 买家信息
                refundLog.setBuyerLogonId(refundResponse.getString("buyer_logon_id"));
                refundLog.setBuyerOpenId(refundResponse.getString("buyer_open_id"));
                // 资金变动信息
                refundLog.setFundChange(refundResponse.getString("fund_change"));
                // 订单信息
                refundLog.setOutTradeNo(refundResponse.getString("out_trade_no"));
                refundLog.setTradeNo(refundResponse.getString("trade_no"));
                // 退款金额信息
                refundLog.setRefundFee(refundResponse.getString("refund_fee"));
                refundLog.setSendBackFee(refundResponse.getString("send_back_fee"));
                // 退款渠道明细（转换为JSON字符串）
                if (refundResponse.containsKey("refund_detail_item_list")) {
                    JSONArray refundDetailList = refundResponse.getJSONArray("refund_detail_item_list");
                    if (refundDetailList != null) {
                        refundLog.setRefundDetailItemList(JSON.toJSONString(refundDetailList));
                    }
                }
                // 退款时间（字符串转Date）
                String gmtRefundPayStr = refundResponse.getString("gmt_refund_pay");
                if (StringUtils.isNotBlank(gmtRefundPayStr)) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        refundLog.setGmtRefundPay(sdf.parse(gmtRefundPayStr));
                    } catch (ParseException e) {
                        log.warn("解析退款时间失败: {}", gmtRefundPayStr, e);
                    }
                }
                // 退款原因和部分退款编号（从请求参数中获取）
                refundLog.setRefundReason(refundReason);
                refundLog.setOutRequestNo(partialRefundCode);
                // 证书和签名信息
                refundLog.setAlipayCertSn(responseBody.getString("alipay_cert_sn"));
                refundLog.setSign(responseBody.getString("sign"));
                // 标准字段
                refundLog.setDeleteFlag(0);
                refundLog.setCreatedTime(new Date());
                
                storeAliPayRefundLogService.save(refundLog);

            } else {
                log.warn("AliPayConfig.processRefund ERROR Msg={}", response.getBody());
                JSONObject jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_trade_refund_response");
                refundReslut =  jsonObject.getString("sub_msg");
            }
            return refundReslut;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 身份证二要素核验
     *
     * @param name   姓名
     * @param idCard 身份证
     * @return true:验证通过，false:验证失败
     */
    public boolean getIdInfo(String name, String idCard) {
        try {
            log.info("AliPayConfig.getIdInfo?name={}&idCard={}", name, idCard);
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasTwometaCheckRequest request = new DatadigitalFincloudGeneralsaasTwometaCheckRequest();
            DatadigitalFincloudGeneralsaasTwometaCheckModel model = new DatadigitalFincloudGeneralsaasTwometaCheckModel();
            // 设置外部订单号
            model.setOuterBizNo("id_" + createOrderNo());
            // 设置姓名
            model.setCertName(name);
            // 设置证件号码
            model.setCertNo(idCard);
            // 设置证件类型
            model.setCertType("IDENTITY_CARD");
            request.setBizModel(model);
            DatadigitalFincloudGeneralsaasTwometaCheckResponse response = alipayClient.certificateExecute(request);
            JSONObject jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_twometa_check_response");
            return response.isSuccess() && "Success".equals(jsonObject.getString("msg")) && "T".equals(jsonObject.getString("match"));
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.getIdInfo ERROR Msg={}", e.getErrMsg());
            return false;
        }
    }

    /**
     * 单笔转账接口
     *
     * @param name   收款人姓名
     * @param idCard 收款人身份证号
     * @param phone  收款人手机号
     * @param money  收款金额
     * @return 是否成功
     */
    public StoreAliPayLog pay(String name, String idCard, String phone, String money) {
        try {
            log.info("AliPayConfig.pay?name={}&idCard={}&phone={}&money={}", name, idCard, phone, money);
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            // 设置商家侧唯一订单号
            model.setOutBizNo("pay_" + createOrderNo());
            // 设置订单总金额
            model.setTransAmount(money);
            // 设置描述特定的业务场景
            model.setBizScene("DIRECT_TRANSFER");
            // 设置业务产品码
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            // 设置转账业务的标题
            model.setOrderTitle("商家转账");
            // 设置收款方信息
            Participant payeeInfo = new Participant();
            payeeInfo.setCertType("IDENTITY_CARD");
            payeeInfo.setCertNo(idCard);
            payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
            payeeInfo.setIdentity(phone);
            payeeInfo.setName(name);
            model.setPayeeInfo(payeeInfo);
            // 设置业务备注
            model.setRemark("爱丽恩提现业务");
            // 设置转账业务请求的扩展参数
            model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
            request.setBizModel(model);
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess()) {
                //查询用户
                LambdaQueryWrapper<StoreUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(StoreUser::getIdCard, idCard);
                queryWrapper.eq(StoreUser::getPhone, phone);
                queryWrapper.eq(StoreUser::getName, name);
                StoreUser one = storeUserService.getOne(queryWrapper);
                JSONObject jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_fund_trans_uni_transfer_response");
                StoreAliPayLog storeAliPayLog = new StoreAliPayLog();
                storeAliPayLog.setTransAmount(money);
                storeAliPayLog.setOutBizNo(jsonObject.getString("out_biz_no"));
                storeAliPayLog.setOrderId(jsonObject.getString("order_id"));
                storeAliPayLog.setPayFundOrderId(jsonObject.getString("pay_fund_order_id"));
                storeAliPayLog.setTransDate(jsonObject.getString("trans_date"));
                if (null == one) {
                    LambdaQueryWrapper<LifeUser> userQueryWrapper = new LambdaQueryWrapper<>();
                    userQueryWrapper.eq(LifeUser::getIdCard, idCard);
                    userQueryWrapper.eq(LifeUser::getUserPhone, phone);
                    userQueryWrapper.eq(LifeUser::getRealName, name);
                    LifeUser userOne = lifeUserService.getOne(userQueryWrapper);
                    storeAliPayLog.setStoreUserId(userOne.getId());
                } else {
                    storeAliPayLog.setStoreUserId(one.getId());

                }
                storeAliPayLogService.save(storeAliPayLog);
                return storeAliPayLog;
            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.pay ERROR Msg={}", e.getErrMsg());
            return null;
        }
    }

    /**
     * 单笔转账接口 提现使用
     *
     * @param name    收款人姓名
     * @param idCard  收款人身份证号
     * @param account 收款人支付宝账号
     * @param money   收款金额
     * @param phone   收款金额
     * @return 是否成功
     */
    public StoreAliPayLog payAccount(String name, String idCard, String account, String money, String phone) {
        try {
            log.info("AliPayConfig.pay?name={}&idCard={}&account={}&money={}&phone={}", name, idCard, account, money, phone);
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            // 设置商家侧唯一订单号
            model.setOutBizNo("pay_" + createOrderNo());
            // 设置订单总金额
            model.setTransAmount(money);
            // 设置描述特定的业务场景
            model.setBizScene("DIRECT_TRANSFER");
            // 设置业务产品码
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            // 设置转账业务的标题
            model.setOrderTitle("商家转账");
            // 设置收款方信息
            Participant payeeInfo = new Participant();
            // 智能判断收款方类型
            if (account.startsWith("2088") && account.length() == 16) {
                // 如果是商户ID格式（2088开头的16位数字）
                payeeInfo.setIdentityType("ALIPAY_USER_ID");
                log.info("检测到收款方为商户ID: {}", account);
//                payeeInfo.setName("爱丽恩严(大连)商务科技有限公司");
            } else {
                // 默认为支付宝账号（手机号或邮箱）
                payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
                log.info("检测到收款方为支付宝账号: {}", account);
                payeeInfo.setCertType("IDENTITY_CARD");
                payeeInfo.setCertNo(idCard);
                payeeInfo.setName(name);
            }
            if(null != account){
                payeeInfo.setIdentity(account);
            }else{
                payeeInfo.setIdentity(phone);
            }
            payeeInfo.setName(name);
            model.setPayeeInfo(payeeInfo);
            // 设置业务备注
            model.setRemark("爱丽恩提现业务");
            // 设置转账业务请求的扩展参数
            model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
            request.setBizModel(model);
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess()) {
                //查询用户
                LambdaQueryWrapper<StoreUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(StoreUser::getIdCard, idCard);
                queryWrapper.eq(StoreUser::getPhone, phone);
                queryWrapper.eq(StoreUser::getName, name);
                StoreUser one = storeUserService.getOne(queryWrapper);
                JSONObject jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_fund_trans_uni_transfer_response");
                StoreAliPayLog storeAliPayLog = new StoreAliPayLog();
                storeAliPayLog.setTransAmount(money);
                storeAliPayLog.setOutBizNo(jsonObject.getString("out_biz_no"));
                storeAliPayLog.setOrderId(jsonObject.getString("order_id"));
                storeAliPayLog.setPayFundOrderId(jsonObject.getString("pay_fund_order_id"));
                storeAliPayLog.setTransDate(jsonObject.getString("trans_date"));
                if (null == one) {
                    LambdaQueryWrapper<LifeUser> userQueryWrapper = new LambdaQueryWrapper<>();
                    userQueryWrapper.eq(LifeUser::getIdCard, idCard);
                    userQueryWrapper.eq(LifeUser::getUserPhone, phone);
                    userQueryWrapper.eq(LifeUser::getRealName, name);
                    LifeUser userOne = lifeUserService.getOne(userQueryWrapper);
                    storeAliPayLog.setStoreUserId(userOne.getId());
                } else {
                    storeAliPayLog.setStoreUserId(one.getId());

                }
                storeAliPayLogService.save(storeAliPayLog);
                return storeAliPayLog;
            } else if(response.getCode().equals("40004")){
                StoreAliPayLog storeAliPayLog = new StoreAliPayLog();
                StoreAliPayErrorLog storeAliPayErrorLog = new StoreAliPayErrorLog();
                LambdaQueryWrapper<StoreUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(StoreUser::getIdCard, idCard);
                queryWrapper.eq(StoreUser::getPhone, phone);
                queryWrapper.eq(StoreUser::getName, name);
                StoreUser one = storeUserService.getOne(queryWrapper);
                String subInfo = getMassage(response.getSubCode());
                storeAliPayErrorLog.setTransAmount(money);
                String bizContentStr = (String) response.getParams().get("biz_content");
                storeAliPayErrorLog.setSubCode(response.getSubCode());
                storeAliPayErrorLog.setSubMsg(response.getSubMsg());
                storeAliPayErrorLog.setBizContent(bizContentStr);
                storeAliPayErrorLog.setInformation(subInfo);
                if (null == one) {
                    LambdaQueryWrapper<LifeUser> userQueryWrapper = new LambdaQueryWrapper<>();
                    userQueryWrapper.eq(LifeUser::getIdCard, idCard);
                    userQueryWrapper.eq(LifeUser::getUserPhone, phone);
                    userQueryWrapper.eq(LifeUser::getRealName, name);
                    LifeUser userOne = lifeUserService.getOne(userQueryWrapper);
                    storeAliPayErrorLog.setLifeUserId(userOne.getId());
                } else {
                    storeAliPayErrorLog.setStoreUserId(one.getId());
                }
                storeAliPayErrorLogService.save(storeAliPayErrorLog);
                storeAliPayLog.setStoreAliPayErrorLog(storeAliPayErrorLog);
                return storeAliPayLog;
            }else{
                StoreAliPayLog storeAliPayLog = new StoreAliPayLog();
                StoreAliPayErrorLog storeAliPayErrorLog = new StoreAliPayErrorLog();
                storeAliPayErrorLog.setInformation("支付宝异常: 请稍后再试");
                storeAliPayLog.setStoreAliPayErrorLog(storeAliPayErrorLog);
                return storeAliPayLog;
            }
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.pay ERROR Msg={}", e.getErrMsg());
            return null;
        }
    }

    /**
     * 银行卡核验
     *
     * @param name     姓名
     * @param idCard   身份证
     * @param bankCard 银行卡
     * @param phone    手机号
     */
    public boolean validateBankCardInfo(String name, String idCard, String bankCard, String phone) {
        try {
            log.info("AliPayConfig.validateBankCardInfo?name={}&idCard={}&bankCard={}&phone={}", name, idCard, bankCard, phone);
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasBankcardCheckRequest request = new DatadigitalFincloudGeneralsaasBankcardCheckRequest();
            DatadigitalFincloudGeneralsaasBankcardCheckModel model = new DatadigitalFincloudGeneralsaasBankcardCheckModel();
            // 设置外部订单号
            model.setOuterBizNo("bank_" + createOrderNo());
            // 设置产品类型
            model.setProductType("BANKCARD_TWO_META");
            // 设置姓名
            model.setCertName(name);
            // 设置证件号码
            model.setCertNo(idCard);
            // 设置银行卡号
            model.setBankcardNo(bankCard);
            // 设置手机号
            model.setPhone(phone);
            request.setBizModel(model);
            DatadigitalFincloudGeneralsaasBankcardCheckResponse response = alipayClient.certificateExecute(request);
            JSONObject jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_twometa_check_response");
            return response.isSuccess() && "Success".equals(jsonObject.getString("msg")) && "T".equals(jsonObject.getString("match"));
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.getBankCardInfo ERROR Msg={}", e.getErrMsg());
            return false;
        }
    }

    /**
     * h5人脸核身初始化
     *
     * @param name   姓名
     * @param idCard 身份证
     * @return {
     * "datadigital_fincloud_generalsaas_face_verification_initialize_response": {
     * "code": "10000",
     * "msg": "Success",
     * //认证单据号，请保留以便排查问题。
     * "certify_id": "adsfasdfasdf",
     * //H5人脸核身地址
     * "web_url": "http://alipay.com/xxx"
     * }
     */
    public JSONObject h5FaceInit(String name, String idCard) {
        try {
            log.info("AliPayConfig.validateFace?name={}&idCard={}", name, idCard);
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig("aes"));
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasFaceVerificationInitializeRequest request = new DatadigitalFincloudGeneralsaasFaceVerificationInitializeRequest();
            DatadigitalFincloudGeneralsaasFaceVerificationInitializeModel model = new DatadigitalFincloudGeneralsaasFaceVerificationInitializeModel();
            // 设置商户请求的唯一标识
            model.setOuterOrderNo("face_" + createOrderNo());
            // 设置人脸核身具体类型目前仅支持
            model.setBizCode("DATA_DIGITAL_BIZ_CODE_FACE_VERIFICATION");
            // 设置认证类型
            model.setIdentityType("CERT_INFO");
            // 设置证件类型
            model.setCertType("IDENTITY_CARD");
            // 设置真实姓名
            model.setCertName(name);
            // 设置证件号
            model.setCertNo(idCard);
            request.setBizModel(model);
            // 需要使用对称加密算法
            request.setNeedEncrypt(true);
            DatadigitalFincloudGeneralsaasFaceVerificationInitializeResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess()) {
                return JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_face_verification_initialize_response");
            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.validateFace ERROR Msg={}", e.getErrMsg());
            return null;
        }
    }

    /**
     * h5人脸核身结果查询
     *
     * @param certifyId 认证单据号
     * @return {
     * "datadigital_fincloud_generalsaas_face_verification_query_response": {
     * "code": "10000",
     * "msg": "Success",
     * //人脸认证状态。PROCESSING：初始化；SUCCESS：认证通过；FAIL：认证不通过。
     * "certify_state": "PROCESSING",
     * //活体检测结果分数
     * "score": "30",
     * //人脸图片质量分
     * "quality": "2",
     * //base64过后的图片图片
     * "alive_photo": "adsfsdfsdf",
     * //本次认证是否存在安全风险，true：检测到安全风险；false：未检测到安全风险。
     * "attack_flag": "true",
     * //人脸认证元数据信息
     * "meta_info": {
     * //设备类型
     * "device_type": "harmony"
     * }
     * }
     */
    public JSONObject h5FaceResult(String certifyId) {
        try {
            log.info("AliPayConfig.getFaceResult?certifyId={}", certifyId);
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasFaceVerificationQueryRequest request = new DatadigitalFincloudGeneralsaasFaceVerificationQueryRequest();
            DatadigitalFincloudGeneralsaasFaceVerificationQueryModel model = new DatadigitalFincloudGeneralsaasFaceVerificationQueryModel();
            // 设置填入人脸核身初始化阶段获取到的certify_id
            model.setCertifyId(certifyId);
            // 设置是否需要返回活体结果图片
            model.setNeedAlivePhoto("N");
            request.setBizModel(model);
            DatadigitalFincloudGeneralsaasFaceVerificationQueryResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess()) {
                return JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_face_verification_query_response");
            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.getFaceResult ERROR Msg={}", e.getErrMsg());
            return null;
        }
    }

    /**
     * 跳转支付宝人脸核身初始化
     *
     * @param name   姓名
     * @param idCard 身份证
     * @return certify_id
     */
    public JSONObject jumpToAliPayInit(String name, String idCard) {
        try {
            log.info("AliPayConfig.jumpToAliPayInit?name={}&idCard={}", name, idCard);
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasFaceCertifyInitializeRequest request = new DatadigitalFincloudGeneralsaasFaceCertifyInitializeRequest();
            DatadigitalFincloudGeneralsaasFaceCertifyInitializeModel model = new DatadigitalFincloudGeneralsaasFaceCertifyInitializeModel();
            // 设置商户请求的唯一标识
            model.setOuterOrderNo("to_ali_" + createOrderNo());
            // 设置H5人脸核身场景码
            model.setBizCode("FUTURE_TECH_BIZ_FACE_SDK");
            // 设置认证信息
            OpenCertifyIdentifyInfo identityParam = new OpenCertifyIdentifyInfo();
            identityParam.setCertType("IDENTITY_CARD");
            identityParam.setCertName(name);
            identityParam.setCertNo(idCard);
            identityParam.setIdentityType("CERT_INFO");
            model.setIdentityParam(identityParam);
            // 设置商户配置信息
            OpenCertifyMerchantConfigs merchantConfig = new OpenCertifyMerchantConfigs();
            //人脸保存策略, 保存活体人脸: reserve, 不保存活体人脸: never
            merchantConfig.setFaceReserveStrategy("never");
            //认证成功后需要跳转的地址，一般为商户业务页面；若无跳转地址可填空字符""。
            merchantConfig.setReturnUrl("");
            model.setMerchantConfig(merchantConfig);
            request.setBizModel(model);
            DatadigitalFincloudGeneralsaasFaceCertifyInitializeResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess()) {
                return JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_face_certify_initialize_response");
            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.jumpToAliPayInit ERROR Msg={}", e.getErrMsg());
            return null;
        }
    }

    /**
     * 跳转支付宝人脸核身开始认证
     *
     * @param certifyId 认证单据号
     * @return certify_url 返回用于唤起刷脸页面的url
     */
    public JSONObject jumpToAliPay(String certifyId) {
        try {
            log.info("AliPayConfig.jumpToAliPay?certifyId={}", certifyId);
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasFaceCertifyVerifyRequest request = new DatadigitalFincloudGeneralsaasFaceCertifyVerifyRequest();
            DatadigitalFincloudGeneralsaasFaceCertifyVerifyModel model = new DatadigitalFincloudGeneralsaasFaceCertifyVerifyModel();
            // 设置本次申请操作的唯一标识
            model.setCertifyId(certifyId);
            request.setBizModel(model);
            DatadigitalFincloudGeneralsaasFaceCertifyVerifyResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess()) {
                return JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_face_certify_verify_response");
            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.jumpToAliPay ERROR Msg={}", e.getErrMsg());
            return null;
        }
    }

    /**
     * 跳转支付宝人脸核身查询记录
     *
     * @param certifyId 认证单据号
     * @return "passed": "T"
     */
    public JSONObject jumpToAliPayResult(String certifyId) {
        try {
            log.info("AliPayConfig.jumpToAliPayResult?certifyId={}", certifyId);
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig(null));
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasFaceCertifyQueryRequest request = new DatadigitalFincloudGeneralsaasFaceCertifyQueryRequest();
            DatadigitalFincloudGeneralsaasFaceCertifyQueryModel model = new DatadigitalFincloudGeneralsaasFaceCertifyQueryModel();
            // 设置本次申请操作的唯一标识
            model.setCertifyId(certifyId);
            request.setBizModel(model);
            DatadigitalFincloudGeneralsaasFaceCertifyQueryResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess()) {
                return JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_face_certify_query_response");
            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            log.error("AliPayConfig.jumpToAliPayResult ERROR Msg={}", e.getErrMsg());
            return null;
        }
    }

    /**
     * 生产订单号
     *
     * @return 订单号
     */
    private String createOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date()) + RandomCreateUtil.getRandomNum(4);
    }

    /**
     * 支付宝OCR识别
     *
     * @param imageId 图片id
     * @param ocrType OCR识别类型
     * @return OCR识别结果
     * @throws Exception 识别异常
     */
    public R ocrRequest(String imageId, String ocrType) throws Exception {
        OcrStrategy strategy = ocrStrategyFactory.getStrategy(ocrType);
        return strategy.recognize(imageId);
    }

    /**
     * 支付宝OCR识别
     *
     * @param imageUrl 图片url
     * @param ocrType OCR识别类型
     * @return OCR识别结果
     * @throws Exception 识别异常
     */
    public R ocrRequestUrl(String imageUrl, String ocrType) throws Exception {
        OcrStrategy strategy = ocrStrategyFactory.getStrategy(ocrType);
        return strategy.recognizeUrl(imageUrl);
    }

    /**
     * 支付宝OCR识别
     *
     * @return OCR识别结果
     * @throws Exception 识别异常
     */
    public R ocrRequestParams(Map<String, String> params) throws Exception {
        OcrStrategy strategy = ocrStrategyFactory.getStrategy(params.get("ocrType"));
        return strategy.recognizeParams(params);
    }


    /**
     * 支付宝OCR识别（Base64方式，使用策略工厂模式）
     * 目前没用w
     * @param imageFile 图片文件
     * @param ocrType OCR识别类型
     * @return OCR识别结果
     * @throws Exception 识别异常
     */
    public R ocrRequestByBase64(MultipartFile imageFile, String ocrType) throws Exception {
        OcrStrategy strategy = ocrStrategyFactory.getStrategy(ocrType);
        byte[] imageBytes = imageFile.getBytes();
        String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
        return strategy.recognizeByBase64(imageBase64);
    }

    private String getMassage(String subCode) {
        switch (subCode) {
            case "ACCOUNT_NOT_EXIST":
                return "收款账户不存在";
            case "ACCOUNT_FROZEN":
                return "收款账户被冻结";
            case "AMOUNT_TOO_BIG":
                return "转账金额过大（超过单笔 / 单日限额）";
            case "AMOUNT_TOO_SMALL":
                return "转账金额过小（低于最低限额）";
            case "INSUFFICIENT_BALANCE":
                return "付款方账户余额不足";
            case "RECEIVER_ID_INVALID":
                return "收款人身份标识无效（如支付宝账号 / 手机号错误）";
            case "RECEIVER_NAME_INVALID":
                return "收款人姓名无效（如姓名与账号不匹配）";
            case "INVALID_PARAMETER":
                return "请求参数无效（如格式错误、必填字段缺失）";
            case "PAYEE_NOT_EXIST":
                return "收款账号不存在或姓名有误";
            case "ACQ.TOTAL_FEE_EXCEED":
                return "订单金额超过商户设置的限额";
            case "ACQ.TRADE_NOT_EXIS":
                return "请求的交易不存在";
            case "ACQ.ACCOUNT_RISK":
                return "账户存在风险";
            case "ACQ.PAYER_STATUS_ABNORMAL":
                return "账户状态异常";
            case "ACQ.BIZ_SCENE_NOT_ALLOWED":
                return "当前业务场景不支持该操作";
            case "ACQ.PRODUCT_NOT_ALLOWED":
                return "商户未开通该产品权限（如未申请 “单笔转账” 功能）";
            case "ACQ.FREQUENCY_LIMIT":
                return "交易频率超限（短时间内多次调用，触发风控限制）";
            default:
        }
        return "支付宝请求错误";
    }

    public R secondClient(String imageUrl, String ocrType, String userName, String idCard) {
        try {
            R r = this.ocrRequestUrl(imageUrl, ocrType);
            r.getCode();
            if(200 == r.getCode()) {
                if(!JSONObject.parseObject(r.getData().toString()).containsKey("face")) {
                    return R.fail("OCR识别异常:请上传身份证正面照片");
                }
                JSONObject jsonObject = JSONObject.parseObject(r.getData().toString()).getJSONObject("face").getJSONObject("data");
                String name = jsonObject.getString("name");
                String idCardNo = jsonObject.getString("idNumber");
                if(userName.equals(name) && idCard.equals(idCardNo)) {
                    return R.success("验证成功");
                } else {
                    return R.fail("委托人姓名或身份证号错误");
                }
            }
        } catch (IllegalArgumentException e) {
            // 7. 细化异常类型（JSON 解析失败，比如数据格式不匹配）
            log.error("OCR 结果解析失败（数据格式异常）：{}", e.getMessage(), e);
            return R.fail("OCR识别异常：返回数据格式错误");
        } catch (Exception e) {
            // 8. 兜底异常（记录详细日志，便于排查）
            log.error("委托人身份验证未知异常：{}", e.getMessage(), e);
            return R.fail("委托人身份验证未知异常："+e.getMessage());
        }
        return R.fail("OCR识别异常");
    }
}
