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

import com.alibaba.fastjson.JSON;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.service.dragon.utils.PayDouYinpayUtils;
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.impl.client.CloseableHttpClient;
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 zhangfuxin
 * @Description:
 * @date 2021/11/12 上午11:15
 */
@Slf4j
@Component
public class DouYinPayBiz {
    @Value("${liquidnet.dragon.wepay.merchantId}")
    private String merchantId;

    /**
     * @author zhangfuxin
     * @Description:抖音订单查询 实现
     * @date 2021/11/12 上午11:27
     */
    public Map<String, Object> tradeQuery(String outOrderNo, String appid) {
        Map<String, Object> respMap =CollectionUtil.mapStringObject();
        log.info("DouYinPayBiz.tradeQuery-->> request out_order_no:{} appid:{} ",outOrderNo,appid);
        SortedMap<String, Object> parameters = new TreeMap<>();
        parameters.put("app_id", appid);
        parameters.put("out_order_no", outOrderNo);
        //生成签名
        String sign = PayDouYinpayUtils.getInstance().createSign(parameters);
        parameters.put("sign", sign);
        //map转string
        String data = JSON.toJSONString(parameters);
        log.info("抖音订单查询请求参数:{}",data);
        try {
            HttpPost httpost = new HttpPost("https://developer.toutiao.com/api/apps/ecpay/v1/query_order");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpClient httpClient = PayDouYinpayUtils.getInstance().getHttpClient();
            CloseableHttpResponse response = httpClient.execute(httpost);
            HttpEntity entity = response.getEntity();
            //接受到返回信息
            String json = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("抖音订单查询接口返回:{}",json);
            EntityUtils.consume(entity);
            respMap=JSON.parseObject(json, HashMap.class);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return respMap;
    }
}
