package com.schoolinout.framework.web.service;

import com.schoolinout.api.mapper.ApiParentMapper;
import com.schoolinout.common.core.domain.entity.ParentLogin;
import com.schoolinout.common.core.domain.model.LoginUser;
import com.schoolinout.common.exception.ServiceException;
import com.schoolinout.common.utils.StringUtils;
import com.schoolinout.common.utils.bean.BeanUtils;
import com.schoolinout.system.domain.Parent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 sakura
 * @date 2024/1/10 11:11:11 Wed
 */
@Service("parentLoginService")
public class ParentLoginUserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ApiParentMapper parentMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Parent selectCondition = new Parent();
        selectCondition.setParentPhone(username);
        Parent parent = parentMapper.selectOnlyOne(selectCondition);//验证登录用户，查询数据库，如果这个mapper定义在自己的模块，引入maven依赖不用我多说吧？
        if (StringUtils.isNull(parent)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        log.info("客户端家长登入：姓名：{}， 电话：{}", parent.getParentName(), parent.getParentPhone());
        return createLoginUser(parent);
    }

    public UserDetails createLoginUser(Parent parent) {
        ParentLogin parentLogin = new ParentLogin();
        BeanUtils.copyBeanProp(parentLogin, parent);
        return new LoginUser(parent.getId(), parentLogin);
    }
}
