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

import com.liquidnet.service.dragon.channel.wepay.resp.WepayOrderQueryRespDto;
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.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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;

    @Autowired
    private WepayBiz wepayBiz;
    /**
     * 订单查询
     *
     * @return
     */
    public WepayOrderQueryRespDto tradeQuery(String outTradeNo,String appid) {
        log.info("======>支付宝交易查询");
        WepayOrderQueryRespDto respDto = null;
        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("dragonPay:wepay:wap response xmlStr: {} ",xmlStr);
            respDto = XmlUtil.toBean(xmlStr, WepayOrderQueryRespDto.class);
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return respDto;
    }
}
