package cn.qinys.platform.mobile.service.impl;

import cn.qinys.platform.base.exceptions.BizException;
import cn.qinys.platform.base.service.AbstractLoginService;
import cn.qinys.platform.base.service.ICaptchaService;
import cn.qinys.platform.base.vo.LoginUserInfo;
import cn.qinys.platform.entity.wishing.WishingUser;
import cn.qinys.platform.mobile.mapper.WishingUserMapper;
import cn.qinys.platform.mobile.req.LoginReq;
import cn.qinys.platform.mobile.resp.CaptchaResp;
import cn.qinys.platform.mobile.resp.LoginResp;
import cn.qinys.platform.mobile.service.LoginService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author lie tan
 * @description
 * @date 2026-06-06 13:35
 **/
@Service
public class LoginServiceImpl extends AbstractLoginService implements LoginService {


    @Resource
    private ICaptchaService captchaService;
    @Resource
    private WishingUserMapper userMapper;


    @Override
    public LoginResp login(LoginReq query) {
        WishingUser user = userMapper.selectByMobile(query.getMobile());
        if (user == null) {
            throw new BizException("用户不存在");
        }
        user.setLastLoginAt(LocalDateTime.now());
        user.setLoginCount(user.getLoginCount() + 1);
        userMapper.updateById(user);

        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String wxId = "wx_" + user.getMobile();
        LoginUserInfo userInfo = new LoginUserInfo();
        userInfo.setId(String.valueOf(user.getId()));
        userInfo.setMobile(user.getMobile());
        userInfo.setUsername(user.getNickname());
        userInfo.setWxId(wxId);
        this.setLoginUserInfo(userInfo, token);
        this.kicKOut(wxId);  // 踢人下线
        this.recordToken(wxId, token);
        // 返回前端
        LoginResp resp = new LoginResp();
        resp.setToken(token);
        resp.setMobile(user.getMobile());
        resp.setNickname(user.getNickname());
        resp.setAvatar(user.getAvatar());
        return resp;
    }

    @Override
    public CaptchaResp getCaptcha(String type) {
        Map<String, String> render = captchaService.render(type);
        CaptchaResp resp = new CaptchaResp();
        AtomicReference<String> key = new AtomicReference<>();
        AtomicReference<String> value = new AtomicReference<>();
        render.forEach((k, v) -> {
            key.set(k);
            value.set(v);
        });
        resp.setKey(key.get());
        resp.setValue(value.get());
        return resp;
    }
}
