//package com.mcwl.web.controller.pay.AliPay;
//
//import cn.hutool.core.bean.BeanUtil;
//import cn.hutool.core.lang.UUID;
//import cn.hutool.json.JSONUtil;
//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.diagnosis.DiagnosisUtils;
//import com.alipay.api.domain.AlipayFundAccountQueryModel;
//import com.alipay.api.domain.AlipayFundTransUniTransferModel;
//import com.alipay.api.domain.Participant;
//import com.alipay.api.request.AlipayFundAccountQueryRequest;
//import com.alipay.api.request.AlipayFundTransUniTransferRequest;
//import com.alipay.api.request.AlipaySystemOauthTokenRequest;
//import com.alipay.api.request.AlipayUserInfoAuthRequest;
//import com.alipay.api.response.AlipayFundAccountQueryResponse;
//import com.alipay.api.response.AlipayFundTransUniTransferResponse;
//import com.alipay.easysdk.base.oauth.models.AlipaySystemOauthTokenResponse;
//import com.alipay.easysdk.factory.Factory;
//import com.alipay.easysdk.kernel.Config;
//import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
//import com.mcwl.common.core.redis.RedisCache;
//import com.mcwl.common.exception.ServiceException;
//import com.mcwl.common.utils.SecurityUtils;
//import com.mcwl.memberCenter.domain.MemberLevel;
//import com.mcwl.memberCenter.service.MemberLevelService;
//import com.mcwl.pay.config.AliConfig;
//import com.mcwl.pay.domain.OrderTrade;
//import com.mcwl.pay.domain.OrderTradeDto;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.util.Optional;
//import java.util.concurrent.TimeUnit;
//
///**
// * 支付宝支付
// */
//@Component
//@Slf4j
//public class AliPayIntegration {
//
//    @Autowired
//    private RedisCache redisCache;
//
//
//    @Autowired
//    private MemberLevelService memberLevelService;
//
//
//    @Autowired
//    private AliConfig aliConfig;
//
//
//    public AliPayIntegration(Config config) {
//        Factory.setOptions(config);
//    }
//
//
//    /**
//     * 调用支付宝预下订单接口
//     *
//     * @param orderTradeDto 订单实体
//     * @return 二维码url
//     * @throws Exception
//     */
////    public String orderPay(OrderTradeDto orderTradeDto) throws Exception {
////        Integer productId = orderTradeDto.getProductId();
////        if (!Optional.ofNullable(productId).isPresent()) {
////            throw new ServiceException("mallProductId不能为空");
////        }
////
////        MallProduct mallProduct = mallProductService.getById(productId);
////        if (!Optional.ofNullable(mallProduct).isPresent()) {
////            throw new ServiceException("mallProduct不存在");
////        }
////
////        // 设置orderTrade信息
////        OrderTrade tradeEntity = new OrderTrade();
////        BeanUtil.copyProperties(orderTradeDto, tradeEntity);
////        tradeEntity.setCode(UUID.randomUUID().toString(true).substring(0, 30));
////        tradeEntity.setUserId(SecurityUtils.getUserId());
////        tradeEntity.setUserName(SecurityUtils.getUsername());
////        tradeEntity.setProductName(mallProduct.getProductName());
////
////        //调用支付宝的接口
////        AlipayTradePrecreateResponse payResponse = Factory.Payment.FaceToFace()
////                .preCreate(mallProduct.getProductName(),
////                        tradeEntity.getCode() + "_product",
////                        orderTradeDto.getPaymentAmount().toString());
////        // 缓存到redis
////        redisCache.setCacheObject(tradeEntity.getCode() + "_product", JSONUtil.toJsonStr(tradeEntity), 3, TimeUnit.MINUTES);
//////        AlipayTradePrecreateResponse payResponse = Factory.Payment.FaceToFace().preCreate("订单主题：Mac笔记本", "LS123qwe123", "19999");
////        //参照官方文档响应示例，解析返回结果
////        String httpBodyStr = payResponse.getHttpBody();
////        JSONObject jsonObject = JSONObject.parseObject(httpBodyStr);
////        return jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
////    }
//
//
//    /**
//     * 调用支付宝预下订单接口
//     *
//     * @param orderTradeDto 订单实体
//     * @return 二维码url
//     * @throws Exception
//     */
//    public String memberPay(OrderTradeDto orderTradeDto) throws Exception {
//
//        // 会员等级id
//        Integer productId = orderTradeDto.getProductId();
//
//        if (!Optional.ofNullable(productId).isPresent()) {
//            throw new ServiceException("memberLevelId不能为空");
//        }
//
//        MemberLevel memberLevel = memberLevelService.getById(productId);
//
//        if (!Optional.ofNullable(memberLevel).isPresent()) {
//            throw new ServiceException("memberLevel不存在");
//        }
//
//        // 设置orderTrade信息
//        OrderTrade tradeEntity = new OrderTrade();
//        BeanUtil.copyProperties(orderTradeDto, tradeEntity);
//        tradeEntity.setCode(UUID.randomUUID().toString(true).substring(0, 30));
//        tradeEntity.setUserId(SecurityUtils.getUserId());
//        tradeEntity.setUserName(SecurityUtils.getUsername());
//        tradeEntity.setProductName(memberLevel.getMemberName());
//
//        //调用支付宝的接口
//        AlipayTradePrecreateResponse payResponse = Factory.Payment.FaceToFace()
//                // 设置过期时
//                .preCreate(memberLevel.getMemberName(),
//                        tradeEntity.getCode() + "_member",
//                        orderTradeDto.getPaymentAmount().toString());
//        // 缓存到redis
//        redisCache.setCacheObject(tradeEntity.getCode() + "_member", JSONUtil.toJsonStr(tradeEntity), 3, TimeUnit.MINUTES);
//        redisCache.setCacheObject(tradeEntity.getCode() + "_member" + "_promotionId", orderTradeDto.getPromotionId(), 3, TimeUnit.MINUTES);
////        AlipayTradePrecreateResponse payResponse = Factory.Payment.FaceToFace().preCreate("订单主题：Mac笔记本", "LS123qwe123", "19999");
//        //参照官方文档响应示例，解析返回结果
//        String httpBodyStr = payResponse.getHttpBody();
//        JSONObject jsonObject = JSONObject.parseObject(httpBodyStr);
//        return jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
//    }
//
//
//    /**
//     * 调用支付宝预下订单接口
//     *
//     * @param paymentAmount 充值金额
//     * @return 二维码url
//     * @throws Exception
//     */
//    public String pointsPay(Double paymentAmount) throws Exception {
//        // 设置orderTrade信息
//        OrderTrade tradeEntity = new OrderTrade();
//        tradeEntity.setCode(UUID.randomUUID().toString(true).substring(0, 30));
//        tradeEntity.setUserId(SecurityUtils.getUserId());
//        tradeEntity.setProductId(-1);
//        tradeEntity.setProductName("积分充值");
//        tradeEntity.setUserName(SecurityUtils.getUsername());
//        tradeEntity.setPaymentAmount(paymentAmount.intValue());
//
//        //调用支付宝的接口
//        AlipayTradePrecreateResponse payResponse = Factory.Payment.FaceToFace()
//                .preCreate(tradeEntity.getProductName(),
//                        tradeEntity.getCode() + "_points",
//                        tradeEntity.getPaymentAmount().toString());
//        // 缓存到redis
//        redisCache.setCacheObject(tradeEntity.getCode() + "_points", JSONUtil.toJsonStr(tradeEntity), 3, TimeUnit.MINUTES);
//        //参照官方文档响应示例，解析返回结果
//        String httpBodyStr = payResponse.getHttpBody();
//        JSONObject jsonObject = JSONObject.parseObject(httpBodyStr);
//        return jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
//    }
//
//    /**
//     * 支付宝转账方法
//     * @param outBizNo 外部业务单号
//     * @param payerUserId 付款方用户ID
//     * @param payeeUserId 收款方用户ID
//     * @param amount 转账金额
//     * @return 返回支付宝转账响应的内容
//     */
//    public String transfer(String outBizNo, String payerUserId, String payeeUserId, String amount) throws AlipayApiException {
//
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
//
//        // 构造请求参数以调用接口
//        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
//        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
//
//        // 设置商家侧唯一订单号
//        model.setOutBizNo(outBizNo);
//
//        // 设置订单总金额
//        model.setTransAmount(amount);
//
//        // 设置描述特定的业务场景
//        model.setBizScene("DIRECT_TRANSFER");
//
//        // 设置业务产品码
//        model.setProductCode("TRANS_ACCOUNT_NO_PWD");
//
//        // 设置转账业务的标题
//        model.setOrderTitle("测试");
//
//        // 设置收款方信息
//        Participant payeeInfo = new Participant();
//        payeeInfo.setCertType("IDENTITY_CARD");
//        payeeInfo.setCertNo("1201152******72917");
//        payeeInfo.setIdentity("2088123412341234");
//        payeeInfo.setName("黄龙国际有限公司");
//        payeeInfo.setIdentityType("ALIPAY_USER_ID");
//        model.setPayeeInfo(payeeInfo);
//
//        // 设置业务备注
//        model.setRemark("201905代发");
//
//        // 设置转账业务请求的扩展参数
//        model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
//
//        request.setBizModel(model);
//        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
//        System.out.println(response.getBody());
//
//        if (response.isSuccess()) {
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
//             String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
//             System.out.println(diagnosisUrl);
//        }
//        return response.getBody();
//    }
//
//    /**
//     * 查看余额
//     */
//    public void balance() throws Exception {
//
//        AlipaySystemOauthTokenResponse token = Factory.Base.OAuth().getToken("code");
//
//
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
//
//        // 构造请求参数以调用接口
//        AlipayFundAccountQueryRequest request = new AlipayFundAccountQueryRequest();
//        AlipayFundAccountQueryModel model = new AlipayFundAccountQueryModel();
//
//        // uid参数未来计划废弃，存量商户可继续使用，新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
//        // model.setAlipayUserId("2088301409188095");
//
//        // 设置支付宝openId
//        model.setAlipayOpenId("061P6NAblcWDWJoDRxSVvOYz-ufp-3wQaA4E_szQyMFTXse");
//
//        // 设置查询的账号类型
//        model.setAccountType("ACCTRANS_ACCOUNT");
//
//        request.setBizModel(model);
//        AlipayFundAccountQueryResponse response = alipayClient.execute(request);
//        System.out.println(response.getBody());
//
//        if (response.isSuccess()) {
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
//            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
//            // System.out.println(diagnosisUrl);
//        }
//    }
//
//    private AlipayConfig getAlipayConfig() {
//        String privateKey  = aliConfig.getPrivateKey();
//        String alipayPublicKey = aliConfig.getPublicKey();
//        AlipayConfig alipayConfig = new AlipayConfig();
//        alipayConfig.setServerUrl(aliConfig.getGatewayUrl());
//        alipayConfig.setAppId(aliConfig.getAppId());
//        alipayConfig.setPrivateKey(privateKey);
//        alipayConfig.setFormat("json");
//        alipayConfig.setAlipayPublicKey(alipayPublicKey);
//        alipayConfig.setCharset("UTF-8");
//        alipayConfig.setSignType("RSA2");
//        return alipayConfig;
//    }
//
//    //TODO 绑定回调，获取openId，保存到数据库
//    public void bindingCallback(String authCode) {
//        try {
//            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
//            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
//            request.setCode(authCode);
//            request.setGrantType("authorization_code");
//            com.alipay.api.response.AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
//            if (response.isSuccess()) {
//                String openId = response.getOpenId(); // 支付宝用户唯一ID
//                // 将openId与当前商城用户绑定（保存到数据库）
//                System.out.println("绑定成功！openId：" + openId);
//            } else {
//                System.out.println("绑定失败：" + response.getSubMsg());
//            }
//
//        } catch (AlipayApiException e) {
//            throw new RuntimeException(e);
//        }
//    }
//}
