package org.jeecg.modules.pay.paytest;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.jeecg.async.DirectCompletableFutureService;
import org.jeecg.async.ThreadPoolProperties;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.pay.config.WechatConstants;
import org.jeecg.modules.pay.config.WechatPayV3Utils;
import org.jeecg.modules.pay.config.WechatUrlConstants;
import org.jeecg.modules.pay.entity.ProfitSharingRequest;
import org.jeecg.modules.pay.entity.Receiver;
import org.jeecg.modules.pay.entity.ReceiverAddForm;
import org.jeecg.modules.pay.config.WeChatProfitSharingService;
import org.jeecg.modules.pay.serverPay.HttpClientUtil;
import org.jeecg.modules.pay.serverPay.PayKit;
import org.jeecg.modules.pay.serverPay.RsaKit;
import org.jeecg.modules.rabbitmq.DelayedMessageService;
import org.jeecg.modules.system.app.entity.AppOrder;
import org.jeecg.modules.system.app.service.IAppOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(value = "/profitSharing")
public class payController {

    private final WechatPayV3Utils wechatPayV3Utils;

    private final IAppOrderService appOrderService;

    private final WeChatProfitSharingService weChatProfitSharingService;

    private final DirectCompletableFutureService directCompletableFutureService;

    @GetMapping(value = "/getPay")
    public String getPay(String orderSn, int total, String description) {
        PayMerchantUtil payMerchantUtil = new PayMerchantUtil();
        try {
            return payMerchantUtil.requestwxChatPay(orderSn, total, description, "oYgFI91D00GpCwccdnKDR4KNxI4k");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 设置sub_mchid允许商户与哪些商户进行分账
     *
     * @param receiverAddForm
     * @return
     */
    @PostMapping(value = "/receivers/add")
    public JSONObject receiverAdd(@RequestBody ReceiverAddForm receiverAddForm) {
        try {
            return weChatProfitSharingService.receiversAdd(receiverAddForm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    @GetMapping(value = "/test")
//    public JSONObject test() {
//        //通过订单ID查询流水号
//        String transaction_id  = "88888888888888888888";
//        try {
//            JSONObject res = wechatPayV3Utils.sendGet(WechatUrlConstants.PAY_V3_QUERY_PROFIT_SHARING+"P001001001"+"?sub_mchid="+ServiceProvider.sub_mchid+"&transaction_id="+transaction_id);
//            log.info("wechatPay res:{}", res.toString());
//            return res;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    @GetMapping(value = "/test666")
    public String test() throws Exception {
        //时间戳
        long timestamp = System.currentTimeMillis() / 1000;
        //随机字符串（用UUID去掉-就行）
        String nonce = IdUtil.fastSimpleUUID().toUpperCase();
        String body = "";
        //拼接要签名的字符串
        PrivateKey privateKey = PayKit.getPrivateKey("这里填商户平台私钥证书");
        //拼接要签名的字符串
        String orgSignText = "GET\n"
                + "/v3/certificates\n"
                + timestamp + "\n"
                + nonce + "\n"
                + body + "\n";
        // 生成签名
        String sign = RsaKit.encryptByPrivateKey(orgSignText, privateKey);
        //要放在HttpHeader中的auth信息
        // 获取商户证书序列号  这里填写公钥路径 也就是apiclient_cert.pem这个文件的路径
        //证书序列号
        X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream("填你的apiclient_cert.pem"));
        String serialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        String auth = "WECHATPAY2-SHA256-RSA2048 "
                + "mchid=\"商户号\",nonce_str=\""
                + nonce + "\",timestamp=\"" + timestamp
                + "\",serial_no=\"" + serialNo + "\",signature=\"" + sign + "\"";
        String url = "https://api.mch.weixin.qq.com/v3/certificates";

        HashMap<String, Object> tmap = new HashMap<String, Object>();
        tmap.put("Authorization", auth);//tmap.put("token","tonken值");
        tmap.put("Accept", "application/json");
        tmap.put("User-Agent", "https://zh.wikipedia.org/wiki/User_agent");

        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Authorization", auth);
        httpGet.addHeader("Accept", "application/json");
        httpGet.addHeader("Content-type", "application/json; charset=utf-8");
        httpGet.addHeader("User-Agent", "https://zh.wikipedia.org/wiki/User_agent");

        String bodyAsString = HttpClientUtil.sendGetRequest(url, null);

        log.info("微信返回的内容：" + bodyAsString);

        String rs = HttpClientUtil.sendGetRequest(url, null);
        System.out.println("获取平台证书" + rs);
        return "success";
    }

    /**
     * 获取分账结果
     * @param out_order_no
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getResult")
    public JSONObject getResult(@RequestParam("out_order_no") String out_order_no){
        AppOrder appOrder = appOrderService.getOne(Wrappers.lambdaQuery(AppOrder.class).eq(AppOrder::getOrderCode, out_order_no).last("limit 1"));
        HashMap<String, String> map = new HashMap<>();
        map.put("sub_mchid", WechatConstants.WECHAT_SUB_MCH_ID);
        map.put("transaction_id", appOrder.getTransactionId());

        String params = WechatPayV3Utils.formatUrlParam(map);
        try {
            String url = WechatUrlConstants.PAY_V3_GET_PROFIT_SHARING + "P"+out_order_no + "?" + params;
//            String url = "https://api.mch.weixin.qq.com/v3/profitsharing/orders/PD202509261128071344?sub_mchid=1726971843&transaction_id=4200002838202509266221070669";

            JSONObject res = wechatPayV3Utils.sendGet(url);
            log.info("微信服务商分账结果查询--------------------------------------------------wechatPay res:{}", res.toString());
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 单次分账测试
     * @param out_order_no
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/test1")
    public JSONObject test(@RequestParam("out_order_no") String out_order_no) throws Exception {

        AppOrder appOrder = appOrderService.getOne(Wrappers.lambdaQuery(AppOrder.class).eq(AppOrder::getOrderCode, out_order_no).last("limit 1"));

        //1.参数封装
        /**
         * 分账接收方列表，不超过50个json对象，不能设置出资子商户作为分账接受方
         点击行前的+展开字段详情
         */
        List<Receiver> receivers = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(appOrder)) {
            String orgCode = appOrder.getOrgCode();
            //通过orgCode查询订单的分账发起方及接收方
        }
        //查询当前订单的分账接收方列表
        for (int i = 0; i < 1; i++) {
            Receiver receiver = new Receiver();
            receiver.setType("MERCHANT_ID")
                    .setAccount("1723757626")
                    .setAmount(1)
                    .setDescription("分给帝释天");
            receivers.add(receiver);
        }
        ProfitSharingRequest profitSharingRequest = new ProfitSharingRequest();
        profitSharingRequest
                .setAppid(WechatConstants.WECHAT_SP_APPID)
                .setSub_mchid(WechatConstants.WECHAT_SUB_MCH_ID)
                .setTransaction_id(appOrder.getTransactionId())
//                .setOut_order_no(out_order_no)
                .setOut_order_no("P"+out_order_no)
                .setReceivers(receivers)
                .setUnfreeze_unsplit(Boolean.TRUE);
        try {
            JSONObject res = wechatPayV3Utils.profitSharingSendPost(WechatUrlConstants.PAY_V3_PROFIT_SHARING, JSONObject.from(profitSharingRequest));
            log.info("微信服务商分账--------------------------------------------------wechatPay res:{}", res.toString());
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 请求分账回退
     * @param out_order_no
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/returnOrder")
    public JSONObject returnOrder(@RequestParam("out_order_no") String out_order_no) throws Exception {
        AppOrder appOrder = appOrderService.getOne(Wrappers.lambdaQuery(AppOrder.class).eq(AppOrder::getOrderCode, out_order_no).last("limit 1"));

        Map<String,Object> map = new HashMap<>();
        map.put("sub_mchid",WechatConstants.WECHAT_SUB_MCH_ID);
        map.put("out_order_no ","P"+out_order_no);
        map.put("order_id",appOrder.getProfitSharingOrderId());
        map.put("out_return_no","T"+out_order_no);
        map.put("return_mchid","1723757626");
        map.put("amount",1);
        map.put("description","帝释天退还");
        try {
            JSONObject res = wechatPayV3Utils.sendPost(WechatUrlConstants.PAY_V3_RETURN_ORDER, JSONObject.from(map));
            log.info("微信服务商分账回退--------------------------------------------------wechatPay res:{}", res.toString());
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询分账回退结果
     * @param out_order_no
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getReturnOrder")
    public JSONObject getReturnOrder(@RequestParam("out_order_no") String out_order_no) throws Exception {

        HashMap<String, String> map = new HashMap<>();
        map.put("sub_mchid", WechatConstants.WECHAT_SUB_MCH_ID);
        map.put("out_order_no", "P" + out_order_no);

        String params = WechatPayV3Utils.formatUrlParam(map);
        try {
            String url = WechatUrlConstants.PAY_V3_GET_RETURN_ORDER + "T" + out_order_no + "?" + params;
//            String url = "https://api.mch.weixin.qq.com/v3/profitsharing/orders/TD202509261128071344?sub_mchid=1726971843&out_order_no=PD202509261128071344";

            JSONObject res = wechatPayV3Utils.sendGet(url);
            log.info("微信服务商分账结果查询--------------------------------------------------wechatPay res:{}", res.toString());
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private final DelayedMessageService delayedMessageService;
    @GetMapping(value = "/test/rabbitTest")
    public Result<String> rabbitTest(@RequestParam("msg") String msg) throws ExecutionException, InterruptedException {
//        delayedMessageService.sendOrderExpireMessage(msg);
        log.info("接口调用，发送消息成功");
        CompletableFuture<String> stringCompletableFuture = directCompletableFutureService.executeTaskWithResult(msg);
        directCompletableFutureService.executeTaskWithoutResult();
        return Result.ok(stringCompletableFuture.get());
    }

    @GetMapping(value = "/test2")
    public JSONObject CertificateDownloaderTest() throws Exception {

        String res = "{\"order_id\":\"30002408162025101097141236049\",\"out_order_no\":\"PD202510101728312802\"," +
                "\"receivers\":[{\"account\":\"1726971843\",\"amount\":19,\"create_time\":\"2025-10-10T18:08:34+08:00\",\"description\":\"商户：中数未来（广州）信息技术有限公司于订单A01分账所获金额：19\",\"detail_id\":\"36002408162025101037927485682\",\"finish_time\":\"1970-01-01T08:00:00+08:00\",\"result\":\"PENDING\",\"type\":\"MERCHANT_ID\"},{\"account\":\"1726705634\",\"amount\":80,\"create_time\":\"2025-10-10T18:08:34+08:00\",\"description\":\"解冻给分账方\",\"detail_id\":\"36002408162025101037927485683\",\"finish_time\":\"1970-01-01T08:00:00+08:00\",\"result\":\"PENDING\",\"type\":\"MERCHANT_ID\"}],\"state\":\"PROCESSING\",\"sub_mchid\":\"1726705634\",\"transaction_id\":\"4200002834202510107247953928\"}";

        WeChatProfitSharingService weChatProfitSharingService = SpringContextUtils.getBean(WeChatProfitSharingService.class);

        return weChatProfitSharingService.profitSharings("D202510101728312802", res);


//        //用于证书解密的密钥
//        String apiV3key = "4b64e17419689527b256f07cdf6bd60c";
//        // 商户号
//        String mchId = "1725845681";
//        // 商户证书序列号
//        String mchSerialNo = "65E9559D81ADA0BDA0CD3CF484A59A8DFB5610BE";
//        // 商户私钥
//        String mchPrivateKeyFilePath = "E:\\wzq\\sss";
//        // 微信支付平台证书
//        //private static String wechatpayCertificateFilePath = "wxpayplatformcert.pem";
//        //下载成功后保存证书的路径
//        String outputFilePath = "E:\\wzq\\sss";
//
//
//        String[] args = {"-k", apiV3key, "-m", mchId, "-f", mchPrivateKeyFilePath,
//                    "-s", mchSerialNo, "-o", outputFilePath};
//
//            CommandLine.run(new CertificateDownloader(), args);
    }

}
 