package cn.common.common.utils.wx;

import cn.common.common.constants.PlatformConstant;
import cn.common.common.interaction.wx.WxAccessToken;
import cn.common.common.redis.RedisRepository;
import cn.common.common.utils.common.CheckParam;
import cn.common.common.constants.BaseConstant;
import cn.common.common.interaction.WxPageQrCode;
import cn.common.common.config.oss.ObjectStorage;
import cn.common.common.interaction.wx.WxBaseReq;
import cn.common.common.utils.http.HttpTookit;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.url.UrlBuilder;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Singer create by Singer email:singer-coder@qq.com
 * @packageName cn.common.common.utils.wx
 * @Description: 微信相关工具
 * @date 2021-02-26
 */
@Component
@Slf4j
public class WxService {

    @Resource
    private BaseConstant baseConstant;

    @Resource
    private PlatformConstant platformConstant;

    @Resource
    private ObjectStorage objectStorage;

    @Resource
    private RedisRepository redisRepository;



    /**
      * 生成微信页面二维码
      * @author: create by singer - Singer email:singer-coder@qq.com
      * @date 2021/2/26
      * @param wxPageQrCode 微信页面二维码请求参数
      * @return
      */
    public String wxPageQrCodeBase64(WxPageQrCode wxPageQrCode){

        log.info(">>>>>>>>>>>>微信生成页面二维码请求参数 : {} <<<<<<<<<<<", JSON.toJSON(wxPageQrCode));

        String itemId = wxPageQrCode.getItemId();

        String qrCodebase64 = redisRepository.get(PlatformConstant.ITEM_PAGE_WX_QR_CODE_CACHE_PREFIX+itemId);

        if(!CheckParam.isNull(qrCodebase64)){
            return qrCodebase64;
        }

        String buildUrl = UrlBuilder.ofHttp(baseConstant.getPageQrCodeUnLimit(), Charset.forName("utf-8"))
                .addQuery("access_token",weChatAccessToken(null))
                .build();

        //HttpPost httpPost = new HttpPost(buildUrl);
        Map<String, Object> paramMap = Maps.newHashMap();
        Map<String, Object> headersMap = Maps.newHashMap();

        headersMap.put("Content-Type","application/json");
        headersMap.put("Accept","*/*");
        headersMap.put("Accept-Encoding","gzip, deflate, br");
        headersMap.put("Connection","keep-alive");

        paramMap.put("scene",wxPageQrCode.getScene());
        paramMap.put("page",wxPageQrCode.getPage());

        try {
            byte[] bytes = HttpTookit.postBodyRequestBuffer(buildUrl, Maps.newHashMap(), paramMap, Maps.newHashMap());

            StringBuffer resultBuffer = new StringBuffer();
            String result = Base64.encode(bytes);
            resultBuffer.append("data:image/jpeg;base64,").append(result);

            qrCodebase64 = resultBuffer.toString();

            redisRepository.set(PlatformConstant.ITEM_PAGE_WX_QR_CODE_CACHE_PREFIX+itemId,qrCodebase64);

            return resultBuffer.toString();
        } catch (IOException e) {
            log.error(">>>>>>>>>>微信生成页面二维码请求参数请求出错: {} , {}  <<<<<<<<<",e.getMessage(),e);
        }

        return "";
    }



    /**
     * 拿到微信AccessToken
     * @author: create by singer - Singer email:singer-coder@qq.com
     * @date 2021/2/25
     * @param wxBaseReq 拿到微信AccessToken的请求参数
     * @return String
     */
    public String weChatAccessToken(WxBaseReq wxBaseReq){

        log.info(">>>>>>>>>>>微信拿到access-token请求参数: {} <<<<<<<<<<<",JSON.toJSONString(wxBaseReq));

        String accessToken = redisRepository.get(PlatformConstant.WX_ACCESS_TOKEN_CACHE_PREFIX);

        if(!CheckParam.isNull(accessToken)){
            return accessToken;
        }

        Map<String, Object> paramHashMap = new HashMap(8);
        paramHashMap.put("appid", baseConstant.getWxMiniAppId());
        //js_code只能使用一次
        paramHashMap.put("secret", baseConstant.getWxMiniAppSecret());

        if(!CheckParam.isNull(wxBaseReq)){
            if(!CheckParam.isNull(wxBaseReq.getGrantType())){
                paramHashMap.put("grant_type", wxBaseReq.getGrantType());
            }else{
                paramHashMap.put("grant_type", "client_credential");
            }
        }else{
            paramHashMap.put("grant_type", "client_credential");
        }
        String result = HttpTookit.getRequest(baseConstant.getAuthAccessTokenApi(), paramHashMap, "UTF-8");

        if(!CheckParam.isNull(result)){}

        WxAccessToken wxAccessToken = JSON.parseObject(result, WxAccessToken.class);

        log.info(">>>>>>>>>>>>>调用微信auth.code2Session接口返回 : <<<<<<<<<<<"+JSON.toJSONString(wxAccessToken));

        accessToken = wxAccessToken.getAccessToken();

        redisRepository.set(PlatformConstant.WX_ACCESS_TOKEN_CACHE_PREFIX,accessToken,7200L);

        return accessToken;
    }


}
