package com.jeeplus.weChat.controller;

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.weChat.domain.SignatureInfo;
import com.jeeplus.weChat.domain.WXTransportTemplate;
import com.jeeplus.weChat.service.WxSendService;
import com.jeeplus.weChat.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.flowable.ui.common.service.exception.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @author 王强
 * @version 1.0
 * @date 2024-07-17 9:57
 */
@RestController
@Slf4j
public class ProxyController {

    @Autowired
    private WxMpService wxMpService;

    @Resource
    private WxSendService wxSendService;

    @GetMapping("/app/proxy")
    public ResponseEntity<?> proxy(@RequestParam String appid,
                                   @RequestParam String secret,
                                   @RequestParam String code) {
        try {
            // 获取 access token
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            log.info("【AccessToken：】{}", wxMpOAuth2AccessToken.getAccessToken());

            // 获取 openid
            String openId = wxMpOAuth2AccessToken.getOpenId();
            log.info("【openid：】{}", openId);

            // 获取用户信息
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
            log.info("【用户信息：】{}", wxMpUser.toString());

            // 返回用户信息
            return ResponseEntity.ok(wxMpUser);

        } catch (WxErrorException e) {
            log.error("【微信网页授权错误】{}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("微信授权失败: " + e.getMessage());
        }
    }

    // 获取微信的access_token（这个token使用一次及失效）
    @GetMapping("/app/getToken")
    public String getAccess_token(){
        String token = HttpUtils.dogetToken();
        return token;
    }
    // 根据微信的access_token获取签名
    @GetMapping("/app/getSignature")
    public SignatureInfo getSignature(@RequestParam String url){
        SignatureInfo signature = HttpUtils.dogetSignature(url);
        return signature;
    }

    @PostMapping("/app/sendTemplate")
    public String sendTranTemplate( @RequestBody WXTransportTemplate resource) throws IOException {
        //templateid，模板id，就是发送信息的格式模板id
        String result = wxSendService.sendTranTemplate(resource);
        //判断发送模板消息结果
        JSONObject obj = JSONObject.parseObject(result);
        Map<String, Object> map =obj;
        Integer code = (Integer)map.get("errcode");
        String msg =map.get("errmsg").toString();
        if (0  != code  ||  !"ok".equals(msg)){
            throw new BadRequestException("微信公众号模板消息推送失败，错误代码为：+"+code+"错误消息为："+msg);
        }
        return result;
    }




//    这是测试号在微信开发者工具里面的 地址
//    https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx96885ba58675d910&redirect_uri=http%3A%2F%2Fxrd3cp.natappfree.cc%2Fh5%2F&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
//    https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa79f618dcaf992f7&redirect_uri=http%3A%2F%2Fkqe4km.natappfree.cc%2Fh5%2F&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
}
