package com.heyu.api.controller.vv;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heyu.api.common.annotation.Describe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;

@Slf4j
@RestController
@RequestMapping("/app/weixin")
public class AppWeiXinPayNotifyController {


    // 微信支付APIv3密钥
    @Value("${eb.config.weixin.pay.apiv3key}")
    private String apiv3key;

    @Describe("微信支付回调")
    @PostMapping("/payNotify")
    public String handleWeChatPayCallback(@RequestBody String requestBody) {
        try {
            // Step 1: 解析微信支付回调通知的JSON
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(requestBody);

            // 获取加密数据
            String ciphertext = rootNode.get("resource").get("ciphertext").asText();
            String associatedData = rootNode.get("resource").get("associated_data").asText();
            String nonce = rootNode.get("resource").get("nonce").asText();
            // Step 2: 解密加密数据，使用AES-GCM解密
            String decryptedData = decrypt(ciphertext, associatedData, nonce);

            // Step 3: 处理解密后的数据
            JsonNode resultData = objectMapper.readTree(decryptedData);
            String transactionId = resultData.get("transaction_id").asText(); // 微信支付订单号
            String outTradeNo = resultData.get("out_trade_no").asText();      // 商户订单号
            String tradeState = resultData.get("trade_state").asText();       // 支付状态
            // 根据支付结果处理商户业务逻辑
            if ("SUCCESS".equals(tradeState)) {
                // 支付成功的逻辑，更新订单状态
                updateOrderStatus(outTradeNo, transactionId);
            }
            // Step 4: 返回处理结果，通知微信支付停止回调
            return "{\"code\":\"SUCCESS\",\"message\":\"OK\"}";

        } catch (Exception e) {
            e.printStackTrace();
            // 如果处理失败，返回错误信息
            return "{\"code\":\"FAIL\",\"message\":\"Server Error\"}";
        }
    }

    // AES-GCM解密方法
    private String decrypt(String ciphertext, String associatedData, String nonce) throws Exception {
        // 将APIv3密钥转为字节数组
        byte[] key = apiv3key.getBytes(StandardCharsets.UTF_8);
        Key secretKey = new SecretKeySpec(key, "AES");

        // 使用AES-GCM解密
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec spec = new GCMParameterSpec(128, nonce.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
        cipher.updateAAD(associatedData.getBytes(StandardCharsets.UTF_8));
        byte[] decodedCiphertext = Base64.getDecoder().decode(ciphertext);
        byte[] decryptedData = cipher.doFinal(decodedCiphertext);

        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    private void updateOrderStatus(String outTradeNo, String transactionId) {
        // 这里是更新商户订单状态的逻辑，例如标记订单已支付
        System.out.println("订单 " + outTradeNo + " 已支付，交易号：" + transactionId);
    }

}
