package top.continew.admin.user.service.Impl;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import me.ahoo.cosid.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import top.continew.admin.common.context.RoleContext;
import top.continew.admin.common.context.UserContext;
import top.continew.admin.common.context.UserContextHolder;
import top.continew.admin.common.context.UserExtraContext;
import top.continew.admin.user.model.entity.TgUser;
import top.continew.admin.user.mapper.TgUserMapper;
import top.continew.admin.user.model.req.AppLoginReq;
import top.continew.admin.user.model.resp.AppLoginResp;
import top.continew.admin.user.service.ITgUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.continew.admin.utils.InviteCodeGenerator;
import top.continew.starter.cache.redisson.util.RedisUtils;
import top.continew.starter.core.validation.CheckUtils;
import top.continew.starter.web.util.SpringWebUtils;

import java.time.LocalDateTime;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * tg用户 服务实现类
 * </p>
 *
 * @author xudm
 * @since 2024-12-14
 */
@Service
public class TgUserServiceImpl extends ServiceImpl<TgUserMapper, TgUser> implements ITgUserService {


    @Override
    public SaTokenInfo tgLogin(AppLoginReq loginReq) {
        LambdaQueryWrapper<TgUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TgUser::getTgId, loginReq.getId());
        TgUser user = getOne(queryWrapper);
        if (ObjUtil.isNull(user)) {
            user = registerToSys(loginReq);
        }
        return this.login(user, loginReq);
    }

    /**
     * 注册用户到系统中
     *
     * @param loginReq
     * @return
     */
    private TgUser registerToSys(AppLoginReq loginReq) {
        TgUser user = TgUser.builder()
                .tgAccount(loginReq.getUsername())
                .tgId(loginReq.getId())
                .avatar(loginReq.getPhotoUrl())
                .firstName(loginReq.getFirstName())
                .lastName(loginReq.getLastName())
                //注册时指定用户的唯一邀请码
                .inviteCode(InviteCodeGenerator.generateInviteCode())
                .languageCode(loginReq.getLanguageCode())
                .ageLimit(Integer.parseInt(loginReq.getAge_limit()))
                .createdTime(LocalDateTime.now())
                .updatedTime(LocalDateTime.now())
                .build();
        if (StrUtil.isNotBlank(loginReq.getShare_code())) {
            //如邀请码不为空 则写入邀请人信息
            LambdaQueryWrapper<TgUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TgUser::getInviteCode, user.getId());
            TgUser inviteUser = getOne(queryWrapper);
            if (ObjUtil.isNotNull(inviteUser)) {
                user.setReferrerId(String.valueOf(inviteUser.getId()));
            }
        }
        this.save(user);
        return user;
    }

    private SaTokenInfo login(TgUser user, AppLoginReq loginReq) {
        Long userId = user.getId();
        UserContext userContext = new UserContext();
        userContext.setId(userId);
        userContext.setUsername(user.getTgAccount());
        // 登录并缓存用户信息
        StpUtil.login(userId, SaLoginConfig.setExtraData(BeanUtil
                .beanToMap(new UserExtraContext(SpringWebUtils.getRequest()))));
        UserContextHolder.setContext(userContext);
        return StpUtil.getTokenInfo();
    }


}
