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.PageQuery;
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.app.service.user.user.UserRegionService;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.domain.model.user.UserProfile;
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 UserRegionGateway userRegionGateway;
  private final UserFreightBalanceConvertor userFreightBalanceConvertor;

  @Override
  public PageResult<UserFreightBalanceCO> pageFreight(UserFreightBalancePageQryCmd cmd, AppExtCommand appExtCommand) {
    // 获取请求用户的国家编码
    UserProfile userProfile = userProfileGateway.getByUserId(appExtCommand.getReqUserId());
    String countryCode = userProfile.getCountryCode();

    cmd.setH5Display(true);
    cmd.setClose(false);

    PageQuery pageQuery = cmd.getPageQuery();

    // 保存原始分页参数
    int pageNo = pageQuery.getCursor();
    int pageSize = pageQuery.getLimit();
    
    pageQuery.setCursor(1);
    pageQuery.setLimit(500);
    PageResult<UserFreightBalanceDTO> freightPageResult = freightGoldClient.pageFreight(cmd).getBody();

    if (freightPageResult.checkRecordsEmpty()) {
      return freightPageResult.emptyRecords();
    }
    
    // 根据国家编码过滤数据
    List<UserFreightBalanceDTO> filteredRecords = freightPageResult.getRecords().stream()
        .filter(dto -> isCountrySupported(userProfile.getId(), dto.getUserId()))
        .collect(Collectors.toList());
    
    if (filteredRecords.isEmpty()) {
      return PageResult.newPageResult(20);
    }
    
    // 手动分页
    int total = filteredRecords.size();
    int fromIndex = (pageNo - 1) * pageSize;
    int toIndex = Math.min(fromIndex + pageSize, total);
    
    if (fromIndex >= total) {
      return PageResult.newPageResult(20);
    }
    
    List<UserFreightBalanceDTO> pagedRecords = filteredRecords.subList(fromIndex, toIndex);
    
    // 构建分页结果
    PageResult<UserFreightBalanceDTO> pagedResult = new PageResult<>();
    pagedResult.setRecords(pagedRecords);
    pagedResult.setTotal((long) total);
    pagedResult.setCurrent(pageNo);
    pagedResult.setSize(pageSize);
    
    if (pagedResult.checkRecordsEmpty()) {
      return pagedResult.emptyRecords();
    }

    Set<Long> userIds = pagedResult.getRecords().stream()
        .map(UserFreightBalanceDTO::getUserId)
        .collect(Collectors.toSet());

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

    Map<Long, Long> transactionCountMap = freightGoldClient.mapTransactionCountByUserIds(userIds).getBody();
    AppCountryCodeCO appCountryCode = appConfigService.getAppCountryCode();

    // 构建国家代码到国旗URL的映射
    Map<String, String> countryFlagMap = buildCountryFlagMap(appCountryCode);

    return pagedResult.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;
    });
  }

  /**
   * 检查国家是否在支持列表中.
   */
  private boolean isCountrySupported(Long userId, Long dtoUserId) {
    return userRegionGateway.checkEqRegion(userId, dtoUserId);
  }

  /**
   * 构建国家代码到国旗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;
  }

}
