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.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.SocialLoginBody;
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端微信公众号认证策略
 * 处理微信公众号环境下的OAuth2登录逻辑
 * 依赖 justauth.type.wechat_mp 配置项
 *
 * @author pengles
 */
@Slf4j
@Service("app_wechat_mp" + IAppAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class AppWechatMpAuthStrategy implements IAppAuthStrategy {

    private final SocialProperties socialProperties;
    private final AppSocialAuthService appSocialAuthService;

    /**
     * 微信公众号登录核心逻辑
     *
     * @param body   登录请求体，包含 socialCode 和 socialState
     * @param client 客户端配置
     * @return 登录结果 LoginVo
     */
    @Override
    public LoginVo login(String body, SysClientVo client) {
        SocialLoginBody loginBody = JsonUtils.parseObject(body, SocialLoginBody.class);
        ValidatorUtils.validate(loginBody);

        String code = loginBody.getSocialCode();
        String state = loginBody.getSocialState();

        // 使用SocialUtils获取微信公众号的AuthRequest
        // 对应 application.yml 中 justauth.type.wechat_mp 的配置
        AuthRequest authRequest = SocialUtils.getAuthRequest("wechat_mp", socialProperties);
        if (authRequest == null) {
            throw new UserException("未配置微信公众号登录");
        }

        // 构造回调参数
        AuthCallback authCallback = new AuthCallback();
        authCallback.setCode(code);
        authCallback.setState(state);
        // 执行第三方登录请求，换取 Access Token 和 User Info
        AuthResponse<AuthUser> response = authRequest.login(authCallback);

        String openid;
        String unionId = null;
        if (response.ok()) {
            AuthUser authUser = response.getData();
            openid = authUser.getUuid();
            if (authUser.getToken() != null) {
                unionId = authUser.getToken().getUnionId();
            }
        } else {
            throw new UserException("第三方登录失败，原因：" + response.getMsg());
        }

        // 根据 OpenId 或 UnionId 查找系统用户
        AppUserVo user = loadUserByWxId("wechat_mp", 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
     * @param platform 平台标识（wechat_mp / wechat_open / wechat_miniprogram）
     * @param openid   微信 openId
     * @param unionId  微信 unionId（可能为空）
     */
    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);
    }
}
