package com.jeequan.jeepay.mch.ctrl.pos;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.TreeMap;

/**
* pos机接口管理类
*
* @author zx
*
* @date 2022/3/4 9:43
*/
@Slf4j
public class PosSignUtil extends CommonCtrl {

    /** 校验签名字符串 */
    public static boolean verify(JSONObject reqParams, String secretKey) {

        String sign = sign(reqParams, secretKey);

        return sign.equals(reqParams.getString("sign"));
    }

    public static String sign(JSONObject reqParams, String secretKey) throws BizException {

        TreeMap<String, Object> tree = new TreeMap<>();

        // 1. 所有参数进行排序
        reqParams.keySet().forEach(key -> tree.put(key, reqParams.get(key)));

        //2. 拼接value
        StringBuffer stringBuffer = new StringBuffer();
        tree.keySet().forEach(key -> {

            if (tree.get(key) == null) {
                return ;
            }
            if(StringUtils.isAnyEmpty(key, tree.get(key).toString())){ //空值， 不参与签名
                return ;
            }
            if("sign".equals(key)){ //签名串， 不参与签名
                return ;
            }

            stringBuffer.append(key + "=" + tree.get(key) + "&");
        });
        String signStr = stringBuffer.append("key=" + secretKey).toString();
        log.info("POS机【待加签字符串】：{}", signStr);
        String md5 = JeepayKit.md5(signStr, "UTF-8");
        log.info("POS机【签名结果】：{}", md5);
        if (StringUtils.isBlank(md5)) {
            throw new BizException("POS机数据加密失败");
        }
        return md5.toLowerCase();
    }

    public static void main(String[] args) {
        //queryOrderTest();
        payOrderTest();
        String pp = "{\"result\":{\"total\":2,\"current\":1,\"records\":[{\"amount\":14,\"createdAt\":\"2024-02-28 09:55:10\",\"payOrderId\":\"O1762657665502453761\",\"refundAmount\":0,\"state\":2,\"wayCodeType\":\"WECHAT\"},{\"amount\":20,\"createdAt\":\"2024-02-28 09:53:18\",\"payOrderId\":\"O1762657192787615745\",\"refundAmount\":0,\"state\":2,\"wayCodeType\":\"WECHAT\"}],\"hasNext\":false},\"code\":\"00000\",\"sign\":\"17d32156e6ffd0374b6884c74b813df3\",\"message\":\"success\"}";
        JSONObject jsonObject = JSONObject.parseObject(pp);
        String sign = sign(jsonObject,"0zjyefg6q1r485llp0x9sdbifss4da24hi42qt0bikfg0sv3nf4asz2buykgxokv5mg32k02ctcijzfiak5yuhtxqv8jrzwf4vvyc78iswlzmdr2anqjhbknbsyqcylq");
        System.out.println(sign);
    }

    public static void queryOrderTest() {
        JSONObject param = new JSONObject();
        /*
        发送地址：https://mch.s.jeepay.vip/api/pos/orderDetail/1
        发送内容：{"appId": "79f23e319567442f8c26e86dee787162","data": "{\"deviceOrderNum\":\"P1517371225137188866\"}","deviceId": "D123456","merchantId": "M1648869277","requestTime": "1650609500","sign": "b958270775ea2c06785cd80b532c7fad","productNum":"123456"}
        返回内容：{"code":"99999","message":"签名错误"}
        */
        param.put("appId", "79f23e319567442f8c26e86dee787162");
        param.put("data", "{\"deviceOrderNum\":\"P1517371225137188866\"}");

        param.put("deviceId", "D123456");
        param.put("merchantId", "M1648869277");
        param.put("requestTime", "1650609500");
        param.put("productNum", "123456");
        param.put("appId", "79f23e319567442f8c26e86dee787162");
        // "sign": "974954509d21dcd4b280f297ea01f12f"

        JSONObject dataObj = param.getJSONObject("data");
        String deviceOrderNum = dataObj.getString("deviceOrderNum");
        if(StringUtils.isNotBlank(deviceOrderNum)) {
            param.put("data", "{\\\"deviceOrderNum\\\":\\\""+deviceOrderNum+"\\\"}");
        }

        String secret = "fdgd3geo62vmfe2pl5m4neckyjeivbuz599giiicjmnwza6yy5grtgxvbm0kxw10t3xihkffec7kjq3tgqyv1515lbsr34h8hn41p6m81yx1zizceg3v4oxk1o9y5epk";

        System.out.println(PosSignUtil.sign(param, secret));


        // 品生问题
        // 查单接口  签名串 fdgd3geo62vmfe2pl5m4neckyjeivbuz599giiicjmnwza6yy5grtgxvbm0kxw10t3xihkffec7kjq3tgqyv1515lbsr34h8hn41p6m81yx1zizceg3v4oxk1o9y5epk79f23e319567442f8c26e86dee787162{\"deviceOrderNum\":\"P1517371225137188866\"}D123456M16488692771234561650609500

        // 查单接口，有传productNum，data里的数据必须 带\

    }

    public static void payOrderTest() {

        /*
            发送地址：https://mch.s.jeepay.vip/api/pos/pay/1
            发送内容：{"appId": "79f23e319567442f8c26e86dee787162","data":"{\"deviceOrderNum\":\"20220422142430913355\",\"payAmount\":0.01,\"payType\":2,\"qrCode\":\"132554727973706005\"}",
            "deviceId": "D123456","merchantId": "M1648869277","requestTime": "1650609381","sign": "fc7498947b73a3f86b326e6557a15fb0"}
            返回内容：{"code":"99999","message":"签名错误"}
        */


        JSONObject param = new JSONObject();

        param.put("appId", "79f23e319567442f8c26e86dee787162");
        param.put("data", "{\"deviceOrderNum\":\"20220422180818629757\",\"payAmount\":0.01,\"payType\":2,\"qrCode\":\"134155583541292265\"}");

        param.put("deviceId", "D123456");
        param.put("merchantId", "M1648869277");
        param.put("requestTime", "1650622175");
        param.put("productNum", "123456");

        // "sign": "974954509d21dcd4b280f297ea01f12f"

        String secret = "fdgd3geo62vmfe2pl5m4neckyjeivbuz599giiicjmnwza6yy5grtgxvbm0kxw10t3xihkffec7kjq3tgqyv1515lbsr34h8hn41p6m81yx1zizceg3v4oxk1o9y5epk";

        param.remove("productNum");

        System.out.println(PosSignUtil.sign(param, secret));

        // 品生问题
        // 查单接口  签名串 fdgd3geo62vmfe2pl5m4neckyjeivbuz599giiicjmnwza6yy5grtgxvbm0kxw10t3xihkffec7kjq3tgqyv1515lbsr34h8hn41p6m81yx1zizceg3v4oxk1o9y5epk79f23e319567442f8c26e86dee787162{\"deviceOrderNum\":\"P1514055777637289986\"}D123456M16488692771650604549

    }

}
