package com.ruoyi.common.weixin.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.weixin.config.WeiXinXcxMemberConfig;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @Author haoxuyang
 * @Date 2024/12/21 10:14
 */
@Component
public class WeiXinXcxMemberUtils {
    //日志
    private static final Logger logger = LoggerFactory.getLogger(WeiXinXcxMemberUtils.class);

    @Resource
    private RedisCache redisService;

//    @Resource
//    private FileUploadService fileUploadService;

    @Resource
    private WeiXinXcxMemberConfig weiXinXcxMemberConfig;

    /**
     * 获取access_token
     *
     * @return access_token
     */
    public String getAccessToken() {
        JSONObject jsonObject = new JSONObject();
        String accessToken = "";
        String redisKey = CacheConstants.XCX_MEMBER_ACCESS_TOKEN_KEY;
        try {
            if (redisService.hasKey(redisKey)) {
                return redisService.getCacheObject(redisKey).toString();
            }
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/token" +
                    "?grant_type=client_credential" +
                    "&appid=" + weiXinXcxMemberConfig.getAppId() +
                    "&secret=" + weiXinXcxMemberConfig.getAppSecret();
            String result = HttpUtil.get(requestUrl);
            logger.info("{} 小程序获取access_token结果 -> {}", DateUtils.getTime(), result);
            jsonObject = JSONObject.parseObject(result);
            // 有效期(s)
            Long expiresIn = 0L;
            if (ObjectUtils.isNotEmpty(jsonObject)) {
                accessToken = jsonObject.getString("access_token");
                expiresIn = jsonObject.getLong("expires_in");
            }
            if (StringUtils.isBlank(accessToken)) {
                logger.error("{} 小程序获取access_token失败 -> {}", DateUtils.getTime(), result);
            } else {
                redisService.setCacheObject(redisKey, accessToken, Integer.parseInt(String.valueOf(expiresIn)), SECONDS);
            }
        } catch (Exception e) {
            logger.error("{} 小程序获取access_token异常 -> {}", DateUtils.getTime(), e.getMessage());
        }
        return accessToken;
    }

    /**
     * 小程序授权获取openId
     *
     * @param code 登录时获取的 code
     * @return openId
     */
    public String getWebAuthorizeInfo(String code) {
        String openId = "";
        String unionid = "";
        try {
            String requestUrl = "https://api.weixin.qq.com/sns/jscode2session" +
                    "?appid=" + weiXinXcxMemberConfig.getAppId() + "&" +
                    "secret=" + weiXinXcxMemberConfig.getAppSecret() + "&" +
                    "js_code=" + code + "&" +
                    "grant_type=authorization_code";
            // 结果
            String result = HttpUtil.get(requestUrl);
            logger.info("{} 小程序授权获取openId结果 -> {}", DateUtils.getTime(), result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            openId = jsonObject.getString("openid");
            unionid = jsonObject.getString("unionid");
        } catch (Exception e) {
            logger.error("{} 小程序授权获取openId异常 -> {}", DateUtils.getTime(), e.getMessage());
        }
        return openId;
    }

    /**
     * 小程序授权获取openId
     *
     * @param code 登录时获取的 code
     * @return openId
     */
    public Map<String, String> getWebAuthorizeInfoMap(String code) {
        Map<String, String> map = new HashMap<>();
        try {
            String requestUrl = "https://api.weixin.qq.com/sns/jscode2session" +
                    "?appid=" + weiXinXcxMemberConfig.getAppId() + "&" +
                    "secret=" + weiXinXcxMemberConfig.getAppSecret() + "&" +
                    "js_code=" + code + "&" +
                    "grant_type=authorization_code";
            // 结果
            String result = HttpUtil.get(requestUrl);
            logger.info("{} 小程序授权获取openId结果 -> {}", DateUtils.getTime(), result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String openId = jsonObject.getString("openid");
            String unionId = jsonObject.getString("unionid");
            map.put("openid", openId);
            map.put("unionId", unionId);
        } catch (Exception e) {
            logger.error("{} 小程序授权获取openId异常 -> {}", DateUtils.getTime(), e.getMessage());
        }
        return map;
    }

    /**
     * 获取用户手机号
     *
     * @param phoneCode 手机号获取凭证
     * @return 手机号
     */
    public String getUserPhoneNumber(String phoneCode) {
        String phoneNumber = "";
        try {
            // 请求地址
            String requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + this.getAccessToken();
            // 请求参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", phoneCode);
            // 结果
            String res = HttpUtil.createPost(requestUrl).
                    body(jsonObject.toString()).execute().body();
            logger.info("{} 小程序手机号API结果 -> {}", DateUtils.getTime(), res);
            JSONObject result = JSONObject.parseObject(res);
            if ("0".equals(result.getString("errcode"))) {
                JSONObject phone_info = result.getJSONObject("phone_info");
                phoneNumber = phone_info.get("phoneNumber").toString();
            }
            return phoneNumber;
        } catch (Exception e) {
            logger.error("{} 小程序手机号API异常 -> {}", DateUtils.getTime(), e.getMessage());
        }
        return phoneNumber;
    }

    /**
     * 获取职位分享小程序码
     * @param positionId 职位ID
     * @param key key
     * @return 结果
     */
   /* public String getPositionShareQRCode(String positionId, String key){
        return this.getQRCode("", key);
    }*/

    /**
     * 获取小程序码
     *
     * @param path 路径参数
     * @param key key
     * @return 图片链接
     */
    /*public String getQRCode(String path, String key){
        String qrCodeUrl = "";
        HttpResponse execute = null;
        try {
            //获取token
            String accessToken = this.getAccessToken();
            String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ accessToken;
            //post参数
            JSONObject jsonObject = new JSONObject();
            if (StringUtils.isNotBlank(path)){
                jsonObject.put("page", path);
            }
            jsonObject.put("scene", key);
            jsonObject.put("check_path", false);
            jsonObject.put("env_version", "trial");

            String params = jsonObject.toString();

            execute = HttpUtil.createPost(codeUrl)
                    .body(params)
                    .header("Contend-Type", "application/json")
                    .execute();
            InputStream inputStream = execute.bodyStream();
            //文件上传,返回小程序码url
            qrCodeUrl = fileUploadService.upload(inputStream, IdUtils.fastSimpleUUID()+"_"+key+".png");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (execute != null){
                execute.close();
            }
        }
        return qrCodeUrl;
    }*/

    /**
     * 生成二维码
     *
     * @param content  二维码内容
     * @param qrConfig 二维码高纠错配置
     * @return 图片byte[]
     */
   /* public byte[] createQrCode(String content, QrConfig qrConfig) {

        if (null == qrConfig || ObjectUtils.isEmpty(qrConfig)) {
            qrConfig = new QrConfig();
            // 高纠错级别
            qrConfig.setErrorCorrection(ErrorCorrectionLevel.H);
        }

        ByteArrayOutputStream baos = null;
        byte[] imageBytes = null;
        try {
            // 生成二维码并转换成字节数组
            BufferedImage image = QrCodeUtil.generate(content, qrConfig);
            baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            baos.flush();
            imageBytes = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imageBytes;
    }*/
}
