package org.dromara.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import org.dromara.app.domain.AppLoginUser;
import org.dromara.member.domain.vo.AppUserVo;
import org.dromara.member.service.AppSocialAuthService;
import org.dromara.app.service.IAppAuthStrategy;
import org.dromara.common.core.domain.model.XcxLoginBody;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.social.config.properties.SocialProperties;
import org.dromara.common.social.utils.SocialUtils;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.web.domain.vo.LoginVo;
import org.springframework.stereotype.Service;

/**
 * App端微信小程序认证策略
 * 支持微信小程序登录，通过微信小程序授权码获取用户信息并完成登录
 *
 * @author pengles
 */
@Slf4j
@Service("app_wechat_miniprogram" + IAppAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class AppWechatMiniprogramAuthStrategy implements IAppAuthStrategy {

    private final SocialProperties socialProperties;
    private final AppSocialAuthService appSocialAuthService;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        XcxLoginBody loginBody = JsonUtils.parseObject(body, XcxLoginBody.class);
        ValidatorUtils.validate(loginBody);

        // xcxCode 为小程序调用 wx.login 授权后获取
        String xcxCode = loginBody.getCode();
        // 多个小程序识别使用
        String appid = loginBody.getAppid();

        // 校验 appid + appsecret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
        // 使用SocialUtils获取微信小程序的AuthRequest
        AuthRequest authRequest = SocialUtils.getAuthRequest("wechat_miniprogram", socialProperties);
        if (authRequest == null) {
            throw new UserException("未配置微信小程序登录");
        }
        AuthCallback authCallback = new AuthCallback();
        authCallback.setCode(xcxCode);
        AuthResponse<AuthUser> response = authRequest.login(authCallback);

        String openid = null;
        String unionId = null;
        if (response.ok()) {
            AuthToken token = response.getData().getToken();
            openid = token.getOpenId();
            // 微信小程序只有关联到微信开放平台下之后才能获取到 unionId，因此unionId不一定能返回。
            unionId = token.getUnionId();
        } else {
            throw new UserException("第三方登录失败，原因：" + response.getMsg());
        }

        AppUserVo user = loadUserByWxId("wechat_miniprogram", openid, unionId);
        if (ObjectUtil.isNull(user)) {
            throw new UserException("登录失败，请先绑定用户账号");
        }

        // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
        AppLoginUser loginUser = new AppLoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getUserName());
        loginUser.setNickname(user.getNickName());
        loginUser.setUserType("app");
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());

        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        loginVo.setOpenid(openid);
        return loginVo;
    }

    /**
     * 通过微信标识加载用户信息，优先 unionId，回退 openId
     */
    private AppUserVo loadUserByWxId(String platform, String openid, String unionId) {
        if (ObjectUtil.isNotEmpty(unionId)) {
            AppUserVo byUnion = appSocialAuthService.selectUserByPlatformAndUnionId(platform, unionId);
            if (ObjectUtil.isNotNull(byUnion)) {
                return byUnion;
            }
        }
        return appSocialAuthService.selectUserByPlatformAndOpenId(platform, openid);
    }

}
