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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.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;

@Service
public class SmsDetailsServiceImpl implements UserDetailsService {

    private Integer companyId;

    @Autowired
    private AuUserDao auUserDao;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {

        if (companyId == null) {
            throw  new UsernameNotFoundException("companyId为null:" + companyId);
        }
        LambdaQueryWrapper<AuUserDO> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper
                .eq(AuUserDO::getPhoneNumber, phone)
                .eq(AuUserDO::getIsDelete, DeleteStateEnum.NON_DELETE.getState())
                .eq(AuUserDO::getCompanyId, companyId);
        AuUserDO userDO = auUserDao.selectOne(lambdaQueryWrapper);

        if (userDO == null) {
            throw new UsernameNotFoundException("用户手机号不存在:" + phone + "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;
    }
}