ClientCustomerServiceImpl.java 20 KB
package com.infoloop.tianting.service.impl;

import com.fasterxml.jackson.annotation.JacksonInject.Value;
import com.infoloop.tianting.clientcustomerorderservice.SingleClientCustomerOrderRpcResponse;
import com.infoloop.tianting.clientcustomerservice.SingleClientCustomerRpcResponse;
import com.infoloop.tianting.context.LoginContextHolder;
import com.infoloop.tianting.menuservice.SingleClientCustomerMenuRefRpcResponse;
import com.infoloop.tianting.menuservice.SingleMenuRpcResponse;
import com.infoloop.tianting.model.dto.ClientCustomerDbDTO.ClientCustomerDto;
import com.infoloop.tianting.model.dto.ClientCustomerDbDTO.CurrentClientCustomerDto;
import com.infoloop.tianting.model.dto.ClientCustomerDbDTO.HospitalRecordDto;
import com.infoloop.tianting.model.dto.ClientCustomerDbDTO.NotOrderCustomerDto;
import com.infoloop.tianting.model.dto.ClientCustomerDbDTO.TodayOrderDto;
import com.infoloop.tianting.model.dto.ClientLabelDTO.BatchCreateCustomerLabelRefDto;
import com.infoloop.tianting.model.dto.ClientLabelDTO.BatchCreateCustomerLabelRefResponseDto;
import com.infoloop.tianting.model.dto.ClientLabelDTO.BatchDeleteCustomerLabelRefRequestDto;
import com.infoloop.tianting.model.dto.ClientLabelDTO.BatchDeleteCustomerLabelRefResponseDto;
import com.infoloop.tianting.model.dto.ClientLabelDTO.CustomerLabelRefDetailDto;
import com.infoloop.tianting.model.dto.MenuDbDTO.DishRuleJson;
import com.infoloop.tianting.model.dto.MenuDbDTO.MenuDto;
import com.infoloop.tianting.model.dto.MenuDbDTO.OrderRuleJson;
import com.infoloop.tianting.model.dto.OrderDbDTO.QueryOrderByConditionDto;
import com.infoloop.tianting.service.ClientCustomerService;
import com.infoloop.tianting.service.client.ClientCustomerServiceHttpClient;
import com.infoloop.tianting.service.client.ClientCustomerServiceRpcClient;
import com.infoloop.tianting.service.client.MenuServiceRpcClient;
import com.infoloop.tianting.service.client.OrderServiceRpcClient;
import com.infoloop.tianting.utils.DateUtil;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.mail.search.SearchTerm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ClientCustomerServiceImpl implements ClientCustomerService {

  private final ClientCustomerServiceRpcClient clientCustomerServiceRpcClient;
  private final ClientCustomerServiceHttpClient clientCustomerServiceHttpClient;
  private final OrderServiceRpcClient orderServiceRpcClient;
  private final MenuServiceRpcClient menuServiceRpcClient;

  @Override
  public ClientCustomerDto getClientCustomerByHISCustomerId(String hisCustomerId) {
    var response = clientCustomerServiceRpcClient.getClientCustomerByHISCustomerId(hisCustomerId).getResponse();
    if (response.getId() == 0) {
      response = clientCustomerServiceRpcClient.getClientCustomerByContactNo(hisCustomerId).getResponse();
    }
    return ClientCustomerDto.builder()
        .id(response.getId())
        .clientId(response.getClientId())
        .enterpriseId(response.getEnterpriseId())
        .age(response.getAge())
        .height(response.getHeight())
        .HISCustomerId(response.getHISCustomerId())
        .identityCardNo(response.getIdentityCardNo())
        .mobile(response.getMobile())
        .name(response.getName())
        .openId(response.getOpenId())
        .sex(response.getSex())
        .stallId(response.getStallId())
        .weight(response.getWeight())
        .isDeleted(response.getIsDeleted())
        .birthday(DateUtil.formatDate(response.getBirthday()))
        .createdAt(DateUtil.formatDate(response.getCreatedAt()))
        .createdBy(response.getCreatedBy())
        .creationSource(response.getCreationSource())
        .updatedAt(DateUtil.formatDate(response.getUpdatedAt()))
        .updateSource(response.getUpdateSource())
        .updatedBy(response.getUpdatedBy())
        .build();
  }

  @Override
  public ClientCustomerDto getClientCustomerByPhone(String phone) {
    final var response = clientCustomerServiceRpcClient.getClientCustomerByMobile(phone);
    return ClientCustomerDto.builder()
        .id(response.getResponse().getId())
        .clientId(response.getResponse().getClientId())
        .enterpriseId(response.getResponse().getEnterpriseId())
        .age(response.getResponse().getAge())
        .height(response.getResponse().getHeight())
        .HISCustomerId(response.getResponse().getHISCustomerId())
        .identityCardNo(response.getResponse().getIdentityCardNo())
        .mobile(response.getResponse().getMobile())
        .name(response.getResponse().getName())
        .openId(response.getResponse().getOpenId())
        .sex(response.getResponse().getSex())
        .stallId(response.getResponse().getStallId())
        .weight(response.getResponse().getWeight())
        .isDeleted(response.getResponse().getIsDeleted())
        .birthday(DateUtil.formatDate(response.getResponse().getBirthday()))
        .createdAt(DateUtil.formatDate(response.getResponse().getCreatedAt()))
        .createdBy(response.getResponse().getCreatedBy())
        .creationSource(response.getResponse().getCreationSource())
        .updatedAt(DateUtil.formatDate(response.getResponse().getUpdatedAt()))
        .updateSource(response.getResponse().getUpdateSource())
        .updatedBy(response.getResponse().getUpdatedBy())
        .build();
  }

  @Override
  public List<HospitalRecordDto> getClientCustomerHospitalRecordsByCustomerId(
      Integer enterpriseId, Integer customerId) {
    final var response = clientCustomerServiceRpcClient
        .getClientCustomerHospitalRecordsByCustomerId(enterpriseId, customerId);
    final var record = response.getResponse();
    return List.of(HospitalRecordDto.builder()
            .id(record.getId())
            .enterpriseId(record.getEnterpriseId())
            .clientId(record.getClientId())
            .stallId(record.getStallId())
            .customerId(record.getCustomerId())
            .actualDischargeTime(DateUtil.formatDate(record.getActualDischargeTime()))
            .birthDate(DateUtil.formatDate(record.getBirthDate()))
            .contractNo(record.getContractNo())
            .departmentName(record.getDepartmentName())
            .dueDate(DateUtil.formatDate(record.getDueDate()))
            .expectDischargeTime(DateUtil.formatDate(record.getExpectDischargeTime()))
            .hospitalStatus(record.getHospitalStatus())
            .hospitalTime(DateUtil.formatDate(record.getHospitalTime()))
            .remark(record.getRemark())
            .roomNo(record.getRoomNo())
            .isDeleted(record.getIsDeleted())
            .createdAt(DateUtil.formatDate(record.getCreatedAt()))
            .createdBy(record.getCreatedBy())
            .creationSource(record.getCreationSource())
            .updatedAt(DateUtil.formatDate(record.getUpdatedAt()))
            .updatedBy(record.getUpdatedBy())
            .updateSource(record.getUpdateSource())
            .build());
  }

  @Override
  public BatchCreateCustomerLabelRefResponseDto batchCreateClientCustomerLabelRefs(
      BatchCreateCustomerLabelRefDto batchCreateCustomerLabelRefDto) {
    final var response = clientCustomerServiceRpcClient.batchCreateClientCustomerLabelRefs(
        batchCreateCustomerLabelRefDto);
    return BatchCreateCustomerLabelRefResponseDto.builder()
        .isCreated(response.getIsCreated())
        .ids(response.getIdsList())
        .build();
  }

  @Override
  public List<CustomerLabelRefDetailDto> getCustomerLabelsByCustomerId(
      Integer enterpriseId, Integer customerId) {
    final var response = clientCustomerServiceRpcClient.getCustomerLabelsByCustomerId(
        enterpriseId, customerId
    );
    return response.getResponsesList().stream().map(
        labelRef -> CustomerLabelRefDetailDto.builder()
            .id(labelRef.getId())
            .customerId(labelRef.getCustomerId())
            .enterpriseId(labelRef.getEnterpriseId())
            .labelId(labelRef.getLabelId())
            .creationSource(labelRef.getCreationSource())
            .createdAt(DateUtil.formatDate(labelRef.getCreatedAt()))
            .createdBy(labelRef.getCreatedBy())
            .build()
    ).collect(Collectors.toList());
  }

  @Override
  public BatchDeleteCustomerLabelRefResponseDto deleteClientCustomerLabelRefsByIds(
      BatchDeleteCustomerLabelRefRequestDto deleteRequestDto) {
    final var response = clientCustomerServiceRpcClient.batchDeleteClientCustomerLabelRefsByIds(
        deleteRequestDto);
    return BatchDeleteCustomerLabelRefResponseDto.builder().isDeleted(response.getIsDeleted()).build();
  }

//  @Override
//  public TodayOrderDto getTodayOrderStatistic(String token) {
//    final var currentCustomers = clientCustomerServiceHttpClient.getCurrentClientCustomer(token, false);
//    final var customerIds = currentCustomers.stream().map(CurrentClientCustomerDto::getId).map(id -> {try{
//      return Integer.valueOf(id);
//    } catch (NumberFormatException e) {
//      return null;
//    }
//    }).filter(Objects::nonNull).distinct().collect(Collectors.toList());
//    final var operatorLoginInfo = LoginContextHolder.getLoginInfo();
//    LocalDate today = LocalDate.now();
//    LocalDateTime todayZero = today.atStartOfDay();
//    LocalDate tomorrow = today.plusDays(1);
//    LocalDateTime tomorrowZero = tomorrow.atStartOfDay();
//    final var queryOrderDto = QueryOrderByConditionDto.builder()
//        .enterpriseId(operatorLoginInfo.getEnterpriseId())
//        .shouldFilterCustomerIds(true)
//        .customerIds(customerIds)
//        .shouldFilterMealTimeStart(true)
//        .mealTimeStart(todayZero)
//        .shouldFilterMealTimeEnd(true)
//        .mealTimeEnd(tomorrowZero)
//        .build();
//    final var orderedResponseList = orderServiceRpcClient.getOrdersByCondition(queryOrderDto);
//    List<Integer> uniqueOrderedCustomerIds = orderedResponseList.stream().map(
//        SingleClientCustomerOrderRpcResponse::getCustomerId).distinct()
//        .collect(Collectors.toList());
//    List<Integer> notOrderedCustomerIds = customerIds.stream().filter(id -> !uniqueOrderedCustomerIds.contains(id)).collect(
//        Collectors.toList());
//    // 根据customerIds 获取到menuRef列表
//    final var menuRefs = menuServiceRpcClient.getClientCustomerMenuRefsByCustomerIds(
//        operatorLoginInfo.getEnterpriseId(), notOrderedCustomerIds).getResponsesList();
//    final var menuIds = menuRefs.stream().map(SingleClientCustomerMenuRefRpcResponse::getMenuId)
//        .collect(Collectors.toList());
//    final var menus = menuServiceRpcClient.getMenusByIds(operatorLoginInfo.getEnterpriseId(),
//        menuIds).getResponsesList();
//
//    List<NotOrderCustomerDto> resNotOrderCustomers = new ArrayList<>();
//    // 在customers里找到未下单的用户
//    final var notOrderCustomers = currentCustomers.stream().filter(c ->
//        notOrderedCustomerIds.contains(Integer.valueOf(c.getId()))).collect(Collectors.toList());
//
//    for(CurrentClientCustomerDto notOrderCustomer: notOrderCustomers) {
//
//      // 在ref里找到这个用户的menu ids
//      final var notOrderCustomerId = Integer.valueOf(notOrderCustomer.getId());
//      final var curMenuIds = menuRefs.stream().filter(r -> r.getCustomerId() == notOrderCustomerId)
//          .map(SingleClientCustomerMenuRefRpcResponse::getMenuId).collect(Collectors.toList());
//      // 根据menu ids找到 menus
//      final var curMenus = menus.stream().filter(m -> curMenuIds.contains(m.getId()))
//          .collect(Collectors.toList());
//
//      final var curMenuDtos = curMenus.stream().map(menu ->
//          MenuDto.builder()
//              .id(menu.getId())
//              .code(menu.getCode())
//              .enterpriseId(menu.getEnterpriseId())
//              .name(menu.getName())
//              .status(menu.getStatusValue())
//              .customerScope(menu.getCustomerScope())
//              .nutritionPromotion(menu.getNutritionPromotion())
//              .nutritionalStatistics(menu.getNutritionalStatistics())
//              .dishRuleJson(DishRuleJson.builder()
//                  .days(menu.getDishRuleJson().getDays())
//                  .dishType(menu.getDishRuleJson().getDishType())
//                  .mealIds(menu.getDishRuleJson().getMealIdsList())
//                  .build())
//              .orderRuleJson(OrderRuleJson.builder()
//                  .allowMicroPlaceOrder(menu.getOrderRuleJson().getAllowMicroPlaceOrder())
//                  .closeTimeType(menu.getOrderRuleJson().getCloseTimeType())
//                  .dishSelectRule(menu.getOrderRuleJson().getDishSelectRule())
//                  .earlyDays(menu.getOrderRuleJson().getEarlyDays())
//                  .modeOfPayment(menu.getOrderRuleJson().getModeOfPayment())
//                  .placeOrderCount(menu.getOrderRuleJson().getPlaceOrderCount())
//                  .startTime(menu.getOrderRuleJson().getStartTime())
//                  .endTime(menu.getOrderRuleJson().getEndTime())
//                  .deadline(menu.getOrderRuleJson().getDeadline())
//                  .build())
//              .createdBy(menu.getCreatedBy())
//              .creationSource(menu.getCreationSource())
//              .createdAt(DateUtil.formatDate(menu.getCreatedAt()))
//              .updatedBy(menu.getUpdatedBy())
//              .updateSource(menu.getUpdateSource())
//              .updatedAt(DateUtil.formatDate(menu.getUpdatedAt()))
//              .publishAt(DateUtil.formatDate(menu.getPublishAt()))
//              .build()).collect(Collectors.toList());
//      final var resNotOrderCustomer = NotOrderCustomerDto.builder()
//          .id(notOrderCustomerId)
//          .name(notOrderCustomer.getName())
//          .roomNo(notOrderCustomer.getRoomNo())
//          .menuList(curMenuDtos)
//          .build();
//      resNotOrderCustomers.add(resNotOrderCustomer);
//    }
//
//    return TodayOrderDto.builder()
//        .totalCurrentCustomerCount(currentCustomers.size())
//        .notOrderCustomers(resNotOrderCustomers)
//        .build();
//  }

  @Override
  public TodayOrderDto getTodayOrderStatistic(String token, boolean isHis) {
    List<CurrentClientCustomerDto> currentCustomers = new ArrayList<>();
    List<Integer> customerIds = new ArrayList<>();
    if (isHis){
      currentCustomers = clientCustomerServiceHttpClient.getCurrentClientCustomer(token, true);
      final var hisCustomerIds = currentCustomers.stream().map(CurrentClientCustomerDto::getId).distinct()
          .collect(Collectors.toList());
      final var currentClientCustomers = clientCustomerServiceRpcClient.getClientCustomersByHISCustomerIds(hisCustomerIds).getResponsesList();
      customerIds = currentClientCustomers.stream().map(SingleClientCustomerRpcResponse::getId).distinct().collect(Collectors.toList());
    } else {
      currentCustomers = clientCustomerServiceHttpClient.getCurrentClientCustomer(token, false);
      customerIds = currentCustomers.stream().map(CurrentClientCustomerDto::getId).map(id -> {try{
        return Integer.valueOf(id);
      } catch (NumberFormatException e) {
        return null;
      }
      }).filter(Objects::nonNull).distinct().collect(Collectors.toList());
    }

    final var operatorLoginInfo = LoginContextHolder.getLoginInfo();
    LocalDate today = LocalDate.now();
    LocalDateTime todayZero = today.atStartOfDay();
    LocalDate tomorrow = today.plusDays(1);
    LocalDateTime tomorrowZero = tomorrow.atStartOfDay();
    final var queryOrderDto = QueryOrderByConditionDto.builder()
        .enterpriseId(operatorLoginInfo.getEnterpriseId())
        .shouldFilterCustomerIds(true)
        .customerIds(customerIds)
        .shouldFilterMealTimeStart(true)
        .mealTimeStart(todayZero)
        .shouldFilterMealTimeEnd(true)
        .mealTimeEnd(tomorrowZero)
        .build();
    final var orderedResponseList = orderServiceRpcClient.getOrdersByCondition(queryOrderDto);
    List<Integer> uniqueOrderedCustomerIds = orderedResponseList.stream().map(
        SingleClientCustomerOrderRpcResponse::getCustomerId).distinct()
        .collect(Collectors.toList());
    List<Integer> notOrderedCustomerIds = customerIds.stream().filter(id -> !uniqueOrderedCustomerIds.contains(id)).collect(
        Collectors.toList());
    // 根据customerIds 获取到menuRef列表
    final var menuRefs = menuServiceRpcClient.getClientCustomerMenuRefsByCustomerIds(
        operatorLoginInfo.getEnterpriseId(), notOrderedCustomerIds).getResponsesList();
    final var menuIds = menuRefs.stream().map(SingleClientCustomerMenuRefRpcResponse::getMenuId)
        .collect(Collectors.toList());
    final var menus = menuServiceRpcClient.getMenusByIds(operatorLoginInfo.getEnterpriseId(),
        menuIds).getResponsesList();

    List<NotOrderCustomerDto> resNotOrderCustomers = new ArrayList<>();
    // 在customers里找到未下单的用户
    final var notOrderCustomers = currentCustomers.stream().filter(c ->
        notOrderedCustomerIds.contains(Integer.valueOf(c.getId()))).collect(Collectors.toList());

    for(CurrentClientCustomerDto notOrderCustomer: notOrderCustomers) {

      // 在ref里找到这个用户的menu ids
      final var notOrderCustomerId = Integer.valueOf(notOrderCustomer.getId());
      final var curMenuIds = menuRefs.stream().filter(r -> r.getCustomerId() == notOrderCustomerId)
          .map(SingleClientCustomerMenuRefRpcResponse::getMenuId).collect(Collectors.toList());
      // 根据menu ids找到 menus
      final var curMenus = menus.stream().filter(m -> curMenuIds.contains(m.getId()))
          .collect(Collectors.toList());

      final var curMenuDtos = curMenus.stream().map(menu ->
          MenuDto.builder()
              .id(menu.getId())
              .code(menu.getCode())
              .enterpriseId(menu.getEnterpriseId())
              .name(menu.getName())
              .status(menu.getStatusValue())
              .customerScope(menu.getCustomerScope())
              .nutritionPromotion(menu.getNutritionPromotion())
              .nutritionalStatistics(menu.getNutritionalStatistics())
              .dishRuleJson(DishRuleJson.builder()
                  .days(menu.getDishRuleJson().getDays())
                  .dishType(menu.getDishRuleJson().getDishType())
                  .mealIds(menu.getDishRuleJson().getMealIdsList())
                  .build())
              .orderRuleJson(OrderRuleJson.builder()
                  .allowMicroPlaceOrder(menu.getOrderRuleJson().getAllowMicroPlaceOrder())
                  .closeTimeType(menu.getOrderRuleJson().getCloseTimeType())
                  .dishSelectRule(menu.getOrderRuleJson().getDishSelectRule())
                  .earlyDays(menu.getOrderRuleJson().getEarlyDays())
                  .modeOfPayment(menu.getOrderRuleJson().getModeOfPayment())
                  .placeOrderCount(menu.getOrderRuleJson().getPlaceOrderCount())
                  .startTime(menu.getOrderRuleJson().getStartTime())
                  .endTime(menu.getOrderRuleJson().getEndTime())
                  .deadline(menu.getOrderRuleJson().getDeadline())
                  .build())
              .createdBy(menu.getCreatedBy())
              .creationSource(menu.getCreationSource())
              .createdAt(DateUtil.formatDate(menu.getCreatedAt()))
              .updatedBy(menu.getUpdatedBy())
              .updateSource(menu.getUpdateSource())
              .updatedAt(DateUtil.formatDate(menu.getUpdatedAt()))
              .publishAt(DateUtil.formatDate(menu.getPublishAt()))
              .build()).collect(Collectors.toList());
      final var resNotOrderCustomer = NotOrderCustomerDto.builder()
          .id(notOrderCustomerId)
          .name(notOrderCustomer.getName())
          .roomNo(notOrderCustomer.getRoomNo())
          .menuList(curMenuDtos)
          .build();
      resNotOrderCustomers.add(resNotOrderCustomer);
    }

    return TodayOrderDto.builder()
        .totalCurrentCustomerCount(currentCustomers.size())
        .notOrderCustomers(resNotOrderCustomers)
        .build();
  }

}