package com.hs.admin.service.impl;

import com.hs.admin.common.utils.TokenUtil;
import com.hs.admin.mapper.DicOrgMapper;
import com.hs.admin.mapper.SysUserMapper;
import com.hs.admin.model.DicOrg;
import com.hs.admin.model.SysUser;
import com.hs.admin.service.LoginService;
import com.hs.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userServiceImpl;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private DicOrgMapper dicOrgMapper;

    @Override
    public LoginInfo login(String logName,String password,String ip) {

        LoginInfo loginInfo = new LoginInfo();

        SysUser user = userServiceImpl.findByLoginName(logName);
        if(user != null && user.getPassword().equals(password)){
            String token = TokenUtil.getToken(password,user);
            //修改ip以及最后登录时间
            user.setLastIp(ip);
            user.setLastTime(new Date());
            sysUserMapper.updateByPrimaryKey(user);

            user.setPassword(null);
            loginInfo.setToken(token);
            loginInfo.setUser(user);
            //查询用户机构
            List<DicOrg> orgList = dicOrgMapper.selectByUser(user.getId());
            loginInfo.setOrg(orgList);
        }
        return loginInfo;
    }

    public String refreshToken(String oldToken) {
        return TokenUtil.refresh(oldToken);
    }
}
