package com.mcwl.framework.web.service;

import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.domain.model.LoginUser;
import com.mcwl.common.enums.UserStatus;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.MessageUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.framework.security.core.OtherUserDetailsService;
import com.mcwl.system.service.ISysUserService;
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 mcwl
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService, OtherUserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    private int num = 0;


    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = null;
        log.info("当前num:{}",num);
        if (num == 0 ){
            user = userService.selectUserByUserName(username);
        }else {
            user = userService.selectUserByPhone(username);
        }

        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            num = 0;
            throw new ServiceException(MessageUtils.message("user.not.exists"), HttpStatus.SHOW_ERROR_MSG);
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            num = 0;
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"), HttpStatus.SHOW_ERROR_MSG);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            num = 0;
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"), HttpStatus.SHOW_ERROR_MSG);
        }

//        passwordService.validate(user);
        if (num == 0) {
            passwordService.validate(user);
        }
        num = 0;

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

    @Override
    public UserDetails otherLoadUser(String username, int num) throws UsernameNotFoundException {
        this.num = num;
        return loadUserByUsername(username);
    }
}
