package com.red.circle.console.app.service.app.team;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.console.app.convertor.UserAppConvertor;
import com.red.circle.console.app.convertor.team.TeamAppConvertor;
import com.red.circle.console.app.dto.clienobject.team.TeamNoticeCO;
import com.red.circle.console.infra.database.rds.entity.admin.User;
import com.red.circle.console.infra.database.rds.service.admin.UserService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.inner.endpoint.team.agency.AgentTeamClient;
import com.red.circle.other.inner.endpoint.team.target.TeamNoticeClient;
import com.red.circle.other.inner.model.cmd.team.TeamNoticeCmd;
import com.red.circle.other.inner.model.dto.agency.agency.TeamNoticeDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 团队通知.
 *
 * @author pengshigang on 2022/12/15
 */
@Service
@RequiredArgsConstructor
public class TeamNoticeBackServiceImpl implements TeamNoticeBackService {

  private final UserService userService;
  private final RedisService redisService;
  private final AgentTeamClient agentTeamClient;
  private final TeamAppConvertor teamAppConvertor;
  private final UserAppConvertor userAppConvertor;
  private final TeamNoticeClient teamNoticeClient;

  @Override
  public List<TeamNoticeCO> listByTeamId(Long teamId) {

    List<TeamNoticeDTO> teamNotices = ResponseAssert.requiredSuccess(
        teamNoticeClient.listByTeamId(teamId));
    if (CollectionUtils.isEmpty(teamNotices)) {
      return List.of();
    }

    Map<Long, User> userMap = userService.mapBackUser(
        teamNotices.stream().map(TeamNoticeDTO::getCreateUser).collect(Collectors.toSet()));

    if (CollectionUtils.isEmpty(userMap)) {
      return List.of();
    }

    return teamNotices.stream().map(teamNotice -> {
      TeamNoticeCO teamNoticeVO = teamAppConvertor.toTeamNoticeCO(teamNotice);
      teamNoticeVO.setCreateUserInfo(
          userAppConvertor.toUserCO(userMap.get(teamNotice.getCreateUser())));
      return teamNoticeVO;
    }).collect(Collectors.toList());
  }

  @Override
  public void send(TeamNoticeCmd noticeParam) {
    teamNoticeClient.sendNotice(noticeParam);
  }

  @Override
  public void deleteById(Long id) {
    teamNoticeClient.deleteById(id);
  }

}
