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

import cn.qinys.platform.base.exceptions.BizException;
import cn.qinys.platform.base.redis.RedisKeyEnum;
import cn.qinys.platform.base.security.utils.CurrentUtils;
import cn.qinys.platform.base.service.AbstractLoginService;
import cn.qinys.platform.base.service.ICaptchaService;
import cn.qinys.platform.base.utils.RedisUtils;
import cn.qinys.platform.base.vo.LoginUserInfo;
import cn.qinys.platform.entity.wishing.WishingUser;
import cn.qinys.platform.mobile.mapper.UserWishMapper;
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.resp.UserWishSummaryResp;
import cn.qinys.platform.mobile.service.LoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

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


    @Resource
    private ICaptchaService captchaService;
    @Resource
    private WishingUserMapper userMapper;
    @Resource
    private UserWishMapper wishMapper;
    @Resource
    RedisUtils redisUtils;


    @Override
    public LoginResp login(LoginReq query) {

        // 校验验证码
        String codeKey = RedisKeyEnum.CAPTCHA.getCode() + query.getCaptchaKey();
        String code = (String) redisUtils.get(codeKey);
        if (!StringUtils.hasLength(code)) {
            throw new BizException("图片验证码已过期");
        }
        if (!code.equalsIgnoreCase(query.getCaptcha())) {
            throw new BizException("图片验证码不正确");
        }

        WishingUser user = userMapper.selectByMobile(query.getMobile());
        if (user == null) {
            //throw new BizException("用户不存在");
            user = this.createWishingUser(query.getMobile());
        }
        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());
        resp.setIsAdmin(user.getIsAdmin());
        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;
    }

    @Override
    public void logout() {
        try {
            LoginUserInfo currentUserInfo = CurrentUtils.getCurrentUserInfo();
            this.kicKOut(currentUserInfo.getWxId());
            log.info("user logout: {}", currentUserInfo);
        } catch (Exception e) {
            log.error("user logout", e);
        }
    }

    @Override
    public UserWishSummaryResp wishSummary() {
        Integer userId = Integer.valueOf(CurrentUtils.getCurrentUserId());
        return wishMapper.selectWishSummary(userId);
    }


    private WishingUser createWishingUser(String mobile) {
        WishingUser user = new WishingUser();
        user.setMobile(mobile);
        user.setNickname(this.createRandUerName());
        user.setLoginCount(0);
        user.setAvatar("");
        user.setIsAdmin(1);
        userMapper.insert(user);
        return user;
    }

    public String createRandUerName() {
        // 常见单字姓氏列表（可根据需要扩充）
        String[] surnames = new String[]{"李","王","张","刘","陈","杨","黄","赵","吴","周","徐","孙","胡","朱","高","林","何","郭","马","罗","梁","宋","郑","谢","唐"};

        // 常见单字名字用字（男女通用，列表可扩充）
        String[] nameChars = new String[]{
                "伟","芳","娜","秀","英","敏","静","丽","强","磊",
                "洋","勇","艳","杰","娟","涛","明","超","平","刚",
                "桂","雪","飞","琳","玲","丹","萍","辉","建","华",
                "晶","燕","晨","晨","鑫","彤","坤","怡","珊","瑶"
        };

        ThreadLocalRandom rnd = ThreadLocalRandom.current();
        String surname = surnames[rnd.nextInt(surnames.length)];

        // 给名长度 1 或 2
        int givenLen = rnd.nextInt(1, 3); // 1 或 2
        StringBuilder givenName = new StringBuilder();
        for (int i = 0; i < givenLen; i++) {
            givenName.append(nameChars[rnd.nextInt(nameChars.length)]);
        }

        return surname + givenName;
    }

}
