package com.seer.teach.user.app.auth.service.strategy;

import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.mp.api.WechatOfficialAccountApi;
import com.seer.teach.mp.api.resp.WxOAuth2AccessTokenDTO;
import com.seer.teach.user.app.auth.LoginType;
import com.seer.teach.user.app.auth.request.LoginParam;
import com.seer.teach.user.app.auth.service.LoginStrategy;
import com.seer.teach.user.app.auth.service.LoginUser;
import com.seer.teach.user.entity.UserAuthEntity;
import com.seer.teach.user.entity.UserEntity;
import com.seer.teach.user.service.IUserAuthService;
import com.seer.teach.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 微信公众号登录策略
 */
@Slf4j
@Service
public class OfficialAccountLoginStrategy extends AbstractLoginStrategy implements LoginStrategy {

    @Autowired
    private WechatOfficialAccountApi wechatOfficialAccountApi;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserAuthService userAuthService;

    @Override
    public LoginType getType() {
        return LoginType.WECHAT_OAUTH;
    }

    @Override
    public LoginUser authenticate(LoginParam request) {
        log.info("微信公众号登录：{}",request);
        WxOAuth2AccessTokenDTO wxOAuth2AccessToken = wechatOfficialAccountApi.getUserWxOAuth2AccessToken(request.getAppId(), request.getJsCode());
        log.debug("获取用户信息：{}",wxOAuth2AccessToken);
        AssertUtils.notNull(wxOAuth2AccessToken, ResultCodeEnum.WX_OAUTH_USED_ERROR);
        String userOpenId = wxOAuth2AccessToken.getOpenId();
        UserAuthEntity userAuth = userAuthService.getOneByOpenId(userOpenId);

        if(Objects.isNull( userAuth)){
            UserEntity user = new UserEntity();
            user.setOpenId(userOpenId);
            boolean saved = userService.save(user);
            log.info("保存用户信息：{}", saved);

            boolean userAuthSaved = saveUserAuth(getType().getCode(), user.getId(), wxOAuth2AccessToken, request.getAppId());
            log.info("保存用户授权信息：{}", userAuthSaved);
            return new LoginUser(user.getId(),-1);
        }else{
            userAuth.setAppId(request.getAppId());
            updateUserAuth(userAuth);
            LoginUser loginUser = new LoginUser(userAuth.getUserId());
            return loginUser;
        }
    }
}