package com.cool.store.http;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dto.wx.CodeSessionDTO;
import com.cool.store.dto.wx.MiniAppUrlLinkDTO;
import com.cool.store.dto.wx.MiniAppUrlLinkReqDTO;
import com.cool.store.dto.wx.PhoneInfoDTO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mq.util.HttpRestTemplateService;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author zhangchenbiao
 * @FileName: WechatRest
 * @Description:微信api
 * @date 2023-05-29 14:49
 */
@Slf4j
@Service
public class WechatRest {

    @Resource
    private RedisUtilPool redisUtilPool;

    @Resource
    private HttpRestTemplateService httpRestTemplateService;

    /**
     * 小程序Token 地址
     */
    String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    /**
     * 获取手机号码 地址
     */
    String GET_USERPHONENUMBER = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";

    String GET_MINIAPP_URL_LINK = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=%s";


    public CodeSessionDTO miniProgramJsCodeSession(String appId, String secret, String jsCode){
        log.info("WechatRest#miniProgramJsCodeSession, jsCode:{}", jsCode);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap requestMap = new HashMap();
        requestMap.put("appid", appId);
        requestMap.put("secret", secret);
        requestMap.put("js_code", jsCode);
        requestMap.put("grant_type","authorization_code");
        try {
            String responseStr = httpRestTemplateService.getForObject(url, String.class ,requestMap);
            log.info("WechatRest#miniProgramJsCodeSession, url:{}, response:{}", url, responseStr);
            if(StringUtils.isNotBlank(responseStr)){
                return JSONObject.parseObject(responseStr, CodeSessionDTO.class);
            }
        } catch (Exception e) {
            log.info("调用微信服务异常{}", e);
            throw new ServiceException(ErrorCodeEnum.WX_SERVICE_ERROR);
        }
        return null;
    }

    public String getAccessToken(String appId, String secret) {
        String cacheAccessToken = "wechat_mini_" + appId;
        String accessToken = redisUtilPool.getString(cacheAccessToken);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        String reqUrl = String.format(ACCESS_TOKEN, appId, secret);
        try {
            JSONObject jsonObject = httpRestTemplateService.getForObject(reqUrl, JSONObject.class, new HashMap());
            log.info("WechatRest#getAccessToken, reqUrl:{}, response:{}", reqUrl, JSONObject.toJSONString(jsonObject));
            String token = jsonObject.getString("access_token");
            if (StringUtils.isBlank(token)) {
                throw new ServiceException(ErrorCodeEnum.GET_ACCESSTOKEN_ERROR);
            }
            redisUtilPool.setString(cacheAccessToken, token, 7000);
            return token;
        } catch (Exception e) {
            log.error("获取微信小程序token异常", e);
        }
        return null;
    }


    public PhoneInfoDTO getUserPhoneNumber(String code, String accessToken){
        String reqUrl = String.format(GET_USERPHONENUMBER, accessToken);
        HashMap requestMap = new HashMap();
        requestMap.put("code", code);
        String responseStr = null;
        try {
            responseStr = httpRestTemplateService.postForObject(reqUrl, requestMap, String.class);
            log.info("WechatRest#getUserPhoneNumber, reqUrl:{}, response:{}", reqUrl, responseStr);
            if(StringUtils.isNotBlank(responseStr)){
                return JSONObject.parseObject(responseStr, PhoneInfoDTO.class);
            }
        } catch (Exception e) {
            log.error("获取手机号异常", e);
        }
        return null;
    }

    public MiniAppUrlLinkDTO getMiniAppUrlLink(String accessToken, MiniAppUrlLinkReqDTO miniAppUrlLinkReqDTO){
        String reqUrl = String.format(GET_MINIAPP_URL_LINK, accessToken);
        String responseStr = null;
        try {
            responseStr = httpRestTemplateService.postForObject(reqUrl, miniAppUrlLinkReqDTO, String.class);
            log.info("WechatRest#getUserPhoneNumber, reqUrl:{}, response:{}", reqUrl, responseStr);
            if(StringUtils.isNotBlank(responseStr)){
                return JSONObject.parseObject(responseStr, MiniAppUrlLinkDTO.class);
            }
        } catch (Exception e) {
            log.error("获取手机号异常", e);
        }
        return null;
    }

}
