package com.cnd3b.utility.qywechat;

import com.cnd3b.utility.qywechat.base.Parameter;
import com.cnd3b.utility.qywechat.base.ReturnHandle;
import com.cnd3b.utility.qywechat.base.system.WXBizMsgCrypt;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

@Path("qywechat")
public class wechat {

    /**
     * 企业微信消息接收及发送接口
     *
     * @param timestamp
     * @param nonce
     * @param msg_signature
     * @param content
     * @return
     */
    @POST
    public String wechatmsg(@QueryParam("timestamp") String timestamp, @QueryParam("nonce") String nonce,
                            @QueryParam("msg_signature") String msg_signature, String content) {
        String finalreturnxml = "";
        try {
            Parameter.initParameter();

            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Parameter.token, Parameter.EncodingAESKey, Parameter.CorpID);
            String finalxml = wxcpt.decryptMsg(msg_signature, timestamp, nonce, content);
            ReturnHandle handle = new ReturnHandle(finalxml);
            String xml = handle.getReturnXML();
            if (xml != null && !xml.equals("")) {
                finalreturnxml = wxcpt.encryptMsg(xml, timestamp, nonce);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return finalreturnxml;
    }

    /**
     * 企业微信接收消息服务器配置验证方法
     *
     * @param timestamp
     * @param nonce
     * @param echostr
     * @param msg_signature
     * @return
     */
    @GET
    public String validate(@QueryParam("timestamp") String timestamp, @QueryParam("nonce") String nonce,
                           @QueryParam("echostr") String echostr, @QueryParam("msg_signature") String msg_signature) {
        // 需要返回的明文
        String returnEchoStr = "";
        try {
            /**
             * 如果企业微信参数未设置，则从数据库中查询获取
             */
            Parameter.initParameter();

            WXBizMsgCrypt wxcpt;
            wxcpt = new WXBizMsgCrypt(Parameter.token, Parameter.EncodingAESKey, Parameter.CorpID);
            returnEchoStr = wxcpt.verifyUrl(msg_signature, timestamp, nonce, echostr);

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