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


import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.yami.shop.config.WxConfig;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.service.AppLoginService;
import com.yami.shop.security.api.service.YamiUserDetailsService;
import com.yami.shop.security.api.util.SecurityUtils;
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 org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;


/**
 * 小程序登陆
 * @author LGH
 */
@Component
@AllArgsConstructor
public class MaAppLoginServiceImpl 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 {

            WxMaJscode2SessionResult session = wxConfig.getWxMaService().getUserService().getSessionInfo(code);
            AppConnect appConnect = appConnectService.getByBizUserId(session.getOpenid(), authentication.getAppType());
            if (appConnect == null) {
                appConnect = new AppConnect();
                appConnect.setAppId(authentication.getAppType());
                appConnect.setBizUserId(session.getOpenid());
                appConnect.setBizUnionid(session.getUnionid());

                appConnectService.save(appConnect);
            }
            YamiUser yamiUser = yamiUserDetailsService.loadUserByAppConnect(appConnect);
            yamiUser.setSessionKey(session.getSessionKey());
            return yamiUser;
        } catch (me.chanjar.weixin.common.error.WxErrorException e) {
            throw new WxErrorException(e.getMessage());
        }
    }

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


}
