package com.red.circle.other.app.service.user.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.convertor.UserFreightBalanceConvertor;
import com.red.circle.other.app.dto.clientobject.sys.AppCountryCodeCO;
import com.red.circle.other.app.dto.clientobject.sys.CountryCodeCO;
import com.red.circle.other.app.dto.clientobject.user.UserFreightBalanceCO;
import com.red.circle.other.app.service.sys.AppConfigService;
import com.red.circle.other.app.service.user.UserFreightBalanceRestService;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.wallet.inner.endpoint.freight.FreightBalanceClient;
import com.red.circle.wallet.inner.endpoint.freight.FreightGoldClient;
import com.red.circle.wallet.inner.model.cmd.UserFreightBalancePageQryCmd;
import com.red.circle.wallet.inner.model.dto.UserFreightBalanceDTO;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 用户货运账户服务实现.
 *
 * @author system
 * @since 2025-10-21
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserFreightBalanceRestServiceImpl implements UserFreightBalanceRestService {

  private final FreightGoldClient freightGoldClient;
  private final UserProfileClient userProfileClient;
  private final AppConfigService appConfigService;
  private final UserProfileGateway userProfileGateway;
  private final UserFreightBalanceConvertor userFreightBalanceConvertor;

  @Override
  public PageResult<UserFreightBalanceCO> pageFreight(UserFreightBalancePageQryCmd cmd, AppExtCommand appExtCommand) {
    // 写死默认查询条件：H5开启且未关闭
    cmd.setH5Display(true);
    cmd.setClose(false);
    
    // 1. 查询货运账户分页数据
    PageResult<UserFreightBalanceDTO> freightPageResult = freightGoldClient.pageFreight(cmd).getBody();

    if (freightPageResult.checkRecordsEmpty()) {
      return freightPageResult.emptyRecords();
    }

    // 2. 查询用户ID集合
    Set<Long> userIds = freightPageResult.getRecords().stream()
        .map(UserFreightBalanceDTO::getUserId)
        .collect(Collectors.toSet());

    // 3. 查询用户基本信息
    Map<Long, UserProfileDTO> userBaseInfoMap = ResponseAssert.requiredSuccess(
        userProfileClient.mapByUserIds(userIds)
    );

    // 4. 查询交易次数（type=1）
    Map<Long, Long> transactionCountMap = freightGoldClient.mapTransactionCountByUserIds(userIds).getBody();

    // 5. 获取支持的国家配置
    AppCountryCodeCO appCountryCode = appConfigService.getAppCountryCode();
    
    // 构建国家代码到国旗URL的映射
    Map<String, String> countryFlagMap = buildCountryFlagMap(appCountryCode);

    // 6. 转换并组装数据
    return freightPageResult.convert(dto -> {
      UserFreightBalanceCO co = userFreightBalanceConvertor.toUserFreightBalanceCO(dto);
      co.setBalance(dto.getBalance());
      co.setIsFollow(userProfileGateway.checkFollow(appExtCommand.getReqUserId(), dto.getUserId()));
      co.setUserBaseInfo(userBaseInfoMap.get(dto.getUserId()));
      
      // 计算成为代理天数
      if (dto.getCreateTime() != null) {
        LocalDateTime createTime = dto.getCreateTime().toLocalDateTime();
        LocalDateTime now = LocalDateTime.now();
        long days = ChronoUnit.DAYS.between(createTime, now);
        co.setBecomeDays((int) days);
      }
      
      // 设置交易次数
      co.setTransactionCount(
          Optional.ofNullable(transactionCountMap.get(dto.getUserId())).orElse(0L)
      );
      
      // 匹配并设置国旗URL
      co.setNationalFlag(matchNationalFlag(dto.getSupportedCountries(), countryFlagMap));

      if (co.getUserBaseInfo() != null) {
        UserProfileDTO userBaseInfo = co.getUserBaseInfo();
        co.setOwnNationalFlag(countryFlagMap.get(userBaseInfo.getCountryName()));
      }
      return co;
    });
  }

  /**
   * 构建国家代码到国旗URL的映射.
   */
  private Map<String, String> buildCountryFlagMap(AppCountryCodeCO appCountryCode) {
    if (appCountryCode == null || appCountryCode.getOpenCountry() == null) {
      return Map.of();
    }
    
    return appCountryCode.getOpenCountry().stream()
        .filter(country -> StringUtils.isNotBlank(country.getCountryName()) && StringUtils.isNotBlank(country.getNationalFlag()))
        .collect(Collectors.toMap(
            CountryCodeCO::getCountryName,
            CountryCodeCO::getNationalFlag,
            (existing, replacement) -> existing
        ));
  }

  /**
   * 匹配国旗URL.
   * 
   * @param supportedCountries 支持的国家（逗号分隔）
   * @param countryFlagMap 国家代码到国旗URL的映射
   * @return 所有匹配的国旗URL（逗号分隔），如果没有匹配则返回空字符串
   */
  private List<String> matchNationalFlag(String supportedCountries, Map<String, String> countryFlagMap) {
    if (supportedCountries == null || supportedCountries.isEmpty() || countryFlagMap.isEmpty()) {
      return new  ArrayList<>(0);
    }
    
    // 分割支持的国家代码
    String[] countries = supportedCountries.split(",");
    
    // 收集所有匹配到的国旗URL
    List<String> flagUrls = new ArrayList<>();
    for (String country : countries) {
      String countryCode = country.trim();
      if (countryFlagMap.containsKey(countryCode)) {
        flagUrls.add(countryFlagMap.get(countryCode));
      }
    }
    
    return flagUrls;
  }

}
