package com.red.circle.other.infra.database.rds.service.sys.impl;

import com.google.common.collect.Lists;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.sys.AdministratorAuthDAO;
import com.red.circle.other.infra.database.rds.entity.sys.AdministratorAuth;
import com.red.circle.other.infra.database.rds.service.sys.AdministratorAuthService;
import com.red.circle.other.inner.model.cmd.sys.SysAdministratorAuthCmd;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP管理员权限关系表 服务实现类.
 * </p>
 *
 * @author pengliang
 * @since 2021-03-30
 */
@Service
@RequiredArgsConstructor
public class AdministratorAuthServiceImpl extends
    BaseServiceImpl<AdministratorAuthDAO, AdministratorAuth> implements AdministratorAuthService {

  private final AdministratorAuthDAO administratorAuthDAO;

  @Override
  public List<Long> listUserAuthResourceId(Long userId) {
    return Optional.ofNullable(
            query()
                .select(AdministratorAuth::getResourceId)
                .eq(AdministratorAuth::getUserId, userId)
                .list()
        ).map(administratorAuths -> administratorAuths.stream().map(AdministratorAuth::getResourceId)
            .collect(
                Collectors.toList()))
        .orElse(null);
  }

  @Override
  public boolean existsAuth(Long userId, String authResource) {
    return existsAuth(userId, List.of(authResource));
  }

  @Override
  public boolean existsAuth(Long userId, List<String> authResource) {
    return Objects.equals(administratorAuthDAO.existsAuth(userId, authResource), Boolean.TRUE);
  }

  @Override
  public List<String> listAuthResources(Long userId) {
    return administratorAuthDAO.listAuthResources(userId);
  }

  @Override
  public List<AdministratorAuth> getSysAdministratorAuthByUserId(Long userId) {
    return Optional.ofNullable(query().eq(AdministratorAuth::getUserId, userId).list())
        .orElse(Lists.newArrayList());
  }

  @Override
  public void deleteAndAddAdministratorAuth(SysAdministratorAuthCmd cmd) {
    delete().eq(AdministratorAuth::getUserId, cmd.getUserId()).execute();
    if (CollectionUtils.isNotEmpty(cmd.getResourceList())) {
      List<AdministratorAuth> sysAdministratorAuthList = Lists.newArrayList();
      for (String resource : cmd.getResourceList()) {
        AdministratorAuth sysAdministratorAuth = new AdministratorAuth();
        sysAdministratorAuth.setUserId(cmd.getUserId());
        sysAdministratorAuth.setResourceId(Long.valueOf(resource));
        sysAdministratorAuthList.add(sysAdministratorAuth);
      }
      saveBatch(sysAdministratorAuthList);
    }
  }
}
