package com.mcwl.web.controller.pay.WxPay;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mcwl.web.controller.pay.WxPay.util.PayUtil;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付
 *
 * @author DaiZibo
 * @date 2025/1/6
 * @apiNote
 */


@RestController
@RequestMapping(value = "/wx/pay")
public class WxPayController {

    /**
     * 预支付下单
     *
     * @param orderSn     订单号
     * @param total       分
     * @param description 描述
     */
    @GetMapping(value = "/getPay")
    public String getPay(String orderSn, int total, String description) {
        PayUtil payUtil = new PayUtil();
        try {
            return payUtil.requestwxChatPay(orderSn, total, description, "oYgFI91D00GpCwccdnKDR4KNxI4k");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 支付回调
    @PostMapping(value = "/returnNotify")
    public Map returnNotify(@RequestBody JSONObject jsonObject) {
        // v3 私钥
        String key = "xxxxx";
        String json = jsonObject.toString();
        String associated_data = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.associated_data");
        String ciphertext = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.ciphertext");
        String nonce = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.nonce");
        try {
            String decryptData = new AesUtil(key.getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
            System.out.println("decryptData = " + decryptData);
            //TODO 业务校验
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("code", "200");
        stringStringHashMap.put("message", "返回成功");
        // 返回这个说明应答成功
        return stringStringHashMap;
    }
}
