package com.cftech.pay.api.callback;

import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.cftech.pay.api.com.cftech.pay.api.entity.WeiXinPayBillEntity;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2017/5/11.
 */
@Controller
@RequestMapping("/weixin/callback")
@Slf4j
public class WeiXinPayCallBackController {

    //RocketMq
    private static DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");

    static {
        producer.setNamesrvAddr("192.168.220.134:9876;192.168.220.135:9876");
        producer.setInstanceName("Producer");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/billcheck")
    public void payparm(HttpServletRequest request, HttpServletResponse response) {

    try
    {
        InputStream is = null;
        BufferedReader br = null;
        try
        {
            is = request.getInputStream();
            br = new BufferedReader(
                    new InputStreamReader(is,
                            "UTF-8"));

            String buffer = null;
            StringBuffer sb = new StringBuffer();
            while ((buffer = br.readLine()) != null)
            {
                sb.append(buffer);
            }
            StringReader sr = new StringReader(sb.toString());
            InputSource is2 = new InputSource(sr);

            // xml请求解析
            Map<String, String> requestMap = parseXml(is2);

            String return_code = requestMap.get("return_code");
            String return_msg = requestMap.get("return_msg");
            if("SUCCESS".equals(return_code))
            {
                String appid = requestMap.get("appid");//是
                String mch_id = requestMap.get("mch_id");//是
                String result_code = requestMap.get("result_code");//是 业务代码
                String err_code = requestMap.get("return_code");//否 错误描述代码
                String err_code_des = requestMap.get("return_code");//否 错误描述
                String openid = requestMap.get("openid");//是 用户OPENID
                String is_subscribe = requestMap.get("is_subscribe");//否 是否关注企业号
                String trade_type = requestMap.get("trade_type");//是 交易类型
                String bank_type = requestMap.get("bank_type");//是 付款银行
                String total_fee = requestMap.get("total_fee");//是 总金额
                String fee_type = requestMap.get("fee_type");//否 货币种类
                String cash_fee = requestMap.get("cash_fee");//是 现金支付金额
                String cash_fee_type = requestMap.get("cash_fee_type");//否 现金支付货币类型
                String transaction_id = requestMap.get("transaction_id");//是 微信支付订单号
                String out_trade_no = requestMap.get("out_trade_no");//是 商户订单号
                String attach = requestMap.get("attach");//否 商家数据包 根据传递过来的值进行填充
                String time_end = requestMap.get("time_end");//是支付完成时间

                WeiXinPayBillEntity entity = new WeiXinPayBillEntity();
                entity.setAppid(appid);
                entity.setMch_id(mch_id);
                entity.setResult_code(result_code);
                entity.setErr_code(err_code);
                entity.setErr_code_des(err_code_des);
                entity.setOpenid(openid);
                entity.setIs_subscribe(is_subscribe);
                entity.setTrade_type(trade_type);
                entity.setBank_type(bank_type);
                entity.setTotal_fee(total_fee);
                entity.setFee_type(fee_type);
                entity.setCash_fee(cash_fee);
                entity.setCash_fee_type(cash_fee_type);
                entity.setTransaction_id(transaction_id);
                entity.setOut_trade_no(out_trade_no);
                entity.setAttach(attach);
                entity.setTime_end(time_end);
                //System.out.println(entity);
                Message msg = new Message("TopicTest1",// topic
                        "TagA",// tag
                        "OrderID001",// key
                        (entity.toString()).getBytes());// body
                SendResult sendResult = producer.send(msg);
                System.out.println(sendResult);

                String res =  "<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>";
                PrintWriter out = response.getWriter();
                sr.close();
                out.print(res);
                out.close();
            }

        }
        catch (IOException e)
        {
            e.printStackTrace();
        } finally {
            if (is != null) is.close();
            if (br != null) br.close();
        }


        System.out.print("执行 CALLBACK");
    }catch(Exception e){
        e.printStackTrace();
    }

    }

    public static Map<String, String> parseXml(InputSource is) throws Exception {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        // 读取输入流
        org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
        org.dom4j.Document document = reader.read(is);
        // 得到xml根元素
        org.dom4j.Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List< Element> elementList = root.elements();

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