package com.liquidnet.service.dragon.channel.wepay.biz;

import com.liquidnet.service.dragon.utils.PayWepayUtils;
import com.liquidnet.service.dragon.utils.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: WepayBiz
 * @Package com.liquidnet.service.dragon.channel.wepay.biz
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/10 16:46
 */
@Slf4j
@Component
public class WepayBiz{
    @Value("${liquidnet.dragon.wepay.merchantId}")
    private String merchantId;

    /**
     * 订单查询
     *
     * @return
     */
    public Map<String, Object> tradeQuery(String outTradeNo, String appid) {
        log.info("WepayBiz.tradeQuery-->> request outTradeNo:{} appid:{} ",outTradeNo,appid);
        Map<String, Object> respMap = new HashMap<>();
        SortedMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("appid", appid);
        paramMap.put("mch_id", merchantId);
        String nonce_str = PayWepayUtils.getInstance().getNonceStr();
        paramMap.put("nonce_str", nonce_str);
        paramMap.put("out_trade_no", outTradeNo);
        String sign = PayWepayUtils.getInstance().createSign(paramMap);
        paramMap.put("sign", sign);

        String data = PayWepayUtils.getInstance().getRequestXml(paramMap);
        try{
            HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = PayWepayUtils.getInstance().getHttpClient().execute(httpost);
            HttpEntity entity = response.getEntity();
            //接受到返回信息
            String xmlStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            log.info("WepayBiz.tradeQuery-->> response xmlStr: {} ",xmlStr);
            respMap = XmlUtil.xmlToMap(xmlStr);
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return respMap;
    }
}
