package com.izouma.nineth.service;

import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.izouma.nineth.config.SiweipayProperties;
import com.izouma.nineth.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * 四维支付实现
 */
@Service
@AllArgsConstructor
@Slf4j
public class SiweipayService {

    private SiweipayProperties siweipayProperties;

    public static final String PAY_ORDER = "/mall/payment/order";


    /**
     * 生成签名,如果参数的值为空不参与签名，该参数包括平台的key
     * @param payParameter
     * @return
     */
    public String getSign(TreeMap<String,Object> payParameter){
        StringBuilder signSource = new StringBuilder();
        payParameter.forEach((key,value) ->{
            signSource.append("&");
            String strValue = Objects.toString(value, "");
            if(StringUtils.isNotEmpty(strValue)){
                signSource.append(key + "=" + strValue);
            }

        });
        signSource.deleteCharAt(0);

        String sign = DigestUtils.md5Hex(signSource.toString()).toUpperCase();
        return sign;
    }


    /**
     * 支付请求
     * @param reqData
     * @return
     */
    public JSONObject pay(Map<String,Object> reqData){
        TreeMap<String,Object> payParameter = new TreeMap<>();
        payParameter.putAll(reqData);

        //附加商户信息
        payParameter.put("appId", siweipayProperties.getAppId());

        String sign = getSign(payParameter);

        payParameter.put("sign", sign);

        if(siweipayProperties.isDebug()){
            System.out.println("请求支付数据：" + payParameter);
        }

        String payUrl = siweipayProperties.getBaseUrl() + PAY_ORDER;
        payUrl  = URLUtil.normalize(payUrl, false, true);
        HttpRequest httpRequest = HttpRequest.post(payUrl);
        httpRequest.contentType(HttpRequest.CONTENT_TYPE_FORM, HttpRequest.CHARSET_UTF8);
        String sendContent = URLUtil.buildQuery(payParameter, Charset.forName(HttpRequest.CHARSET_UTF8));
        httpRequest.send(sendContent);
        String resStr = httpRequest.body();
        if(siweipayProperties.isDebug()){
            System.out.println("请求支付响应结果：" + resStr);
        }

        return JSONObject.parseObject(resStr);
    }

    /**
     * 检查状态
     * “status”: “0”, “qrcode”: ”二维码路径”, “errMsg”:”错误消息
     * @param response
     */
    public void checkSuccess(JSONObject response){
        String status = response.getString("status");
        String errMsg = response.getString("errMsg");
        if(!"0".equals(status)){
            throw new BusinessException(errMsg + "("+status+")");
        }

    }


}
