package com.cyksj.service.authorization.impl;

import com.cyksj.common.util.Codec;
import com.cyksj.config.WeChatConfig;
import com.cyksj.config.wxlogin.WxOpenPlatYHLXLoginConfig;
import com.cyksj.enums.WeChatAuthRedirectUrl;
import com.cyksj.model.dto.JsSdkTicket;
import com.cyksj.service.authorization.AuthorizationService;
import com.cyksj.service.wechat.WeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author chan
 * @className AuthorizationServiceImpl
 * @description 授权服务
 * @date 2021/10/8 1:58 下午
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AuthorizationServiceImpl implements AuthorizationService {

    private final WeChatService weChatService;

    private final WeChatConfig weChatConfig;

    private final WxOpenPlatYHLXLoginConfig wxOpenPlatYHLXLoginConfig;


    @Override
    public String createUrl(String state, String authType) {
        return weChatService.createUrl(state,weChatConfig.getDomain() + WeChatAuthRedirectUrl.get(authType).getUrl()
                ,weChatConfig.getAppid(),WeChatAuthRedirectUrl.get(authType).getScope());
    }

    @Override
    public JsSdkTicket getJsTicket(String appId, String url) throws Exception {

        // 获取js-ticket
        String ticket = weChatService.getJsTicket(appId);

        // 生成js-sdk权限验证 签名
        JsSdkTicket jsSdkTicket = new JsSdkTicket();
        jsSdkTicket.setAppid(appId);
        jsSdkTicket.setNonceStr("chan");
        jsSdkTicket.setTimestamp(System.currentTimeMillis());

        String str = "jsapi_ticket=" + ticket +
                "&noncestr=" + jsSdkTicket.getNonceStr() +
                "&timestamp=" + jsSdkTicket.getTimestamp() +
                "&url=" + url;

        String sha1Hex = Codec.DoDigest.custom()
                .setAlgorithm(Codec.DoDigest.Algorithm.SHA1).setStringData(str).toHexString();
        jsSdkTicket.setSignature(sha1Hex);
        return jsSdkTicket;
    }

    @Override
    public String createWxAuthLoginUrl(String state, String appId, String redirectUrl) {
        return weChatService.createWxAuthLoginUrl(state, appId, URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8));
    }

}
