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 lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
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.model.req.AppLoginReq;
import top.continew.admin.user.service.AppLoginService;
import top.continew.admin.user.service.ITgUserService;
import top.continew.admin.utils.InviteCodeGenerator;
import top.continew.starter.web.util.SpringWebUtils;

import java.time.LocalDateTime;

@Service
@AllArgsConstructor
public class AppLoginServiceImpl implements AppLoginService {

    private final ITgUserService userService;

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

    @Override
    public 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())
                .createdTime(LocalDateTime.now())
                .updatedTime(LocalDateTime.now())
                .build();
        if (StrUtil.isNotBlank(loginReq.getAge_limit())) {
            user.setAgeLimit(Integer.parseInt(loginReq.getAge_limit()));
        }
        if (StrUtil.isNotBlank(loginReq.getShare_code())) {
            //如邀请码不为空 则写入邀请人信息
            LambdaQueryWrapper<TgUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TgUser::getInviteCode, loginReq.getShare_code());
            TgUser inviteUser = userService.getOne(queryWrapper);
            if (ObjUtil.isNotNull(inviteUser)) {
                user.setReferrerId(String.valueOf(inviteUser.getId()));
            }
            user.setPassengerFlowWay(2);
        }
        userService.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);
        //TODO 记录登录时间以及ip等信息
        return StpUtil.getTokenInfo();
    }
}
