package com.ruoyi.generator.service.front;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.front.FrontUser;
import com.ruoyi.generator.domain.front.dto.FrontRegisterBody;
import com.ruoyi.generator.mapper.front.FrontUserMapper;

@Service
public class FrontUserServiceImpl implements IFrontUserService
{
    @Autowired
    private FrontUserMapper frontUserMapper;

    @Override
    public FrontUser selectByUsername(String username)
    {
        return frontUserMapper.selectFrontUserByUsername(username);
    }

    @Override
    public FrontUser selectById(Long userId)
    {
        return frontUserMapper.selectFrontUserById(userId);
    }

    @Override
    public int register(FrontRegisterBody body)
    {
        if (body == null || StringUtils.isEmpty(body.getUsername()))
        {
            throw new ServiceException("用户名不能为空");
        }
        if (body.getUsername().length() < 2 || body.getUsername().length() > 50)
        {
            throw new ServiceException("用户名长度必须在2到50个字符之间");
        }
        if (StringUtils.isEmpty(body.getPassword()))
        {
            throw new ServiceException("密码不能为空");
        }
        if (body.getPassword().length() < 5 || body.getPassword().length() > 50)
        {
            throw new ServiceException("密码长度必须在5到50个字符之间");
        }
        if (frontUserMapper.selectFrontUserByUsername(body.getUsername()) != null)
        {
            throw new ServiceException("前台账号已存在");
        }

        FrontUser user = new FrontUser();
        user.setUsername(body.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(body.getPassword()));
        user.setNickname(StringUtils.isEmpty(body.getNickname()) ? body.getUsername() : body.getNickname());
        user.setEmail(body.getEmail());
        user.setPhone(body.getPhone());
        user.setStatus("0");
        user.setDelFlag("0");
        return frontUserMapper.insertFrontUser(user);
    }

    @Override
    public int updateLastLoginTime(Long userId)
    {
        FrontUser user = new FrontUser();
        user.setUserId(userId);
        user.setLastLoginTime(new Date());
        return frontUserMapper.updateFrontUser(user);
    }

    @Override
    public FrontUser selectFrontUserById(Long userId)
    {
        return selectById(userId);
    }

    @Override
    public FrontUser selectFrontUserByUsername(String username)
    {
        return selectByUsername(username);
    }

    @Override
    public List<FrontUser> selectFrontUserList(FrontUser frontUser)
    {
        return frontUserMapper.selectFrontUserList(frontUser);
    }
}
