package com.cm.common.wechat.controller;

import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.SearchException;
import com.cm.common.result.SuccessResultData;
import com.cm.common.utils.AesUtil;
import com.cm.common.wechat.manager.officialaccount.WechatOfficialAccountManager;
import com.cm.common.wechat.pojo.WechatOfficialAccountUser;
import io.swagger.annotations.Api;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: WechatOfficialAccountApiController
 * @Description: 微信公众号公共接口
 * @Author: WangGeng
 * @Date: 2020/3/8 10:28 上午
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_WECHAT_PREFIX + "公共接口")
@RestController
@RequestMapping(ISystemConstant.WECHAT_PREFIX + "/officialaccount")
public class WechatOfficialAccountApiController {

    @GetMapping("getusertokenbyappidandopenidrelease/{appId}/{openId}")
    public SuccessResultData<String> getUserTokenByAppIdAndOpenId(@PathVariable("appId") String appId,
                                                                  @PathVariable("openId") String openId) throws Exception {
        String wechatSignInfo = Base64.encodeBase64String(AesUtil.aesCommonEncoder("WECHAT_SIGN_INFO", new StringBuilder(openId).append("_WenG_").append(appId).toString()).getBytes("UTF-8"));
        String token = WechatOfficialAccountManager.getInstance().getAppToken(wechatSignInfo);
        return new SuccessResultData<>(token);
    }

    @GetMapping("getusertokenrelease")
    public SuccessResultData<String> getUserToken(HttpServletRequest request) throws Exception {
        Object accessToken = request.getSession().getAttribute(ISystemConstant.SESSION_WECHAT_ACCESS_TOKEN);
        if (accessToken == null) {
            throw new SearchException("用户未登录，无token");
        }
        WechatOfficialAccountUser wechatOfficialAccountUser = (WechatOfficialAccountUser) accessToken;
        return new SuccessResultData<>(wechatOfficialAccountUser.getToken());
    }

}
