package com.izouma.awesomeadmin.util;

import com.izouma.awesomeadmin.dto.WxPaySendData;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.*;

/**
 * <p>微信统一下单相关服务类。</p>
 *
 * @author 索晨成 <br />
 * 更新履历 <br />
 * 日期 : 姓名: 更新内容<br />
 * @version 1.0
 */
public class UnifiedorderService {

    /**
     * 日志对象
     */
    private static Logger logger = Logger.getLogger(UnifiedorderService.class);


    public static Map<String, String> unifiedOrder(WxPaySendData data, String key) {

        //统一下单支付
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        try {
            //生成sign签名
            SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("appid", data.getAppid());
            parameters.put("mch_id", data.getMch_id());
            parameters.put("device_info", data.getDevice_info());
            parameters.put("nonce_str", data.getNonce_str());
            parameters.put("body", data.getBody());
            parameters.put("out_trade_no", data.getOut_trade_no());
            parameters.put("notify_url", data.getNotify_url());
            parameters.put("total_fee", data.getTotal_fee());
            parameters.put("trade_type", data.getTrade_type());
            parameters.put("spbill_create_ip", data.getSpbill_create_ip());
            if (data.getOpenid() != null) {

                parameters.put("openid", data.getOpenid());
            }
            parameters.put("attach", data.getAttach());

            /*
             * System.out.println("appid:" + data.getAppid() + ",mch_id:" + data.getMch_id() + ",device_info:" + data.getDevice_info() + ",nonce_str:"
                     + data.getNonce_str() + ",body:" + data.getBody() + ",out_trade_no:" + data.getOut_trade_no() + ",notify_url:"
                     + data.getNotify_url() + ",total_fee:" + data.getTotal_fee() + ",trade_type:" + data.getTrade_type() + ",spbill_create_ip:"
                     + data.getSpbill_create_ip() + ",openid:" + data.getOpenid());
            */
            String mySign = MbappUtil.createSign(key, parameters);
            logger.info("SIGN:" + mySign);
            // System.out.println("SIGN:" + mySign);
            data.setSign(mySign);
            XStream xs = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("__", "_")));
            xs.alias("xml", WxPaySendData.class);
            String xml = xs.toXML(data);
            logger.info("统一下单xml为:\n" + xml);

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder");

            StringEntity reqEntity = new StringEntity(xml, "utf-8");

            // 设置类型 
            reqEntity.setContentType("application/x-www-form-urlencoded");

            httpPost.setEntity(reqEntity);

            System.out.println("executing request" + httpPost.getRequestLine());

            HttpResponse response = httpclient.execute(httpPost);

            try {
                HttpEntity entity = response.getEntity();
                System.out.println(response.getStatusLine());
                if (entity != null) {

                    // 从request中取得输入流
                    InputStream inputStream = entity.getContent();
                    // 读取输入流
                    SAXReader reader = new SAXReader();
                    Document document = reader.read(inputStream);
                    // 得到xml根元素
                    Element root = document.getRootElement();
                    // 得到根元素的所有子节点
                    @SuppressWarnings("unchecked")
                    List<Element> elementList = root.elements();

                    // 遍历所有子节点
                    for (Element e : elementList) {
                        map.put(e.getName(), e.getText());

                        System.out.println(e.getName() + ":" + e.getText());
                    }
                    // 释放资源
                    inputStream.close();
                    inputStream = null;

                }
                EntityUtils.consume(entity);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

}
