package com.jdc.jdcproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jdc.jdcproject.entity.Users;
import com.jdc.jdcproject.exceptionhandler.JdcException;
import com.jdc.jdcproject.mapper.UsersMapper;
import com.jdc.jdcproject.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdc.jdcproject.utils.JwtUtils;
import com.jdc.jdcproject.utils.MD5;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author haoyanlu
 * @since 2025-04-26
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Override
    public String login(Users user) {
        System.out.println(user.toString());
        String password = user.getPassword();
        String name = user.getUsername();
        String phone = user.getUsername();

        if (user.getUsername().matches("^\\d{11}$")) {
            phone = user.getUsername();
        } else {
            name = user.getUsername();
        }

        if ((StringUtils.isEmpty(phone) ^ StringUtils.isEmpty(name)) || StringUtils.isEmpty(password)) {
            throw new JdcException(20001, "登陆失败");
        }

        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", name).or().eq("tel", phone);
        Users users = baseMapper.selectOne(wrapper);

        if (users == null) {
            throw new JdcException(20001, "登陆失败");
        }

        // 增加锁定判断
        if (users.getLockdatetime() != null && users.getLockdatetime().isAfter(LocalDateTime.now())) {
            throw new JdcException(20001, "账号已锁定,请稍后再试");
        }

        // 校验密码
        if (!MD5.encrypt(password).equals(users.getPassword())) {
            // 密码错误,增加错误次数
            Integer errorCount = users.getErrlogincount() == null ? 0 : users.getErrlogincount();
            errorCount++;

            users.setErrlogincount(errorCount);

            // 如果错误次数达到5次,锁定账户
            if (errorCount >= 5) {
                users.setLockdatetime(LocalDateTime.now().plusMinutes(30));
            }

            baseMapper.updateById(users); // 保存用户状态

            throw new JdcException(20001, "登陆失败");
        }

        // 登录成功,清除错误次数和锁定时间
        users.setErrlogincount(0);
        users.setLockdatetime(null);
        baseMapper.updateById(users);

        String token = JwtUtils.getJwtToken(users.getId(), users.getUsername());
        return token;
    }
}