package com.yihu.wlyy.service.weixin;

import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.wechat.process.WeiXinEventProcess;
import com.yihu.wlyy.wechat.util.WeiXinMessageUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

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

/**
 * Created by lyr on 2016/08/11.
 */
@Service
public class WeiXinCoreService extends BaseService{

    /**
     * 微信推送消息处理
     *
     * @param request
     * @param accessToken
     */
    public String messageProcess(HttpServletRequest request,String accessToken){
        try{
            String returnStr = "";
            // 将解析结果存储在HashMap中
            Map<String,String> message = new HashMap();

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

            // 遍历所有子节点
            for (Object e : elementList) {
                Element ele = (Element)e;
                message.put(ele.getName(), ele.getText());
            }
            System.out.println("weixin  event:" + message.toString());
            // 释放资源
            inputStream.close();
            // 添加access_token参数
            message.put("token",accessToken);
            // 消息处理
            returnStr = messageProcess(message);

            return returnStr;
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 对接收到的消息进行处理
     *
     * @param message
     * @return
     */
    private String messageProcess(Map<String,String> message) throws Exception {
        String msgType = message.get("MsgType");
        String result = "";

        switch (msgType){
            case WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT:  // 事件消息
                result = WeiXinEventProcess.eventProcess(message);
                break;
            default:
                break;
        }

        return result;
    }
}
