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

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.red.circle.console.app.convertor.sys.CustomerServiceAppConvertor;
import com.red.circle.console.app.dto.clienobject.sys.SysCustomerServiceConfigCO;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.inner.endpoint.sys.SysCustomerServiceClient;
import com.red.circle.other.inner.model.cmd.sys.CustomerServiceConfigCmd;
import com.red.circle.other.inner.model.dto.sys.SysCustomerServiceConfigDTO;
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.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 客服配置.
 *
 * @author pengshigang on 2022/10/8
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysCustomerServiceConfigServiceImpl implements SysCustomerServiceConfigService {

  private final UserProfileClient userProfileClient;
  private final SysCustomerServiceClient customerServiceClient;
  private final CustomerServiceAppConvertor customerServiceAppConvertor;

  @Override
  public void add(CustomerServiceConfigCmd param) {
    ResponseAssert.requiredSuccess(customerServiceClient.add(param));
  }

  @Override
  public void update(CustomerServiceConfigCmd param) {
    ResponseAssert.requiredSuccess(customerServiceClient.update(param));
  }

  @Override
  public void delete(Long id) {
    ResponseAssert.requiredSuccess(customerServiceClient.delete(id));
  }

  @Override
  public List<SysCustomerServiceConfigCO> list(String sysOrigin, String region) {
    log.warn("客服传入参数信息:{},地区信息:{}",sysOrigin,region);
    List<SysCustomerServiceConfigDTO> list = ResponseAssert.requiredSuccess(
        customerServiceClient.list(sysOrigin, region));
    log.warn("客户列表信息:{}", JSON.toJSON(list));

    Map<Long, UserProfileDTO> mapUser = ResponseAssert.requiredSuccess(
        userProfileClient.mapByUserIds(
            list.stream().map(SysCustomerServiceConfigDTO::getUserId).collect(Collectors.toSet())));
    if (CollectionUtils.isEmpty(mapUser)) {
      return Lists.newArrayList();
    }
    return list.stream().map(item -> {
      SysCustomerServiceConfigCO result = customerServiceAppConvertor.toCustomerServiceConfig(item);
      result.setUserProfile(mapUser.get(item.getUserId()));
      return result;
    }).toList();
  }
}
