package com.skr.mdm.authentication.user.qr;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.skr.mdm.dao.AuUserDao;
import com.skr.mdm.dto.LoginUserDTO;
import com.skr.mdm.entity.AuUserDO;
import com.skr.mdm.enums.DeleteStateEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author nfq
 * @date 2020/7/15 14:27
 */
@Service
public class UsernameDetailsServiceImpl implements UserDetailsService {

    private Integer companyId;

    @Autowired
    private AuUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username) || companyId == null) {
            throw new UsernameNotFoundException("username为空:" + username + "companyId:" + companyId);
        }
        AuUserDO userDO = new LambdaQueryChainWrapper<>(userDao)
                .eq(AuUserDO::getPhoneNumber, username)
                .eq(AuUserDO::getIsDelete, DeleteStateEnum.NON_DELETE.getState())
                .eq(AuUserDO::getCompanyId, companyId)
                .one();
        if (userDO == null) {
            throw new UsernameNotFoundException("用户不存在:" + username + "companyId:" + companyId);
        }
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        BeanUtils.copyProperties(userDO, loginUserDTO);
        loginUserDTO.setUserId(userDO.getId());
        loginUserDTO.setDepartmentId(userDO.getDepartmentId());
        loginUserDTO.setDepartmentName(userDO.getDepartmentName());
        loginUserDTO.setPassword(userDO.getPassword());
        return loginUserDTO;
    }

    public void setCompanyId(Integer companyId) {
        this.companyId = companyId;
    }
}
