package ink.wgink.login.base.service.user;

import ink.wgink.common.enums.RoleDataRightEnum;
import ink.wgink.exceptions.SaveException;
import ink.wgink.exceptions.UpdateException;
import ink.wgink.interfaces.role.IRoleDataRightBaseService;
import ink.wgink.login.base.service.log.ILoginLogService;
import ink.wgink.pojo.bos.LoginUser;
import ink.wgink.pojo.dtos.role.RoleSimpleDTO;
import ink.wgink.service.department.service.IDepartmentService;
import ink.wgink.service.department.service.IDepartmentUserService;
import ink.wgink.service.user.service.IUserService;
import ink.wgink.util.UUIDUtil;
import ink.wgink.util.date.DateUtil;
import ink.wgink.util.request.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: UserLoginService
 * @Description: 用户登录业务
 * @Author: WangGeng
 * @Date: 2020/5/25 3:32 下午
 * @Version: 1.0
 **/
@Service
public class UserLoginService {

    private static final Logger LOG = LoggerFactory.getLogger(UserLoginService.class);
    @Autowired
    private IUserService userService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IDepartmentUserService departmentUserService;
    @Autowired
    private ILoginLogService loginLogService;
    @Autowired(required = false)
    private IRoleDataRightBaseService roleDataRightBaseService;

    /**
     * 设置人员数据权限
     *
     * @param loginUser
     * @throws Exception
     */
    public void setUserDataAuthority(LoginUser loginUser) throws AuthenticationException {
        LOG.debug("取出所属部门列表");
        loginUser.setBaseDepartmentIds(departmentService.listRootId(loginUser.getDepartments()));
        LOG.debug("权限信息，判断数据权限");
        String roleDataAuthority = getDataRight(loginUser.getRoles());
        loginUser.setDataRight(roleDataAuthority);
        if (StringUtils.equals(RoleDataRightEnum.DEPARTMENT.getValue(), roleDataAuthority)) {
            LOG.debug("角色拥有部门的数据权限");
            List<String> departmentIds = new ArrayList<>();
            loginUser.getDepartments().forEach(departmentPO -> {
                departmentIds.add(departmentPO.getDepartmentId());
            });
            loginUser.setDataRightUserIds(departmentUserService.listUserId(departmentIds));
        } else if (StringUtils.equals(RoleDataRightEnum.CUSTOM.getValue(), roleDataAuthority)) {
            if (roleDataRightBaseService != null) {
                LOG.debug("角色拥有自定义数据权限");
                List<String> roleIds = new ArrayList<>();
                loginUser.getRoles().forEach(rolePO -> {
                    roleIds.add(rolePO.getRoleId());
                });
                loginUser.setDataRightUserIds(roleDataRightBaseService.listUserId(roleIds));
            }
        }
    }

    /**
     * 更新用户登录信息
     *
     * @param userId
     */
    public void updateUserLoginInfo(String userId, String userName, String loginType) {
        LOG.debug("更新登录信息");
        String address = RequestUtil.getRequestIp();
        String currentTime = DateUtil.getTime();
        updateLoginInfo(userId, address, currentTime);
        LOG.debug("新增登录日志");
        saveLoginLogger(userId, userName, loginType, address, currentTime);
    }

    /**
     * 登录日志
     *
     * @param userId
     * @param userName
     * @param loginType
     * @param address
     * @param currentTime
     * @throws SaveException
     */
    private void saveLoginLogger(String userId, String userName, String loginType, String address, String currentTime) throws SaveException {
        Map<String, Object> params = new HashMap<>(12);
        params.put("loginLogId", UUIDUtil.getUUID());
        params.put("loginAddress", address);
        params.put("loginType", loginType);
        params.put("gmtCreate", currentTime);
        params.put("creator", userId);
        params.put("creatorName", userName);
        loginLogService.save(params);
    }

    /**
     * 更新登录信息
     *
     * @param userId
     * @param address
     * @param currentTime
     * @throws UpdateException
     */
    private void updateLoginInfo(String userId, String address, String currentTime) throws UpdateException {
        Map<String, Object> params = new HashMap<>(10);
        params.put("userId", userId);
        params.put("lastLoginAddress", address);
        params.put("lastLoginTime", currentTime);
        params.put("gmtModified", currentTime);
        params.put("modifier", userId);
        userService.updateLoginInfo(params);
    }

    /**
     * 获取数据权限
     *
     * @param roles
     * @return
     */

    public String getDataRight(List<RoleSimpleDTO> roles) {
        String roleDataAuthority = RoleDataRightEnum.SELF.getValue();
        for (RoleSimpleDTO roleSimplePO : roles) {
            if (StringUtils.equals(RoleDataRightEnum.ALL.getValue(), roleSimplePO.getRoleDataRight())) {
                roleDataAuthority = RoleDataRightEnum.ALL.getValue();
                break;
            }
            if (StringUtils.equals(RoleDataRightEnum.DEPARTMENT.getValue(), roleSimplePO.getRoleDataRight())) {
                roleDataAuthority = RoleDataRightEnum.DEPARTMENT.getValue();
                break;
            }
            if (StringUtils.equals(RoleDataRightEnum.CUSTOM.getValue(), roleSimplePO.getRoleDataRight())) {
                roleDataAuthority = RoleDataRightEnum.CUSTOM.getValue();
                break;
            }
        }
        return roleDataAuthority;
    }

}
