package cn.com.poc.user.builder;

import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.equity.aggregate.MemberEquityService;
import cn.com.poc.user.dto.MemberLoginRequestDto;
import cn.com.poc.user.entity.MemberInfoEntity;
import cn.com.poc.user.query.CheckMemberInfoQueryCondition;
import cn.com.poc.user.query.CheckMemberInfoQueryItem;
import cn.com.poc.user.service.BizMemberInfoService;
import cn.com.yict.framemax.core.config.Config;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.data.model.BaseModel;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.googleapis.auth.oauth2.GooglePublicKeysManager;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.v2.ApacheHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author alex.yao
 * @date 2024/12/24
 */
@Component
public class GoogleLoginChannel implements LoginChannelService {

    private final Logger logger = LoggerFactory.getLogger(GoogleLoginChannel.class);

    private static final String CLIENT_ID = Config.get("google.client.id");

    private final HttpTransport transport = new ApacheHttpTransport();

    private final JsonFactory jsonFactory = new GsonFactory();

    @Resource
    private BizMemberInfoService bizMemberInfoService;

    @Resource
    private MemberEquityService memberEquityService;

    @Resource
    private FmxParamConfigService fmxParamConfigService;

    @Override
    public BaseModel doLogin(MemberLoginRequestDto memberLoginRequest) throws Exception {
        GooglePublicKeysManager.Builder builder = new GooglePublicKeysManager.Builder(transport, jsonFactory);
        builder.setPublicCertsEncodedUrl("https://google-api.gsstcloud.com/oauth2/v1/certs");
        GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(builder.build())
                .setAudience(Collections.singletonList(CLIENT_ID))
                .build();

        String idTokenString = memberLoginRequest.getAuthCode();
        GoogleIdToken idToken = verifier.verify(idTokenString);
        if (idToken != null) {
            Payload payload = idToken.getPayload();
            String userId = payload.getSubject();
            logger.info("User ID: {}", userId);
            String email = payload.getEmail();
            String name = (String) payload.get("name");
            String pictureUrl = (String) payload.get("picture");
            MemberInfoEntity result = bizMemberInfoService.getMemberEntityByAccount(email);
            if (result == null) {
                CheckMemberInfoQueryCondition condition = new CheckMemberInfoQueryCondition();
                condition.setEmail(email);
                List<CheckMemberInfoQueryItem> checkMemberInfoQueryItems = bizMemberInfoService.checkMemberInfoIsExist(condition);
                if (CollectionUtils.isEmpty(checkMemberInfoQueryItems)) {//用户没有注册过 需要注册
                    result = register(email, name, pictureUrl);
                } else {  //用户已经注册过 直接登录
                    CheckMemberInfoQueryItem checkMemberInfoQueryItem = checkMemberInfoQueryItems.get(0);
                    Integer memberId = checkMemberInfoQueryItem.getMemberId();
                    result = bizMemberInfoService.getById(memberId);
                }
            }
            return result;
        } else {
            logger.error("Google id token is null");
            throw new I18nMessageException("exception/system.error");
        }

    }

    private MemberInfoEntity register(String email, String name, String avatar) {
        MemberInfoEntity result;
        MemberInfoEntity memberInfoEntity = new MemberInfoEntity();
        memberInfoEntity.setAccount(email);
        memberInfoEntity.setNickName(name);
        memberInfoEntity.setEmail(email);
        if (StringUtils.isBlank(avatar)) {
            avatar = fmxParamConfigService.getParam("member.default.avatar");
        }
        memberInfoEntity.setAvatarUrl(avatar);
        result = bizMemberInfoService.createMemberInfo(memberInfoEntity);
        try {
            memberEquityService.initMemberEquity(result.getMemberId().longValue());
        } catch (Exception e) {
            throw new I18nMessageException("exception/system.error");
        }
        return result;
    }

}
