package com.xy.service;

import cn.hutool.core.util.IdUtil;
import com.xy.dto.WxAuthorizeDto;
import com.xy.utils.R;
import com.xy.utils.WxMaUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Formatter;

/**
 * 微信授权 接口实现
 */
@Service
@AllArgsConstructor
@Api(tags = "微信授权")
public class WxAuthorizeServiceImpl implements WxAuthorizeService {

    @Override
    @SneakyThrows
    @ApiOperation("jssdk工具签名")
    public R<WxAuthorizeDto.JssdkSignVo> jssdkSign(WxAuthorizeDto.JssdkSign jssdkSign) {
        String jsapiTicket = WxMaUtils.switchoverTo(jssdkSign.getAppId(), jssdkSign.getAppId()).getJsapiService().getJsapiTicket();
        String nonceStr = IdUtil.simpleUUID();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String str = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + jssdkSign.getUrl();
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(str.getBytes(StandardCharsets.UTF_8));
        Formatter formatter = new Formatter();
        for (byte b : crypt.digest()) {
            formatter.format("%02x", b);
        }
        String signature = formatter.toString();
        formatter.close();
        WxAuthorizeDto.JssdkSignVo jssdkSignVo = new WxAuthorizeDto.JssdkSignVo()
                .setAppId(jssdkSign.getAppId())
                .setTimestamp(timestamp)
                .setNonceStr(nonceStr)
                .setSignature(signature);
        return R.ok(jssdkSignVo);
    }
}
