package com.yami.shop.security.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yami.shop.config.WxConfig;
import com.yami.shop.security.api.service.AppLoginService;
import com.yami.shop.security.api.service.YamiUserDetailsService;
import com.yami.shop.security.comment.enums.App;
import com.yami.shop.security.comment.exception.WxErrorException;
import com.yami.shop.security.comment.model.AppConnect;
import com.yami.shop.security.comment.service.AppConnectService;
import com.yami.shop.security.comment.token.AuthenticationToken;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;


/**
 * 微信公众号登陆
 * @author LGH
 */
@Component
@AllArgsConstructor
public class MpAppLoginServiceImpl implements AppLoginService {

    private final YamiUserDetailsService yamiUserDetailsService;

    private final WxConfig wxConfig;

    private final AppConnectService appConnectService;

    @Override
    public UserDetails loginAndGetUserDetails(AuthenticationToken authentication) {
        String code = authentication.getPrincipal();
        try {

            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxConfig.getWxMpService().getOAuth2Service().getAccessToken(code);
            AppConnect appConnect = appConnectService.getByBizUserId(wxMpOAuth2AccessToken.getOpenId(), authentication.getAppType());
            if (appConnect == null) {
                appConnect = new AppConnect();

                WxMpUser wxMpUser = wxConfig.getWxMpService().getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
                appConnect.setAppId(authentication.getAppType());
                appConnect.setNickName(wxMpUser.getNickname());
                appConnect.setImageUrl(wxMpUser.getHeadImgUrl());
                appConnect.setBizUserId(wxMpUser.getOpenId());
                appConnect.setBizUnionid(wxMpUser.getUnionId());
                appConnectService.save(appConnect);
            }
            return yamiUserDetailsService.loadUserByAppConnect(appConnect);
        } catch (me.chanjar.weixin.common.error.WxErrorException e) {
            throw new WxErrorException(e.getMessage());
        }
    }

    @Override
    public App getApp() {
        return App.MP;
    }
}
