package com.house365.wechat.rest;

import com.house365.wechat.WeChatProperties;
import com.house365.wechat.aes.WXBizMsgCrypt;
import com.house365.wechat.service.RemoteCallService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 2016/12/13</p>
 *
 * @author XN
 * @version 1.0
 */
@RestController
public class WechatController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private DiscoveryClient client;

    @Autowired
    private RemoteCallService remoteCallService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String add() {
        ServiceInstance instance = client.getLocalServiceInstance();
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
        return "OK";
    }

    @RequestMapping(value = "/call", method = RequestMethod.POST)
    public String call() {
        ServiceInstance instance = client.getLocalServiceInstance();
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
        return "CALL";
    }

    @RequestMapping(value = "checkWeChatCallback", method = RequestMethod.GET)
    public String checkWeChatCallback(@RequestParam(value = "msg_signature") String sVerifyMsgSig,
                                      @RequestParam(value = "timestamp") String sVerifyTimeStamp,
                                      @RequestParam(value = "nonce") String sVerifyNonce,
                                      @RequestParam(value = "echostr") String sVerifyEchoStr) throws Exception {
        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(weChatProperties.getToken(),
                weChatProperties.getEncodingAESKey(),
                weChatProperties.getCorpId());

        String sEchoStr = null; //需要返回的明文
        try {
            sEchoStr = wxBizMsgCrypt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);
            System.out.println("verifyUrl echostr: " + sEchoStr);
            // 验证URL成功，将sEchoStr返回
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            logger.error(e.getMessage(), e);
        }
        return sEchoStr;
    }

    /**
     * 获取access token
     *
     * @param corpID 企业号id
     * @param secret 权限组密钥
     * @return
     */
    @RequestMapping(value = "getAccessToken")
    public String getAccessToken(
            @RequestParam(value = "corpID") String corpID, @RequestParam(value = "secret") String secret
    ) {
        return remoteCallService.getAccessToken(corpID, secret);
    }

    /**
     * 根据code 和 accesstoken获取用户信息
     *
     * @param code        微信回调时传入
     * @param accessToken
     * @return
     */
    @RequestMapping(value = "getUserInfo")
    public JSONObject getUserInfo(
            @RequestParam(value = "code") String code, @RequestParam(value = "accessToken") String accessToken
    ) {
        return remoteCallService.getUserInfo(code, accessToken);
    }

    /**
     * 根据userid获取openid
     *
     * @param userId
     * @param agentId 应用ID
     * @return
     */
    @RequestMapping(value = "getOpenId")
    public JSONObject getOpenId(
            @RequestParam(value = "userId") String userId, @RequestParam(value = "agentId") String agentId,
            @RequestParam(value = "accessToken") String accessToken
    ) {
        return remoteCallService.getOpenId(userId, agentId, accessToken);
    }

    /**
     * 获取access token
     *
     * @param corpID
     * @param secret
     * @return
     */
    @RequestMapping(value = "getJsapiTicket")
    public String getJsapiTicket(
            @RequestParam(value = "corpID") String corpID, @RequestParam(value = "secret") String secret
    ) {
        return remoteCallService.getJsapiTicket(corpID, secret);
    }
}
