package com.fzm.mall.midea.pay.utils;

import com.alibaba.fastjson.JSON;
import com.fzm.mall.midea.pay.params.BaseParam;
import com.fzm.mall.midea.pay.properties.MideaPayProperties;
import com.fzm.mall.midea.pay.model.CheckSignResponse;
import com.fzm.mall.midea.pay.model.HttpResponse;
import com.fzm.mall.midea.pay.model.SignResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author tangtuo
 * @date 2021/5/19 18:02
 */
@Component
public class SignUtil {

    @Resource
    private MideaPayProperties mideaPayProperties;

    private static final String SUCC_CODE = "1";

    public static String partnerAesEncrypt(String text, String partner, String reqSeqNo, String key) {

        String md5Source = new StringBuilder().append("partner=").append(partner).append("&req_seq_no=")
                .append(reqSeqNo).append("&key=").append(key).toString();
        String aesKey = DigestUtils.getMD5String(md5Source).substring(8, 24).toLowerCase();

        return DigestUtils.aesEncrypt(text, aesKey);
    }

    public String getSign(String sourceSign) {

        Map<String, String> params = new HashMap<>();
        params.put("source", DigestUtils.encryptMD5(sourceSign));
        //此处商户应该调用自己部署的tw-rsa-web程序
        HttpResponse httpResp = HttpClientUtils.doPost(mideaPayProperties.getGetSignUrl(), params);
        //WebUtils.checkJson(httpResp);
        SignResponse signResponse = JSON.parseObject(httpResp.getEntity(), SignResponse.class);
        if (signResponse != null && !SUCC_CODE.equals(signResponse.getCode())) {
            throw new RuntimeException("get tw sign exception");
        }
        return signResponse.getSign();

    }

    public void checkSign(Map<String, String> resultMap) {
        String sign = resultMap.get("sign");
        String sourceSign = getStringToSignOfStr(resultMap);
        Map<String, String> params = new HashMap<>();
        params.put("source", DigestUtils.encryptMD5(sourceSign));
        params.put("sign", sign);
        HttpResponse resp = HttpClientUtils.doPost(mideaPayProperties.getCheckSignUrl(), params);
        CheckSignResponse checkSignResponse = JSON.parseObject(resp.getEntity(), CheckSignResponse.class);
        if (!SUCC_CODE.equals(checkSignResponse.getCode())) {
            //验证签名成功&&返回的结果码为成功(如果是交易接口,还需要判断订单的状态),可做业务逻辑处理
            throw new RuntimeException("签名验证失败");
        }
    }

    public void checkSign(BaseParam param) {
        checkSign(param.beanToMap(param));
    }

    public static String getStringToSignOfStr(Map<String, String> map) {

        TreeMap<String, String> treeMap = new TreeMap<>();
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            treeMap.put(key, map.get(key));
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (StringUtils.isBlank(value) || "sign".equals(key)) {
                continue;
            } else {
                sb.append(key).append("=").append(value).append("&");
            }
        }
        if (sb.length() > 1)
            return sb.deleteCharAt(sb.length() - 1).toString();
        else
            return "";
    }

}
