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

import com.red.circle.common.business.dto.cmd.PageUserIdCmd;
import com.red.circle.console.app.convertor.sys.ImAccountAppConvertor;
import com.red.circle.console.app.dto.clienobject.sys.SysImAccountCO;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.sys.SysImAccountClient;
import com.red.circle.other.inner.model.cmd.sys.SysImAccountCmd;
import com.red.circle.other.inner.model.dto.sys.SysImAccountDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * im登录账号 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2020-11-10
 */
@Service
@RequiredArgsConstructor
public class SysImAccountServiceImpl implements SysImAccountService {

  private final SysImAccountClient imAccountClient;
  private final UserProfileClient userProfileClient;
  private final ImAccountAppConvertor accountAppConvertor;

  @Override
  public PageResult<SysImAccountCO> pageImAccountVo(PageUserIdCmd cmd) {
    PageResult<SysImAccountDTO> sysImAccountPage = ResponseAssert.requiredSuccess(
        imAccountClient.pageImAccountVo(cmd));

    if (CollectionUtils.isEmpty(sysImAccountPage.getRecords())) {
      return sysImAccountPage.convert(accountAppConvertor::toSysImAccountCO);
    }

    Map<Long, UserProfileDTO> baseInfoMap = ResponseAssert.requiredSuccess(userProfileClient
        .mapByUserIds(sysImAccountPage.getRecords().stream().map(SysImAccountDTO::getUserId)
            .collect(Collectors.toSet())));

    return sysImAccountPage.convert(
        sysImAccount -> accountAppConvertor.toSysImAccountCO(sysImAccount)
            .setUserBaseInfo(baseInfoMap.get(sysImAccount.getUserId())));
  }

  @Override
  public void addImAccount(SysImAccountCmd sysImAccount) {
    ResponseAssert.requiredSuccess(imAccountClient.addImAccount(sysImAccount));
  }


  @Override
  public void resetPassword(Long userId, Long operationUserId) {
    ResponseAssert.requiredSuccess(imAccountClient.resetPassword(userId, operationUserId));
  }

  @Override
  public void deleteImAccount(Long userId) {
    ResponseAssert.requiredSuccess(imAccountClient.deleteImAccount(userId));
  }

}
