package com.jeequan.jeepay.pay.ctrl.test;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.jeequan.jeepay.components.mq.model.PayOrderDivisionMQ;
import com.jeequan.jeepay.components.mq.model.PushWxMpMsgMQ;
import com.jeequan.jeepay.components.mq.model.ZftSettOrderMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.components.oss.ctrl.OssFileController;
import com.jeequan.jeepay.components.oss.model.MockMultipartFile;
import com.jeequan.jeepay.components.oss.model.OssFileConfig;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.IPayOrderQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.ITransferService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.openapi.biz.transfer.TransferOrderParam;
import com.jeequan.jeepay.core.model.params.alipay.AlipayIsvParams;
import com.jeequan.jeepay.core.model.params.lklspay.LklspayIsvParams;
import com.jeequan.jeepay.core.model.params.yspay.YspayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.service.ISysConfigService;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.pay.service.PayOrderDivisionProcessService;
import com.jeequan.jeepay.pay.service.StatisticsService;
import com.jeequan.jeepay.pay.service.payorderpush.impl.PushWxMpTemplateMsgService;
import com.jeequan.jeepay.service.impl.*;
import com.jeequan.jeepay.thirdparty.channel.lklspay.LklspayKit;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklPayMethod;
import com.jeequan.jeepay.thirdparty.channel.yspay.model.ReqMethod;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.YspayKit;
import com.jeequan.jeepay.thirdparty.device.speaker.lklsSpeaker.LklsSpeakerService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @author crystal
 * @date 2023/12/25 17:12
 */
@RequestMapping(value = "test")
@RestController
@Slf4j
public class TestController {

    @Autowired
    private ConfigContextQueryService queryService;

    @Autowired private PayOrderDivisionProcessService payOrderDivisionProcessService;

    @Autowired
    private TransferOrderService transferOrderService;

    @Autowired
    private StatisticsService statisticsService;

    @Autowired
    private MchStoreDeviceService mchStoreDeviceService;

    @Autowired
    private PushWxMpTemplateMsgService pushWxMpTemplateMsgService;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired private IConfigContextQueryService configContextQueryService;

    @Autowired
    private MchApplymentService mchApplymentService;

    @Autowired
    private LklsSpeakerService lklsSpeakerService;

    @Autowired
    private MchInfoConverter mchInfoConverter;

    @Autowired
    private DeviceProvideConfigService deviceProvideConfigService;

    @Autowired
    private OssFileController ossFileController;

    @Autowired private IMQSender mqSender;


    @RequestMapping("/lkl/bind")
    public void bind(){
        JSONObject request = new JSONObject();
        request.put("ver","1.0.0");
        request.put("reqId", SeqKit.genMhoOrderId());
        request.put("timestamp", DateUtil.format(new DateTime(), DatePattern.PURE_DATETIME_PATTERN));
        JSONObject reqData = new JSONObject();
        reqData.put("merId","8225210899900DS");
        reqData.put("termId","D4039820");
        reqData.put("sn","QR939200003565");
        reqData.put("businessType","1");
        reqData.put("shopName","测试门店");
        reqData.put("source","LOAP");
        reqData.put("merOrgNo","967080");
        request.put("reqData",reqData);
        String isvNo = "V1698312342";
        String ifCode = CS.IF_CODE.LKLSPAY;
        LklspayIsvParams isvParams = (LklspayIsvParams)queryService.queryIsvParams(isvNo, ifCode);
        JSONObject jsonObject = LklspayKit.reqApi(LklPayMethod.Api.DEVICE_SPEAKER_BOX_ACTIVATE_URL, isvParams, JSON.toJSONString(request));
        log.info("接口响应参数:{}",jsonObject);
    }

    @RequestMapping("/lkl/unBind")
    public void unBind(){
        JSONObject request = new JSONObject();
        request.put("ver","1.0.0");
        request.put("reqId", SeqKit.genMhoOrderId());
        request.put("timestamp", DateUtil.format(new DateTime(), DatePattern.PURE_DATETIME_PATTERN));
        JSONObject reqData = new JSONObject();
        reqData.put("merId","8225210899900DS");
        reqData.put("termId","D4039820");
        reqData.put("sn","QR939200003565");
        reqData.put("source","KSAAS");
        request.put("reqData",reqData);
        String isvNo = "V1698312342";
        String ifCode = CS.IF_CODE.LKLSPAY;
        LklspayIsvParams isvParams = (LklspayIsvParams)queryService.queryIsvParams(isvNo, ifCode);
        JSONObject jsonObject = LklspayKit.reqApi(LklPayMethod.Api.DEVICE_SPEAKER_BOX_DEACTIVATE_URL, isvParams, JSON.toJSONString(request));
        log.info("接口响应参数:{}",jsonObject);
    }

    @RequestMapping("/lkl/queryStatus")
    public void queryStatus(){
        JSONObject request = new JSONObject();
        request.put("ver","1.0.0");
        request.put("reqId", SeqKit.genMhoOrderId());
        request.put("timestamp", DateUtil.format(new DateTime(), DatePattern.PURE_DATETIME_PATTERN));
        JSONObject reqData = new JSONObject();
        reqData.put("merId","8225210899900DS");
        reqData.put("termId","D4039820");
        reqData.put("sn","QR939200003565");
        request.put("reqData",reqData);
        String isvNo = "V1698312342";
        String ifCode = CS.IF_CODE.LKLSPAY;
        LklspayIsvParams isvParams = (LklspayIsvParams)queryService.queryIsvParams(isvNo, ifCode);
        JSONObject jsonObject = LklspayKit.reqApi(LklPayMethod.Api.DEVICE_SPEAKER_BOX_ACTIVATE_STATUS_QUERY_URL, isvParams, JSON.toJSONString(request));
        log.info("接口响应参数:{}",jsonObject);
    }

    @RequestMapping("/lkl/pushQrcode")
    public void pushQrCode(){
        JSONObject request = new JSONObject();
        request.put("ver","1.0.0");
        request.put("reqId", SeqKit.genMhoOrderId());
        request.put("timestamp", DateUtil.format(new DateTime(), DatePattern.PURE_DATETIME_PATTERN));
        JSONObject reqData = new JSONObject();
        reqData.put("merId","8225210899900DS");
        reqData.put("termId","D4039820");
        reqData.put("deviceSn","QR939200003565");
        reqData.put("qrcode","https://www.baidu.com");
        reqData.put("expireTime","60");
        reqData.put("ts",System.currentTimeMillis() + "");
        reqData.put("nonce",SeqKit.genTransferId());
        request.put("reqData",reqData);
        String isvNo = "V1698312342";
        String ifCode = CS.IF_CODE.LKLSPAY;
        LklspayIsvParams isvParams = (LklspayIsvParams)queryService.queryIsvParams(isvNo, ifCode);
        JSONObject jsonObject = LklspayKit.reqApi(LklPayMethod.Api.DEVICE_SPEAKER_BOX_PUSH_QRCODE_URL, isvParams, JSON.toJSONString(request));
        log.info("接口响应参数:{}",jsonObject);
    }

    @RequestMapping("/lkl/getActiveSn")
    public void getActiveSn(){
        JSONObject request = new JSONObject();
        request.put("ver","1.0.0");
        request.put("reqId", SeqKit.genMhoOrderId());
        request.put("timestamp", DateUtil.format(new DateTime(), DatePattern.PURE_DATETIME_PATTERN));
        JSONObject reqData = new JSONObject();
        reqData.put("merId","8225210899900DS");
        reqData.put("termId","D4039820");
        reqData.put("source","TKSAAS");
        reqData.put("ts",System.currentTimeMillis() + "");
        reqData.put("nonce",SeqKit.genTransferId());
        request.put("reqData",reqData);
        String isvNo = "V1698312342";
        String ifCode = CS.IF_CODE.LKLSPAY;
        LklspayIsvParams isvParams = (LklspayIsvParams)queryService.queryIsvParams(isvNo, ifCode);
        JSONObject jsonObject = LklspayKit.reqApi(LklPayMethod.Api.DEVICE_SPEAKER_BOX_QUERY_SN_URL, isvParams, JSON.toJSONString(request));
        log.info("接口响应参数:{}",jsonObject);
    }

    /**
     * 分账test
     */
    @RequestMapping("/division/{payOrderId}")
    public void divisionTest(@PathVariable("payOrderId") String payOrderId){
        payOrderDivisionProcessService.processPayOrderDivision(payOrderId,(byte)1,null,false,false);
    }

    @RequestMapping("/state/count")
    public void stateCount(){
        String begin = "2024-01-29 00:00:00";
        String end = "2024-01-29 23:59:59";
        DateTime startDate = DateUtil.parse(begin, DatePattern.NORM_DATETIME_PATTERN);
        DateTime endDate = DateUtil.parse(end, DatePattern.NORM_DATETIME_PATTERN);
        statisticsService.doStats(startDate,endDate);
    }


    @RequestMapping("/transfer/{transferId}")
    public String transfer(@PathVariable("transferId") String transferId){
        ITransferService transferService = SpringBeansUtil.getBean("sybpayTransferService", ITransferService.class);
        if(transferService == null){
            throw new BizException("无此转账通道接口");
        }
        TransferOrderParam rq = new TransferOrderParam();
        TransferOrderEntity transferOrder = transferOrderService.getById(transferId);
        transferService.preCheck(rq,transferOrder);
        try {
            ChannelRetMsg transfer = transferService.transfer(rq, transferOrder);
            return JSON.toJSONString(transfer);
        }catch (Exception e){
            e.printStackTrace();
            return "错误请求";
        }
    }

    @RequestMapping("/device/lkl/{startSn}/{endSn}")
    public String deviceInto(@PathVariable("startSn") String startSn,@PathVariable("endSn") String endSn){
        Long start = Long.valueOf(startSn.replace("QR", ""));
        Long end = Long.valueOf(endSn.replace("QR", ""));
        String batch_id = DateUtil.format(new DateTime(),DatePattern.PURE_DATE_PATTERN);
        List<MchStoreDevice> list = new ArrayList<>();
        for (long i = start; i <= end ; i++) {
            MchStoreDevice mchStoreDevice = new MchStoreDevice();
            mchStoreDevice.setDeviceName(RandomUtil.randomNumbers(4));
            mchStoreDevice.setBatchId(batch_id);
            mchStoreDevice.setDeviceType((byte)1);
            mchStoreDevice.setProvider("lkls");
            mchStoreDevice.setDeviceNo("QR"+ i);
            JSONObject deviceParams = new JSONObject();
            deviceParams.put("deviceNo","QR" + i);
            mchStoreDevice.setDeviceParams(deviceParams.toJSONString());
            list.add(mchStoreDevice);
        }
        mchStoreDeviceService.saveBatch(list);
        return "SUCCESS";
    }


    @RequestMapping("/send/order/msg/{orderNo}")
    public String sendOrderMsg(@PathVariable("orderNo") String orderNo){
        pushWxMpTemplateMsgService.send(orderNo, PushWxMpMsgMQ.ROUTE_NOTICE);
        return "SUCCESS";
    }

    @RequestMapping("/send/zft/msg/{settleNo}")
    public String sendZftSettleMsg(@PathVariable("settleNo") String settleNo){
        mqSender.send(ZftSettOrderMQ.build(settleNo));
        return "SUCCESS";
    }

    @RequestMapping("/send/division/msg/{payOrderId}")
    public String sendDivisionMsg(@PathVariable("payOrderId") String payOrderId){
        mqSender.send(PayOrderDivisionMQ.build(payOrderId, CS.YES, null, false, false), 3); //xx s后执行
        return "SUCCESS";
    }


    @RequestMapping("/statistics")
    public String statistics(){
        DateTime now = DateUtil.date();
        DateTime yesterday = DateUtil.offsetDay(now, -1);

        Date beginDate = DateUtil.beginOfDay(yesterday);
        Date endDate = DateUtil.endOfDay(yesterday);
        log.info("【处理数据统计任务】统计日期: {}", DateUtil.formatDate(beginDate));
        statisticsService.doStats(beginDate, endDate);
        return "SUCCESS";
    }

    @RequestMapping("/genTk")
    public String genTk(){
        ISysConfigService sysService = SpringBeansUtil.getBean("sysConfigService", ISysConfigService.class);
        return sysService.genQrToken((byte)1,"123123",1L);
    }

    @RequestMapping("/tradeQuery/{orderId}")
    public String tradeQuery(@PathVariable("orderId") String payOrderId){
        IPayOrderQueryService queryService = SpringBeansUtil.getBean("yspayPayOrderQueryService", IPayOrderQueryService.class);
        if(queryService == null){
            throw new BizException("无此支付通道接口");
        }
        PayOrder payOrder = payOrderService.getById(payOrderId);
        //查询出商户应用的配置信息
        MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfoV2(payOrder.getMchNo(), payOrder.getAppId(),payOrder.getMchExtNo());
        try {
            ChannelRetMsg query = queryService.query(payOrder,mchAppConfigContext);
            return JSON.toJSONString(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("/div/query/{orderId}")
    public String divQuery(@PathVariable("orderId") String payOrderId){
        PayOrder payOrder = payOrderService.getById(payOrderId);
        JSONObject bizData = new JSONObject();
        bizData.put("mercId",payOrder.getChannelMchNo());
        bizData.put("orderId",payOrderId);
        MchApplyment applyment = mchApplymentService.getById(payOrder.getMchExtNo());
        YspayIsvParams yspayIsvParams = configContextQueryService.queryIsvParams(mchInfoConverter.toModel(applyment));
        try {
            JSONObject result = YspayKit.reqV3(ReqMethod.Method.QUERY_D0_DIVISION_SETTLE,yspayIsvParams, bizData);
            log.info("返回结果：{}",result);
            return result.toJSONString();
        }catch (BizException e){
            e.printStackTrace();
        }
       return "ERROR";
    }

    @RequestMapping("/get/box/market/{sn}")
    public String getBoxMarket(@PathVariable("sn") String sn){
        MchStoreDevice device = mchStoreDeviceService.getDeviceInfo(sn, (byte) 1, "lkls");
        DeviceProvideConfig provideConfig = deviceProvideConfigService.getById(device.getConfigId());
        JSONObject deviceParams = new JSONObject();
        deviceParams.put("deviceParams", device.getDeviceParams());
        deviceParams.put("bizConfigParams", device.getBizConfigParams());
        deviceParams.put("providerParams", provideConfig.getProviderParams());
        JSONObject resp = lklsSpeakerService.getMarketAreaAdvert(deviceParams);
        return resp.toString();
    }

    @RequestMapping("/set/box/market/{sn}")
    public String setBoxMarket(@PathVariable("sn") String sn){
        MchStoreDevice device = mchStoreDeviceService.getDeviceInfo(sn, (byte) 1, "lkls");
        DeviceProvideConfig provideConfig = deviceProvideConfigService.getById(device.getConfigId());
        JSONObject deviceParams = new JSONObject();
        deviceParams.put("deviceParams", device.getDeviceParams());
        deviceParams.put("bizConfigParams", device.getBizConfigParams());
        deviceParams.put("providerParams", provideConfig.getProviderParams());
        JSONObject reqData = new JSONObject();
        reqData.put("translsNo",SeqKit.genFlowNo("F"));
        reqData.put("devSn",device.getDeviceNo());


        ArrayList markPicVos = new ArrayList();
        String url1 = "https://syb-jq-public.oss-cn-hangzhou.aliyuncs.com/notice/069507a2-e4a0-4a64-9122-0f40727aa60d.jpg";
        String url2 = "https://syb-jq-public.oss-cn-hangzhou.aliyuncs.com/notice/c55f884e-ad79-4daf-b710-6edef4c658b3.jpg";
        JSONObject item1 = new JSONObject();
        item1.put("displayTime",5);
        item1.put("enable",1);
        item1.put("picName",url1);
        item1.put("picSize",71693L);
        item1.put("picWidth",800);
        item1.put("picHeight",960);

        JSONObject item2 = new JSONObject();
        item2.put("displayTime",5);
        item2.put("enable",1);
        item2.put("picName",url2);
        item2.put("picSize",87993L);
        item2.put("picWidth",800);
        item2.put("picHeight",960);
        markPicVos.add(item1);
        markPicVos.add(item2);
        reqData.put("markPicVos",markPicVos);
        JSONObject result = lklsSpeakerService.setMarketAreaAdvert(deviceParams,reqData);
        return result.toString();
    }

    /**
     * 设置跑马灯
     * @param sn
     * @return
     */
    @RequestMapping("/set/box/marquee/{sn}")
    public String setBoxMarquee(@PathVariable("sn") String sn){
        MchStoreDevice device = mchStoreDeviceService.getDeviceInfo(sn, (byte) 1, "lkls");
        DeviceProvideConfig provideConfig = deviceProvideConfigService.getById(device.getConfigId());
        JSONObject deviceParams = new JSONObject();
        deviceParams.put("deviceParams", device.getDeviceParams());
        deviceParams.put("bizConfigParams", device.getBizConfigParams());
        deviceParams.put("providerParams", provideConfig.getProviderParams());
        JSONObject bizData = new JSONObject();
        bizData.put("translsNo",SeqKit.genFlowNo("F"));
        bizData.put("devSn",device.getDeviceNo());
        JSONObject marqueeVo = new JSONObject();
        marqueeVo.put("inputText","快来玩啊小哥哥");
        marqueeVo.put("fontSize",20);
        marqueeVo.put("fontColor","#FFFFFF");
        marqueeVo.put("bgColor","#409EFF");
        marqueeVo.put("displayAreX",0);
        marqueeVo.put("displayAreY",300);
        marqueeVo.put("picWidth",840);
        marqueeVo.put("picHeight",40);
        bizData.put("marqueeVo",marqueeVo);
        JSONObject result = lklsSpeakerService.setMarqueeInfo(deviceParams,bizData);
        return result.toString();
    }

    @RequestMapping("/set/split/image")
    public String setBoxMarquee(){
        // 源图片路径
        String sourceImagePath = "D:\\pic\\pic1.jpg";
        // 目标图片路径
        String targetImagePath = "D:\\pic\\223.jpg";
        // 目标宽度
        int targetWidth = 800;
        // 目标高度
        int targetHeight = 960;
        // 读取源图片
        BufferedImage image = ImgUtil.read(FileUtil.file(sourceImagePath));
        // 缩放图片
        Image scaledImage = ImgUtil.scale(image, targetWidth, targetHeight);
        // 将Image对象转换为BufferedImage
        BufferedImage bufferedImage = ImgUtil.castToBufferedImage(scaledImage,ImgUtil.IMAGE_TYPE_JPG);
        // 将BufferedImage转换为字节数组
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", os);
            ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray());
            String url = ossFileController.singleFileUpload(new MockMultipartFile(UUID.fastUUID() + ".jpg", 1L, bis), OssFileConfig.BIZ_TYPE.MATERIAL);
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/set/aliapy/plym")
    public String alipayPlym(){
        String domain = "https://openapi.alipay.com/gateway.do";
        String path = "D:\\crystal\\cert\\2021004143669573\\";
        String alipayPublicCert = path + "alipayCertPublicKey_RSA2.crt";
        String alipayRootCert = path +"alipayRootCert.crt";
        String appPublicCert = path +"appCertPublicKey_2021004143669573.crt";
        String appid = "2021004143669573";
        String prikey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCPENaSv1YzGidYZF5wGbmwShV6SjwFgq3WSIgIFa9Ctaq/x4BmBFtf6pwAWnkYyVzRfUonh+leWD3ufT2fB6zRZkEPLY9zxUGDLCXR6r8+RhIZ0V9jKaVo2VP+j4XFn68mgUu07H1G4P8DsSper2DJ9FwDlxw96Vy8yOnvu31XYkEfh150PuU7PsiQlKHmskhU0+6aQnmmXZU6rPT9HHK8JDofUkotG5lRpe3sTk7tt5jK+PeXxAOK5SKImuO3kywsm5lUwzKSNEZfM6kVaHzsUojLL1FH1T7pACwuu7ot35GjopB8XhBza515zbOXiwzmOa0HFDXWVkvMGih3Ou2VAgMBAAECggEAP0GRrkbdZTDuLp4KR4SIXtMS1gRWr5UNKc7eHrz/xf4vJiaetfy9Lha8rUdTfcsiuBmunPXyEF3x3C4R/evV1KxincRmRij0g3wUqNEjh/RRcorpox253jchdU+eNTgaqGrIv5FE/v7ioo5GDqF6qTDbMlcxDIrPD0XCcdYzYFwOvx9d7DNymiM2XqvDww9KRs3H0XQvRMBY3lOYG1Bj9nEHaN//lVVsY0470e2wEJUKfofo8GuL+EcarJJ9C5OsKKYfwOjqNopB4RtFEI197qDVtaGtG5F4gtx/bu+2lLcULAMMpf59r3S7pVd5koQhSIDpxdQNi4eP5q+mUr6UIQKBgQDJKnkP+ojvILxaN+DqUE7TFjYCYIndJV0MMndoZF7yxv8snakhXIwbbvlfn/cNlAqtcQSM4BFtwv/A2mY0y31dO/GuymXB+Cm8vehx5MCyX7ioESFbGfIzmvNXah1fh5EgEvhM6zdqFWdKG2az3RX6FCUa+Hh+1FDCbFVEjibM/QKBgQC2EBa3eDSkbnCUp4Fh9I5UTLCce3xe5p74KlDBhEQecV42wYyIA2mROg0wAVJjMXfidW+DkP0sDw7aAG2LzdsPhub+t+kGfEOxmDOicY7q5EBKxep+OJJW5kmp3Qk9QM8MvnGp6BLEGt7Ln+RhV4MzqXvRZ0PTNivZM4eIsJdSeQKBgQCpbJghmQQTQiLgaQeI0LJSnfZG8j+qfXlseGSRC1fcaTUownBbpLJruH9WxkcwrGqBwRnv/BcxtnXoWwiRloCzMXVPnS8uum+MgvVuVxbkJDJFeof5TlTqmaoxCTJL7sWPmep9/ezh77zacVGCUsXbpXPKz1HMn8yUsuDtqDuNkQKBgFvbnjqPcbAM8Mxv/z2XEEDEOM+bFlMjdM2tO/WHcH8Tn/9shCUT462cZo7z+8eEbAJcUhlFjBcwucOQN7Uz9fTNkbquu+nDxLvUGSk6tmsZIr8XQIrSrDMgGcaUeVboXg8F/39EUkOTcxm14JqkdtQYDRrISVZFnLYH47g5sP+xAoGAD6EP/TyOHabSIxWqc/RbTs9xAgeMzC9r+Cra+QOaHmWCwNKXEeyDVATl8z8OJpurUn7X3T3YgCknS0tAmdc9MHs5SRiqW98qUtPNYHKzpHah/10YSGkfCzEqDfPrujXM6e2HdoWNFEi+NwqP9BwC834ad6Y5/xEEw8TA5EtcPyo=";
        AlipayConfig config = new AlipayConfig();
        config.setServerUrl(domain);
        config.setRootCertPath(alipayRootCert);
        config.setAppId(appid);
        config.setPrivateKey(prikey);
        config.setAlipayPublicCertPath(alipayPublicCert);
        config.setAppCertPath(appPublicCert);
        config.setFormat("json");
        config.setCharset("GBK");
        config.setSignType("RSA2");
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(config);
            AlipayFundAuthorizeUniApplyRequest request = new AlipayFundAuthorizeUniApplyRequest();
            AlipayFundAuthorizeUniApplyModel model = new AlipayFundAuthorizeUniApplyModel();
            model.setProductCode("BATCH_API_TO_ACC");
            model.setBizScene("STANDARD_MESSAGE_BATCH_PAY");
            model.setOutBizNo(SeqKit.genFlowNo("AT"));
            model.setAuthorizeLinkType("SHORT_URL");
            AuthParticipantInfo participantInfo = new AuthParticipantInfo();
            participantInfo.setParticipantId("1@shouyinbei.com");
            participantInfo.setParticipantIdType("ALIPAY_LOGON_ID");
            participantInfo.setName("武汉融商创银科技有限公司");
            model.setPrincipalInfo(participantInfo);
            model.setSubBizScene("COMMON");
            model.setChannel("tinyapp");
            model.setApplyExpireTime("2024-05-22 22:00");
//            model.setAuthExpireTime("2024-05-22 18:00:00");
            request.setBizModel(model);
            AlipayFundAuthorizeUniApplyResponse response = alipayClient.certificateExecute(request);
            log.info("返回参数：{}",JSON.toJSONString(response));
            log.info("返回参数内容：{}",response.getBody());
        }catch (Exception e){
            e.printStackTrace();
        }
        return "SUCCESS";
    }

    /**
     * 鲍志刚 AT1793199383804825601
     * agreement_no 20245322072022588330
     * @return
     */
    @RequestMapping("/set/aliapy/plym/createOrder")
    public String createOrder(){
        String domain = "https://openapi.alipay.com/gateway.do";
        String path = "D:\\crystal\\cert\\2021004143669573\\";
        String alipayPublicCert = path + "alipayCertPublicKey_RSA2.crt";
        String alipayRootCert = path +"alipayRootCert.crt";
        String appPublicCert = path +"appCertPublicKey_2021004143669573.crt";
        String appid = "2021004143669573";
        String prikey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCPENaSv1YzGidYZF5wGbmwShV6SjwFgq3WSIgIFa9Ctaq/x4BmBFtf6pwAWnkYyVzRfUonh+leWD3ufT2fB6zRZkEPLY9zxUGDLCXR6r8+RhIZ0V9jKaVo2VP+j4XFn68mgUu07H1G4P8DsSper2DJ9FwDlxw96Vy8yOnvu31XYkEfh150PuU7PsiQlKHmskhU0+6aQnmmXZU6rPT9HHK8JDofUkotG5lRpe3sTk7tt5jK+PeXxAOK5SKImuO3kywsm5lUwzKSNEZfM6kVaHzsUojLL1FH1T7pACwuu7ot35GjopB8XhBza515zbOXiwzmOa0HFDXWVkvMGih3Ou2VAgMBAAECggEAP0GRrkbdZTDuLp4KR4SIXtMS1gRWr5UNKc7eHrz/xf4vJiaetfy9Lha8rUdTfcsiuBmunPXyEF3x3C4R/evV1KxincRmRij0g3wUqNEjh/RRcorpox253jchdU+eNTgaqGrIv5FE/v7ioo5GDqF6qTDbMlcxDIrPD0XCcdYzYFwOvx9d7DNymiM2XqvDww9KRs3H0XQvRMBY3lOYG1Bj9nEHaN//lVVsY0470e2wEJUKfofo8GuL+EcarJJ9C5OsKKYfwOjqNopB4RtFEI197qDVtaGtG5F4gtx/bu+2lLcULAMMpf59r3S7pVd5koQhSIDpxdQNi4eP5q+mUr6UIQKBgQDJKnkP+ojvILxaN+DqUE7TFjYCYIndJV0MMndoZF7yxv8snakhXIwbbvlfn/cNlAqtcQSM4BFtwv/A2mY0y31dO/GuymXB+Cm8vehx5MCyX7ioESFbGfIzmvNXah1fh5EgEvhM6zdqFWdKG2az3RX6FCUa+Hh+1FDCbFVEjibM/QKBgQC2EBa3eDSkbnCUp4Fh9I5UTLCce3xe5p74KlDBhEQecV42wYyIA2mROg0wAVJjMXfidW+DkP0sDw7aAG2LzdsPhub+t+kGfEOxmDOicY7q5EBKxep+OJJW5kmp3Qk9QM8MvnGp6BLEGt7Ln+RhV4MzqXvRZ0PTNivZM4eIsJdSeQKBgQCpbJghmQQTQiLgaQeI0LJSnfZG8j+qfXlseGSRC1fcaTUownBbpLJruH9WxkcwrGqBwRnv/BcxtnXoWwiRloCzMXVPnS8uum+MgvVuVxbkJDJFeof5TlTqmaoxCTJL7sWPmep9/ezh77zacVGCUsXbpXPKz1HMn8yUsuDtqDuNkQKBgFvbnjqPcbAM8Mxv/z2XEEDEOM+bFlMjdM2tO/WHcH8Tn/9shCUT462cZo7z+8eEbAJcUhlFjBcwucOQN7Uz9fTNkbquu+nDxLvUGSk6tmsZIr8XQIrSrDMgGcaUeVboXg8F/39EUkOTcxm14JqkdtQYDRrISVZFnLYH47g5sP+xAoGAD6EP/TyOHabSIxWqc/RbTs9xAgeMzC9r+Cra+QOaHmWCwNKXEeyDVATl8z8OJpurUn7X3T3YgCknS0tAmdc9MHs5SRiqW98qUtPNYHKzpHah/10YSGkfCzEqDfPrujXM6e2HdoWNFEi+NwqP9BwC834ad6Y5/xEEw8TA5EtcPyo=";
        AlipayConfig config = new AlipayConfig();
        config.setServerUrl(domain);
        config.setRootCertPath(alipayRootCert);
        config.setAppId(appid);
        config.setPrivateKey(prikey);
        config.setAlipayPublicCertPath(alipayPublicCert);
        config.setAppCertPath(appPublicCert);
        config.setFormat("json");
        config.setCharset("GBK");
        config.setSignType("RSA2");
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(config);
            AlipayFundBatchCreateRequest request = new AlipayFundBatchCreateRequest();
            AlipayFundBatchCreateModel model = new AlipayFundBatchCreateModel();
            model.setOutBatchNo(SeqKit.genFlowNo("OR"));
            model.setTotalTransAmount("1");
            model.setTotalCount("1");
            model.setProductCode("BATCH_API_TO_ACC");
            model.setBizScene("STANDARD_MESSAGE_BATCH_PAY");
            model.setOrderTitle("订单支付");
            model.setTimeExpire("2024-05-23 10:00");
            model.setRemark("测试支付");
//            model.setPassbackParams("");
            TransOrderDetail orderDetail = new TransOrderDetail();
            orderDetail.setOutBizNo(SeqKit.genMhoOrderId());
            orderDetail.setTransAmount("1");
            Participant participant = new Participant();
            participant.setName("刘韵杰");
            participant.setIdentityType("ALIPAY_LOGON_ID");
            participant.setIdentity("17764028120");
            orderDetail.setPayeeInfo(participant);
            List<TransOrderDetail> list = new ArrayList<>(1);
            list.add(orderDetail);
            model.setTransOrderList(list);

            Participant pree = new Participant();
            pree.setIdentity("2088502904759300");
            pree.setIdentityType("ALIPAY_USER_ID");
            JSONObject extJson = new JSONObject();
            extJson.put("agreement_no","20245322072022588330");
            //TODO 个人需要签约协议号 否则无法支付
            pree.setExtInfo(extJson.toString());
            model.setPayerInfo(pree);
            request.setBizModel(model);
            AlipayFundBatchCreateResponse response = alipayClient.certificateExecute(request);
            if(response.isSuccess()){
                return response.getBatchTransId();
            }else{
                return response.getSubMsg();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "SUCCESS";
    }

    @RequestMapping("/set/aliapy/plym/pay/{batchOrderId}")
    public String pay(@PathVariable("batchOrderId") String batchOrderId){
        String domain = "https://openapi.alipay.com/gateway.do";
        String path = "D:\\crystal\\cert\\2021004143669573\\";
        String alipayPublicCert = path + "alipayCertPublicKey_RSA2.crt";
        String alipayRootCert = path +"alipayRootCert.crt";
        String appPublicCert = path +"appCertPublicKey_2021004143669573.crt";
        String appid = "2021004143669573";
        String prikey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCPENaSv1YzGidYZF5wGbmwShV6SjwFgq3WSIgIFa9Ctaq/x4BmBFtf6pwAWnkYyVzRfUonh+leWD3ufT2fB6zRZkEPLY9zxUGDLCXR6r8+RhIZ0V9jKaVo2VP+j4XFn68mgUu07H1G4P8DsSper2DJ9FwDlxw96Vy8yOnvu31XYkEfh150PuU7PsiQlKHmskhU0+6aQnmmXZU6rPT9HHK8JDofUkotG5lRpe3sTk7tt5jK+PeXxAOK5SKImuO3kywsm5lUwzKSNEZfM6kVaHzsUojLL1FH1T7pACwuu7ot35GjopB8XhBza515zbOXiwzmOa0HFDXWVkvMGih3Ou2VAgMBAAECggEAP0GRrkbdZTDuLp4KR4SIXtMS1gRWr5UNKc7eHrz/xf4vJiaetfy9Lha8rUdTfcsiuBmunPXyEF3x3C4R/evV1KxincRmRij0g3wUqNEjh/RRcorpox253jchdU+eNTgaqGrIv5FE/v7ioo5GDqF6qTDbMlcxDIrPD0XCcdYzYFwOvx9d7DNymiM2XqvDww9KRs3H0XQvRMBY3lOYG1Bj9nEHaN//lVVsY0470e2wEJUKfofo8GuL+EcarJJ9C5OsKKYfwOjqNopB4RtFEI197qDVtaGtG5F4gtx/bu+2lLcULAMMpf59r3S7pVd5koQhSIDpxdQNi4eP5q+mUr6UIQKBgQDJKnkP+ojvILxaN+DqUE7TFjYCYIndJV0MMndoZF7yxv8snakhXIwbbvlfn/cNlAqtcQSM4BFtwv/A2mY0y31dO/GuymXB+Cm8vehx5MCyX7ioESFbGfIzmvNXah1fh5EgEvhM6zdqFWdKG2az3RX6FCUa+Hh+1FDCbFVEjibM/QKBgQC2EBa3eDSkbnCUp4Fh9I5UTLCce3xe5p74KlDBhEQecV42wYyIA2mROg0wAVJjMXfidW+DkP0sDw7aAG2LzdsPhub+t+kGfEOxmDOicY7q5EBKxep+OJJW5kmp3Qk9QM8MvnGp6BLEGt7Ln+RhV4MzqXvRZ0PTNivZM4eIsJdSeQKBgQCpbJghmQQTQiLgaQeI0LJSnfZG8j+qfXlseGSRC1fcaTUownBbpLJruH9WxkcwrGqBwRnv/BcxtnXoWwiRloCzMXVPnS8uum+MgvVuVxbkJDJFeof5TlTqmaoxCTJL7sWPmep9/ezh77zacVGCUsXbpXPKz1HMn8yUsuDtqDuNkQKBgFvbnjqPcbAM8Mxv/z2XEEDEOM+bFlMjdM2tO/WHcH8Tn/9shCUT462cZo7z+8eEbAJcUhlFjBcwucOQN7Uz9fTNkbquu+nDxLvUGSk6tmsZIr8XQIrSrDMgGcaUeVboXg8F/39EUkOTcxm14JqkdtQYDRrISVZFnLYH47g5sP+xAoGAD6EP/TyOHabSIxWqc/RbTs9xAgeMzC9r+Cra+QOaHmWCwNKXEeyDVATl8z8OJpurUn7X3T3YgCknS0tAmdc9MHs5SRiqW98qUtPNYHKzpHah/10YSGkfCzEqDfPrujXM6e2HdoWNFEi+NwqP9BwC834ad6Y5/xEEw8TA5EtcPyo=";
        AlipayConfig config = new AlipayConfig();
        config.setServerUrl(domain);
        config.setRootCertPath(alipayRootCert);
        config.setAppId(appid);
        config.setPrivateKey(prikey);
        config.setAlipayPublicCertPath(alipayPublicCert);
        config.setAppCertPath(appPublicCert);
        config.setFormat("json");
        config.setCharset("GBK");
        config.setSignType("RSA2");
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(config);
            AlipayFundBatchAppPayRequest request = new AlipayFundBatchAppPayRequest();
            AlipayFundBatchAppPayModel model = new AlipayFundBatchAppPayModel();
            model.setBatchTransId(batchOrderId);
            request.setBizModel(model);
            AlipayFundBatchAppPayResponse response = alipayClient.pageExecute(request,"get");
            String url = response.getBody();
            String parm = url.replace("https://openapi.alipay.com/gateway.do?","");
            String encodeParm = URLEncoder.encode(parm, "utf-8");
            String pageEncode = URLEncoder.encode("pages/confirm/index/index?signParams=" + encodeParm,"utf-8");
            String payUrl = "alipays://platformapi/startapp?appId=2021002133661287&appClearTop=false&startMultApp=YES"
                    + "&page=" + pageEncode;
            String fullUrl = "https://render.alipay.com/p/s/ulink/?scheme=" + URLEncoder.encode(payUrl, "utf-8");
            log.info("付款url:{}",fullUrl);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "SUCCESS";
    }


//    @RequestMapping("/set/aliapy/plym/createOrder")
//    public String createOrder(){
//        String domain = "https://openapi.alipay.com/gateway.do";
//        String path = "D:\\crystal\\cert\\2021004143669573\\";
//        String alipayPublicCert = path + "alipayCertPublicKey_RSA2.crt";
//        String alipayRootCert = path +"alipayRootCert.crt";
//        String appPublicCert = path +"appCertPublicKey_2021004143669573.crt";
//        String appid = "2021004143669573";
//        String prikey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCPENaSv1YzGidYZF5wGbmwShV6SjwFgq3WSIgIFa9Ctaq/x4BmBFtf6pwAWnkYyVzRfUonh+leWD3ufT2fB6zRZkEPLY9zxUGDLCXR6r8+RhIZ0V9jKaVo2VP+j4XFn68mgUu07H1G4P8DsSper2DJ9FwDlxw96Vy8yOnvu31XYkEfh150PuU7PsiQlKHmskhU0+6aQnmmXZU6rPT9HHK8JDofUkotG5lRpe3sTk7tt5jK+PeXxAOK5SKImuO3kywsm5lUwzKSNEZfM6kVaHzsUojLL1FH1T7pACwuu7ot35GjopB8XhBza515zbOXiwzmOa0HFDXWVkvMGih3Ou2VAgMBAAECggEAP0GRrkbdZTDuLp4KR4SIXtMS1gRWr5UNKc7eHrz/xf4vJiaetfy9Lha8rUdTfcsiuBmunPXyEF3x3C4R/evV1KxincRmRij0g3wUqNEjh/RRcorpox253jchdU+eNTgaqGrIv5FE/v7ioo5GDqF6qTDbMlcxDIrPD0XCcdYzYFwOvx9d7DNymiM2XqvDww9KRs3H0XQvRMBY3lOYG1Bj9nEHaN//lVVsY0470e2wEJUKfofo8GuL+EcarJJ9C5OsKKYfwOjqNopB4RtFEI197qDVtaGtG5F4gtx/bu+2lLcULAMMpf59r3S7pVd5koQhSIDpxdQNi4eP5q+mUr6UIQKBgQDJKnkP+ojvILxaN+DqUE7TFjYCYIndJV0MMndoZF7yxv8snakhXIwbbvlfn/cNlAqtcQSM4BFtwv/A2mY0y31dO/GuymXB+Cm8vehx5MCyX7ioESFbGfIzmvNXah1fh5EgEvhM6zdqFWdKG2az3RX6FCUa+Hh+1FDCbFVEjibM/QKBgQC2EBa3eDSkbnCUp4Fh9I5UTLCce3xe5p74KlDBhEQecV42wYyIA2mROg0wAVJjMXfidW+DkP0sDw7aAG2LzdsPhub+t+kGfEOxmDOicY7q5EBKxep+OJJW5kmp3Qk9QM8MvnGp6BLEGt7Ln+RhV4MzqXvRZ0PTNivZM4eIsJdSeQKBgQCpbJghmQQTQiLgaQeI0LJSnfZG8j+qfXlseGSRC1fcaTUownBbpLJruH9WxkcwrGqBwRnv/BcxtnXoWwiRloCzMXVPnS8uum+MgvVuVxbkJDJFeof5TlTqmaoxCTJL7sWPmep9/ezh77zacVGCUsXbpXPKz1HMn8yUsuDtqDuNkQKBgFvbnjqPcbAM8Mxv/z2XEEDEOM+bFlMjdM2tO/WHcH8Tn/9shCUT462cZo7z+8eEbAJcUhlFjBcwucOQN7Uz9fTNkbquu+nDxLvUGSk6tmsZIr8XQIrSrDMgGcaUeVboXg8F/39EUkOTcxm14JqkdtQYDRrISVZFnLYH47g5sP+xAoGAD6EP/TyOHabSIxWqc/RbTs9xAgeMzC9r+Cra+QOaHmWCwNKXEeyDVATl8z8OJpurUn7X3T3YgCknS0tAmdc9MHs5SRiqW98qUtPNYHKzpHah/10YSGkfCzEqDfPrujXM6e2HdoWNFEi+NwqP9BwC834ad6Y5/xEEw8TA5EtcPyo=";
//        AlipayConfig config = new AlipayConfig();
//        config.setServerUrl(domain);
//        config.setRootCertPath(alipayRootCert);
//        config.setAppId(appid);
//        config.setPrivateKey(prikey);
//        config.setAlipayPublicCertPath(alipayPublicCert);
//        config.setAppCertPath(appPublicCert);
//        config.setFormat("json");
//        config.setCharset("GBK");
//        config.setSignType("RSA2");
//        try {
//            AlipayClient alipayClient = new DefaultAlipayClient(config);
//            AlipayFundAuthorizeUniQueryRequest request = new AlipayFundAuthorizeUniQueryRequest();
//            AlipayFundAuthorizeUniQueryModel model = new AlipayFundAuthorizeUniQueryModel();
//            model.setProductCode("BATCH_API_TO_ACC");
//            model.setBizScene("STANDARD_MESSAGE_BATCH_PAY");
//            model.setOutBizNo("");
//            request.setBizModel(model);
//            AlipayFundAuthorizeUniQueryResponse response = alipayClient.certificateExecute(request);
//            if(response.isSuccess()){
//                return response.getAgreementNo();
//            }else{
//                return response.getSubMsg();
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return "SUCCESS";
//    }

    public static void main(String[] args) {
//        JSONObject params = new JSONObject();
//        params.put("alipay_root_cert_sn","687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6");
//        params.put("alipay_sdk","alipay-sdk-java-4.38.61.ALL");
//        params.put("app_cert_sn","688411dca29b7c7edddb57c5f75c7414");
//        params.put("app_id","2021004143669573");
//        params.put("biz_content","%7B%22batch_trans_id%22%3A%222024052210881255135%22%7D");
//        params.put("charset","GBK");
//
//        params.put("format","json");
//
//        params.put("method","alipay.fund.batch.app.pay");
//
//        params.put("charset","GBK");
//
//        params.put("sign","FvSYtxPqCTMhH6OGPz%2F3Nt0eTc4SflPPymW9VQnUAvDuemUgM6eKsTz62iCUPvpJ7gUnAa01j%2BDUvq7%2FI6Tuzt7lwS13P2EaAD5RZ61zDxVwOZrznakCeQ2f1s4JngVO3NzZfWGwpXVJabyHiPXnXa8h69yKd%2FZN8MQMgsr%2B3L2g0YPRQ8fV8DaoHgaSpPB%2BuAmmb6mwjWC0EOSc%2FqOBrHoJvRF1wB6Hh9Ir3JGfC4rhmXtw%2BnWDevOT9uluDQrq4mRIuuptqVjQ6yeNCkhIfJcvZTjgNjqTzm451Jf09aXz2STSpCE3wE2jTD3Yl1Ku984E88a03lZ9JHfELNbUFw%3D%3D")
        String parm = "alipay_root_cert_sn=687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6&alipay_sdk=alipay-sdk-java-4.38.61.ALL&app_cert_sn=688411dca29b7c7edddb57c5f75c7414&app_id=2021004143669573&biz_content=%7B%22batch_trans_id%22%3A%222024052210881255135%22%7D&charset=GBK&format=json&method=alipay.fund.batch.app.pay&sign=FvSYtxPqCTMhH6OGPz%2F3Nt0eTc4SflPPymW9VQnUAvDuemUgM6eKsTz62iCUPvpJ7gUnAa01j%2BDUvq7%2FI6Tuzt7lwS13P2EaAD5RZ61zDxVwOZrznakCeQ2f1s4JngVO3NzZfWGwpXVJabyHiPXnXa8h69yKd%2FZN8MQMgsr%2B3L2g0YPRQ8fV8DaoHgaSpPB%2BuAmmb6mwjWC0EOSc%2FqOBrHoJvRF1wB6Hh9Ir3JGfC4rhmXtw%2BnWDevOT9uluDQrq4mRIuuptqVjQ6yeNCkhIfJcvZTjgNjqTzm451Jf09aXz2STSpCE3wE2jTD3Yl1Ku984E88a03lZ9JHfELNbUFw%3D%3D&sign_type=RSA2×tamp=2024-05-22+19%3A17%3A35&version=1.0";

    }

}
