package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 开放平台回调接收端
 * 注意：/product/receive 与 /order/receive 为示例路径，请在开放平台配置时使用你自己的正式回调地址
 */
@RestController
@RequestMapping("/open/callback")
public class OpenCallbackController extends BaseController {

    @PostMapping("/product/receive")
    public JSONObject receiveProductCallback(
            @RequestParam("appid") String appid,
            @RequestParam(value = "timestamp", required = false) Long timestamp,
            @RequestParam("sign") String sign,
            @RequestBody JSONObject body
    ) {
        if (!verifySign(appid, timestamp, sign, body)) {
            JSONObject fail = new JSONObject();
            fail.put("result", "fail");
            fail.put("msg", "签名失败");
            return fail;
        }
        JSONObject ok = new JSONObject();
        ok.put("result", "success");
        ok.put("msg", "接收成功");
        return ok;
    }

    @PostMapping("/order/receive")
    public JSONObject receiveOrderCallback(
            @RequestParam("appid") String appid,
            @RequestParam(value = "timestamp", required = false) Long timestamp,
            @RequestParam("sign") String sign,
            @RequestBody JSONObject body
    ) {
        if (!verifySign(appid, timestamp, sign, body)) {
            JSONObject fail = new JSONObject();
            fail.put("result", "fail");
            fail.put("msg", "签名失败");
            return fail;
        }
        JSONObject ok = new JSONObject();
        ok.put("result", "success");
        ok.put("msg", "接收成功");
        return ok;
    }

    private boolean verifySign(String appid, Long timestamp, String sign, JSONObject body) {
        // TODO: 这里需要根据appid查出对应的 appKey/appSecret
        // 为了示例，直接使用 ERPAccount.ACCOUNT_HUGE 的常量。生产请替换为从数据库/配置读取
        String appKey = "1016208368633221";
        String appSecret = "waLiRMgFcixLbcLjUSSwo370Hp1nBcBu";

        String json = body == null ? "{}" : body.toJSONString();
        String data = appKey + "," + md5(json) + "," + (timestamp == null ? 0 : timestamp) + "," + appSecret;
        String local = md5(data);
        return StringUtils.equalsIgnoreCase(local, sign);
    }

    private String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}


