package com.pannk.mms.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pannk.mms.common.base.Result;
import com.pannk.mms.common.utils.RedisUtil;
import com.pannk.mms.common.utils.TokenUtil;
import com.pannk.mms.modules.sys.dao.SysUserMapper;
import com.pannk.mms.modules.sys.entity.SysRoleEntity;
import com.pannk.mms.modules.sys.entity.SysUserEntity;
import com.pannk.mms.modules.sys.service.SysRoleService;
import com.pannk.mms.modules.sys.service.SysUserService;
import com.pannk.mms.modules.sys.vo.LoginForm;
import com.pannk.mms.modules.sys.vo.SysUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 系统用户服务
 * Created by wolf on 20-11-2.
 */
@Slf4j
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysRoleService sysRoleService;


    @Override
    public SysUserEntity queryByUserName(String userName) {
        return baseMapper.queryByUserName(userName);
    }

    @Override
    public Result login(LoginForm loginForm) {
        SysUserEntity sysUserEntity = queryByUserName(loginForm.getUserName());
        if (sysUserEntity == null || !sysUserEntity.getPassword().equals(loginForm.getPassword())) {
            return Result.error("账号或密码不正确");
        }
        if (sysUserEntity.getStatus() == 1) {
            return Result.error("账号被锁定,请联系管理员处理");
        }
        String token = TokenUtil.generateToken();
        redisUtil.set(sysUserEntity.getCode(), token);
        return Result.success(token);
    }

    @Override
    public SysUserInfo queryUserInfo(Long id) {
        SysUserEntity sysUserEntity = getById(id);
        SysUserInfo sysUserInfo = new SysUserInfo();
        if (sysUserEntity == null) {
            return null;
        }
        List<SysRoleEntity> roles = sysRoleService.queryUserRole(sysUserEntity.getId());
        sysUserInfo.setRoles(roles);
        sysUserInfo.setAvatar("avatar");
        sysUserInfo.setIntroduction("This is a user info");
        sysUserInfo.setName(sysUserEntity.getFullName());
        return sysUserInfo;
    }
}
