package com.erp.order.settlement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.order.settlement.dto.*;
import com.erp.order.settlement.entity.OrderSettlement;
import com.erp.order.settlement.entity.SettlementPeriod;
import com.erp.order.settlement.entity.SettlementReport;
import com.erp.order.settlement.repository.OrderSettlementRepository;
import com.erp.order.settlement.service.OrderSettlementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import com.erp.common.core.model.PageResponse;

/**
 * 订单结算服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderSettlementServiceImpl implements OrderSettlementService {

    private final OrderSettlementRepository settlementRepository;
    private final com.erp.order.settlement.repository.SettlementPeriodRepository periodRepository;
    private final com.erp.order.settlement.repository.SettlementReportRepository reportRepository;

    private static final DateTimeFormatter SETTLEMENT_NO_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    private static final BigDecimal DEFAULT_COMMISSION_RATE = new BigDecimal("0.006"); // 默认0.6%平台佣金

    // ==================== 订单结算基础操作 ====================

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSettlement createSettlement(OrderSettlement settlement) {
        if (settlement.getSettlementNo() == null || settlement.getSettlementNo().isEmpty()) {
            settlement.setSettlementNo(generateSettlementNo());
        }
        if (settlement.getSettlementStatus() == null) {
            settlement.setSettlementStatus(OrderSettlement.STATUS_PENDING);
        }
        settlement.setCreatedAt(LocalDateTime.now());
        settlement.setUpdatedAt(LocalDateTime.now());
        settlementRepository.insert(settlement);
        log.info("创建订单结算记录: {}", settlement.getSettlementNo());
        return settlement;
    }

    @Override
    public OrderSettlement getSettlementById(Long id) {
        return settlementRepository.selectById(id);
    }

    @Override
    public OrderSettlement getSettlementBySettlementNo(String settlementNo) {
        return settlementRepository.findBySettlementNo(settlementNo);
    }

    @Override
    public OrderSettlement getSettlementByOrderId(Long orderId) {
        return settlementRepository.findByOrderId(orderId);
    }

    @Override
    public PageResponse<SettlementDTO> querySettlements(SettlementQueryRequest request) {
        LambdaQueryWrapper<OrderSettlement> wrapper = new LambdaQueryWrapper<>();

        if (request.getSettlementNo() != null && !request.getSettlementNo().isEmpty()) {
            wrapper.eq(OrderSettlement::getSettlementNo, request.getSettlementNo());
        }
        if (request.getOrderShortId() != null && !request.getOrderShortId().isEmpty()) {
            wrapper.eq(OrderSettlement::getOrderShortId, request.getOrderShortId());
        }
        if (request.getPlatformOrderSn() != null && !request.getPlatformOrderSn().isEmpty()) {
            wrapper.eq(OrderSettlement::getPlatformOrderSn, request.getPlatformOrderSn());
        }
        if (request.getPlatform() != null && !request.getPlatform().isEmpty()) {
            wrapper.eq(OrderSettlement::getPlatform, request.getPlatform());
        }
        if (request.getShopId() != null) {
            wrapper.eq(OrderSettlement::getShopId, request.getShopId());
        }
        if (request.getSettlementStatus() != null && !request.getSettlementStatus().isEmpty()) {
            wrapper.eq(OrderSettlement::getSettlementStatus, request.getSettlementStatus());
        }
        if (request.getSettlementPeriodId() != null) {
            wrapper.eq(OrderSettlement::getSettlementPeriodId, request.getSettlementPeriodId());
        }
        if (request.getStartDate() != null) {
            wrapper.ge(OrderSettlement::getPaymentTime, request.getStartDate().atStartOfDay());
        }
        if (request.getEndDate() != null) {
            wrapper.le(OrderSettlement::getPaymentTime, request.getEndDate().atTime(23, 59, 59));
        }

        wrapper.orderByDesc(OrderSettlement::getCreatedAt);

        IPage<OrderSettlement> page = settlementRepository.selectPage(
                new Page<>(request.getPageNum(), request.getPageSize()),
                wrapper
        );

        List<SettlementDTO> dtoList = page.getRecords().stream()
                .map(this::toDTO)
                .collect(Collectors.toList());

        return PageResponse.of(dtoList, page.getTotal(), request.getPageNum(), request.getPageSize());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSettlement updateSettlement(OrderSettlement settlement) {
        settlement.setUpdatedAt(LocalDateTime.now());
        settlementRepository.updateById(settlement);
        log.info("更新订单结算记录: {}", settlement.getSettlementNo());
        return settlement;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUpdateStatus(List<Long> ids, String status) {
        return settlementRepository.batchUpdateStatus(ids, status);
    }

    // ==================== 结算计算 ====================

    @Override
    public BigDecimal calculateSettlementAmount(Long orderId, BigDecimal commissionRate) {
        OrderSettlement settlement = settlementRepository.findByOrderId(orderId);
        if (settlement == null) {
            throw new IllegalArgumentException("订单结算记录不存在: " + orderId);
        }

        BigDecimal rate = commissionRate != null ? commissionRate : DEFAULT_COMMISSION_RATE;
        BigDecimal platformFee = settlement.getTotalAmount().multiply(rate).setScale(2, RoundingMode.HALF_UP);
        BigDecimal settlementAmount = settlement.getTotalAmount().subtract(platformFee);

        settlement.setPlatformCommissionRate(rate);
        settlement.setPlatformFee(platformFee);
        settlement.setSettlementAmount(settlementAmount);
        settlement.setSettlementStatus(OrderSettlement.STATUS_CALCULATING);

        updateSettlement(settlement);
        return settlementAmount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OrderSettlement> batchCalculateSettlement(List<Long> orderIds, BigDecimal commissionRate) {
        List<OrderSettlement> results = new ArrayList<>();
        for (Long orderId : orderIds) {
            try {
                OrderSettlement settlement = settlementRepository.findByOrderId(orderId);
                if (settlement != null && OrderSettlement.STATUS_PENDING.equals(settlement.getSettlementStatus())) {
                    calculateSettlementAmount(orderId, commissionRate);
                    results.add(settlementRepository.findByOrderId(orderId));
                }
            } catch (Exception e) {
                log.error("计算订单结算失败: orderId={}", orderId, e);
            }
        }
        log.info("批量计算结算完成: 共{}条", results.size());
        return results;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmSettlement(Long settlementId) {
        OrderSettlement settlement = getSettlementById(settlementId);
        if (settlement == null) {
            throw new IllegalArgumentException("结算记录不存在: " + settlementId);
        }
        if (!OrderSettlement.STATUS_CALCULATING.equals(settlement.getSettlementStatus())) {
            throw new IllegalStateException("只有计算中的结算可以确认");
        }

        settlement.setSettlementStatus(OrderSettlement.STATUS_SETTLED);
        settlement.setConfirmSettlementTime(LocalDateTime.now());
        settlement.setSettlementDate(LocalDateTime.now());
        updateSettlement(settlement);
        log.info("确认结算: {}", settlement.getSettlementNo());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchConfirmSettlement(List<Long> settlementIds) {
        int count = 0;
        for (Long id : settlementIds) {
            try {
                if (confirmSettlement(id)) {
                    count++;
                }
            } catch (Exception e) {
                log.error("确认结算失败: id={}", id, e);
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean freezeSettlement(Long settlementId, String reason) {
        OrderSettlement settlement = getSettlementById(settlementId);
        if (settlement == null) {
            throw new IllegalArgumentException("结算记录不存在: " + settlementId);
        }

        settlement.setSettlementStatus(OrderSettlement.STATUS_FROZEN);
        settlement.setRemark(reason != null ? reason : "冻结");
        updateSettlement(settlement);
        log.info("冻结结算: {}, 原因: {}", settlement.getSettlementNo(), reason);
        return true;
    }

    // ==================== 结算周期管理 ====================

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SettlementPeriod createSettlementPeriod(SettlementPeriod period) {
        if (period.getPeriodNo() == null || period.getPeriodNo().isEmpty()) {
            period.setPeriodNo(generatePeriodNo(period.getPeriodType()));
        }
        if (period.getPeriodStatus() == null) {
            period.setPeriodStatus(SettlementPeriod.STATUS_OPEN);
        }
        period.setCreatedAt(LocalDateTime.now());
        period.setUpdatedAt(LocalDateTime.now());

        // 保存到数据库
        periodRepository.insert(period); // FIXED: 添加PeriodRepository
        log.info("创建结算周期: {}", period.getPeriodNo());
        return period;
    }

    @Override
    public SettlementPeriod getSettlementPeriodById(Long id) {
        // TODO: 如果租户隔离需要校验tenantId，添加 tenantId 条件
        return periodRepository.selectById(id);
    }

    @Override
    public SettlementPeriod getCurrentOpenPeriod(String periodType) {
        List<SettlementPeriod> periods = periodRepository.findByTypeAndStatus(periodType, SettlementPeriod.STATUS_OPEN);
        return periods != null && !periods.isEmpty() ? periods.get(0) : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeSettlementPeriod(Long periodId) {
        SettlementPeriod period = getSettlementPeriodById(periodId);
        if (period == null) {
            throw new IllegalArgumentException("结算周期不存在: " + periodId);
        }
        if (!SettlementPeriod.STATUS_OPEN.equals(period.getPeriodStatus())) {
            throw new IllegalStateException("只有开放状态的结算周期可以关闭");
        }
        period.setPeriodStatus(SettlementPeriod.STATUS_CLOSED);
        period.setUpdatedAt(LocalDateTime.now());
        periodRepository.updateById(period);
        log.info("关闭结算周期: {}, periodNo={}", periodId, period.getPeriodNo());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int settlePeriodOrders(Long periodId) {
        // 获取周期内所有待结算订单并结算
        List<OrderSettlement> pendingSettlements = settlementRepository.findByPeriodIdAndStatus(periodId, OrderSettlement.STATUS_PENDING);
        List<Long> orderIds = pendingSettlements.stream().map(OrderSettlement::getOrderId).collect(Collectors.toList());
        batchCalculateSettlement(orderIds, DEFAULT_COMMISSION_RATE);
        log.info("结算周期订单: periodId={}, count={}", periodId, pendingSettlements.size());
        return pendingSettlements.size();
    }

    @Override
    public List<SettlementPeriodDTO> querySettlementPeriods(SettlementQueryRequest request) {
        LambdaQueryWrapper<SettlementPeriod> wrapper = new LambdaQueryWrapper<>();

        if (request.getPlatform() != null && !request.getPlatform().isEmpty()) {
            // 按平台筛选需要关联查询，这里暂时不做
        }
        if (request.getStartDate() != null) {
            wrapper.ge(SettlementPeriod::getStartDate, request.getStartDate());
        }
        if (request.getEndDate() != null) {
            wrapper.le(SettlementPeriod::getEndDate, request.getEndDate());
        }
        if (request.getSettlementPeriodId() != null) {
            wrapper.eq(SettlementPeriod::getId, request.getSettlementPeriodId());
        }

        wrapper.orderByDesc(SettlementPeriod::getCreatedAt);

        List<SettlementPeriod> periods = periodRepository.selectList(wrapper);

        return periods.stream().map(period -> SettlementPeriodDTO.builder()
                .id(period.getId())
                .periodNo(period.getPeriodNo())
                .periodType(period.getPeriodType())
                .startDate(period.getStartDate())
                .endDate(period.getEndDate())
                .periodStatus(period.getPeriodStatus())
                .orderCount(period.getOrderCount())
                .totalOrderAmount(period.getTotalOrderAmount())
                .totalSettlementAmount(period.getTotalSettlementAmount())
                .totalPlatformFee(period.getTotalPlatformFee())
                .settlementTime(period.getSettlementTime())
                .remark(period.getRemark())
                .createdAt(period.getCreatedAt())
                .updatedAt(period.getUpdatedAt())
                .build())
                .collect(Collectors.toList());
    }

    // ==================== 统计报表 ====================

    @Override
    public SettlementStatisticsDTO getStatistics(SettlementQueryRequest request) {
        LambdaQueryWrapper<OrderSettlement> wrapper = new LambdaQueryWrapper<>();

        if (request.getPlatform() != null && !request.getPlatform().isEmpty()) {
            wrapper.eq(OrderSettlement::getPlatform, request.getPlatform());
        }
        if (request.getShopId() != null) {
            wrapper.eq(OrderSettlement::getShopId, request.getShopId());
        }
        if (request.getStartDate() != null) {
            wrapper.ge(OrderSettlement::getPaymentTime, request.getStartDate().atStartOfDay());
        }
        if (request.getEndDate() != null) {
            wrapper.le(OrderSettlement::getPaymentTime, request.getEndDate().atTime(23, 59, 59));
        }

        List<OrderSettlement> settlements = settlementRepository.selectList(wrapper);

        // 状态统计
        Map<String, Long> statusCountMap = settlements.stream()
                .collect(Collectors.groupingBy(OrderSettlement::getSettlementStatus, Collectors.counting()));

        // 金额统计
        BigDecimal totalOrderAmount = settlements.stream().map(OrderSettlement::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalDiscountAmount = settlements.stream().map(OrderSettlement::getDiscountAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalFreight = settlements.stream().map(OrderSettlement::getFreight).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalPlatformFee = settlements.stream().map(OrderSettlement::getPlatformFee).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalSettlementAmount = settlements.stream().map(OrderSettlement::getSettlementAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

        // 已结算/待结算/冻结
        BigDecimal settledAmount = settlements.stream()
                .filter(s -> OrderSettlement.STATUS_SETTLED.equals(s.getSettlementStatus()))
                .map(OrderSettlement::getSettlementAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal pendingAmount = settlements.stream()
                .filter(s -> OrderSettlement.STATUS_PENDING.equals(s.getSettlementStatus()))
                .map(OrderSettlement::getSettlementAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal frozenAmount = settlements.stream()
                .filter(s -> OrderSettlement.STATUS_FROZEN.equals(s.getSettlementStatus()))
                .map(OrderSettlement::getSettlementAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 平台维度统计
        List<SettlementStatisticsDTO.PlatformStatistics> platformStats = settlements.stream()
                .collect(Collectors.groupingBy(OrderSettlement::getPlatform))
                .entrySet().stream()
                .map(entry -> SettlementStatisticsDTO.PlatformStatistics.builder()
                        .platform(entry.getKey())
                        .orderCount((long) entry.getValue().size())
                        .orderAmount(entry.getValue().stream().map(OrderSettlement::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add))
                        .platformFee(entry.getValue().stream().map(OrderSettlement::getPlatformFee).reduce(BigDecimal.ZERO, BigDecimal::add))
                        .settlementAmount(entry.getValue().stream().map(OrderSettlement::getSettlementAmount).reduce(BigDecimal.ZERO, BigDecimal::add))
                        .build())
                .collect(Collectors.toList());

        // 店铺维度统计
        List<SettlementStatisticsDTO.ShopStatistics> shopStats = settlements.stream()
                .collect(Collectors.groupingBy(s -> s.getShopId() + "-" + s.getShopName()))
                .entrySet().stream()
                .map(entry -> {
                    String[] parts = entry.getKey().split("-", 2);
                    List<OrderSettlement> shopSettlements = entry.getValue();
                    return SettlementStatisticsDTO.ShopStatistics.builder()
                            .shopId(Long.parseLong(parts[0]))
                            .shopName(parts[1])
                            .platform(shopSettlements.isEmpty() ? null : shopSettlements.get(0).getPlatform())
                            .orderCount((long) shopSettlements.size())
                            .orderAmount(shopSettlements.stream().map(OrderSettlement::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add))
                            .platformFee(shopSettlements.stream().map(OrderSettlement::getPlatformFee).reduce(BigDecimal.ZERO, BigDecimal::add))
                            .settlementAmount(shopSettlements.stream().map(OrderSettlement::getSettlementAmount).reduce(BigDecimal.ZERO, BigDecimal::add))
                            .build();
                })
                .collect(Collectors.toList());

        return SettlementStatisticsDTO.builder()
                .totalOrderCount((long) settlements.size())
                .totalOrderAmount(totalOrderAmount)
                .totalDiscountAmount(totalDiscountAmount)
                .totalFreight(totalFreight)
                .totalPlatformFee(totalPlatformFee)
                .totalSettlementAmount(totalSettlementAmount)
                .settledAmount(settledAmount)
                .pendingSettlementAmount(pendingAmount)
                .frozenAmount(frozenAmount)
                .statusCountMap(statusCountMap)
                .platformStatistics(platformStats)
                .shopStatistics(shopStats)
                .startTime(request.getStartDate() != null ? request.getStartDate().atStartOfDay() : null)
                .endTime(request.getEndDate() != null ? request.getEndDate().atTime(23, 59, 59) : null)
                .build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SettlementReport generateReport(String reportType, Long shopId, String platform, LocalDate startDate, LocalDate endDate) {
        SettlementReport report = SettlementReport.builder()
                .reportNo(generateReportNo(reportType))
                .reportType(reportType)
                .shopId(shopId)
                .platform(platform)
                .startDate(startDate)
                .endDate(endDate)
                .reportDate(LocalDate.now())
                .reportStatus(SettlementReport.STATUS_GENERATING)
                .createdAt(LocalDateTime.now())
                .build();

        // 统计结算数据
        SettlementQueryRequest request = SettlementQueryRequest.builder()
                .shopId(shopId)
                .platform(platform)
                .startDate(startDate)
                .endDate(endDate)
                .build();

        SettlementStatisticsDTO stats = getStatistics(request);

        report.setOrderCount(stats.getTotalOrderCount().intValue());
        report.setTotalOrderAmount(stats.getTotalOrderAmount());
        report.setTotalDiscountAmount(stats.getTotalDiscountAmount());
        report.setTotalFreight(stats.getTotalFreight());
        report.setPlatformFee(stats.getTotalPlatformFee());
        report.setSettlementAmount(stats.getTotalSettlementAmount());
        report.setSettledAmount(stats.getSettledAmount());
        report.setPendingSettlementAmount(stats.getPendingSettlementAmount());
        report.setFrozenAmount(stats.getFrozenAmount());
        report.setReportStatus(SettlementReport.STATUS_GENERATED);
        report.setGeneratedAt(LocalDateTime.now());

        reportRepository.insert(report); // FIXED: 添加ReportRepository
        log.info("生成结算报表完成: {}", report.getReportNo());
        return report;
    }

    @Override
    public SettlementReport getReportById(Long id) {
        // TODO: 如果租户隔离需要校验tenantId，添加 tenantId 条件
        return reportRepository.selectById(id);
    }

    @Override
    public List<SettlementReport> queryReports(String reportType, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<SettlementReport> wrapper = new LambdaQueryWrapper<>();

        if (reportType != null && !reportType.isEmpty()) {
            wrapper.eq(SettlementReport::getReportType, reportType);
        }
        if (startDate != null) {
            wrapper.ge(SettlementReport::getStartDate, startDate);
        }
        if (endDate != null) {
            wrapper.le(SettlementReport::getEndDate, endDate);
        }

        wrapper.orderByDesc(SettlementReport::getCreatedAt);

        return reportRepository.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReport(Long reportId) {
        SettlementReport report = getReportById(reportId);
        if (report == null) {
            throw new IllegalArgumentException("结算报表不存在: " + reportId);
        }
        if (!SettlementReport.STATUS_GENERATED.equals(report.getReportStatus())) {
            throw new IllegalStateException("只有已生成的报表可以确认");
        }
        report.setReportStatus(SettlementReport.STATUS_CONFIRMED);
        report.setConfirmedAt(LocalDateTime.now());
        reportRepository.updateById(report);
        log.info("确认结算报表: {}, reportNo={}", reportId, report.getReportNo());
        return true;
    }

    // ==================== 店铺/平台维度统计 ====================

    @Override
    public BigDecimal getShopPendingSettlementAmount(Long shopId) {
        return settlementRepository.sumPendingSettlementByShop(shopId);
    }

    @Override
    public BigDecimal getPlatformPendingSettlementAmount(String platform) {
        return settlementRepository.sumPendingSettlementByPlatform(platform);
    }

    @Override
    public SettlementStatisticsDTO.ShopStatistics getShopSettlementSummary(Long shopId, LocalDate startDate, LocalDate endDate) {
        SettlementQueryRequest request = SettlementQueryRequest.builder()
                .shopId(shopId)
                .startDate(startDate)
                .endDate(endDate)
                .build();
        SettlementStatisticsDTO stats = getStatistics(request);
        if (stats.getShopStatistics().isEmpty()) {
            return null;
        }
        return stats.getShopStatistics().get(0);
    }

    @Override
    public SettlementStatisticsDTO.PlatformStatistics getPlatformSettlementSummary(String platform, LocalDate startDate, LocalDate endDate) {
        SettlementQueryRequest request = SettlementQueryRequest.builder()
                .platform(platform)
                .startDate(startDate)
                .endDate(endDate)
                .build();
        SettlementStatisticsDTO stats = getStatistics(request);
        if (stats.getPlatformStatistics().isEmpty()) {
            return null;
        }
        return stats.getPlatformStatistics().get(0);
    }

    // ==================== 私有辅助方法 ====================

    private String generateSettlementNo() {
        return "STL" + LocalDateTime.now().format(SETTLEMENT_NO_FORMATTER) + String.format("%04d", new Random().nextInt(10000));
    }

    private String generatePeriodNo(String periodType) {
        String prefix = "PER";
        switch (periodType) {
            case SettlementPeriod.TYPE_WEEKLY:
                prefix = "WKL";
                break;
            case SettlementPeriod.TYPE_MONTHLY:
                prefix = "MTH";
                break;
            case SettlementPeriod.TYPE_DAILY:
                prefix = "DAY";
                break;
        }
        return prefix + LocalDateTime.now().format(SETTLEMENT_NO_FORMATTER);
    }

    private String generateReportNo(String reportType) {
        String prefix = "RPT";
        switch (reportType) {
            case SettlementReport.TYPE_SHOP:
                prefix = "SHOP";
                break;
            case SettlementReport.TYPE_PLATFORM:
                prefix = "PLAT";
                break;
            case SettlementReport.TYPE_PERIOD:
                prefix = "PRDT";
                break;
        }
        return prefix + LocalDateTime.now().format(SETTLEMENT_NO_FORMATTER);
    }

    private SettlementDTO toDTO(OrderSettlement settlement) {
        return SettlementDTO.builder()
                .id(settlement.getId())
                .settlementNo(settlement.getSettlementNo())
                .orderId(settlement.getOrderId())
                .orderShortId(settlement.getOrderShortId())
                .platformOrderSn(settlement.getPlatformOrderSn())
                .platform(settlement.getPlatform())
                .shopId(settlement.getShopId())
                .shopName(settlement.getShopName())
                .orderAmount(settlement.getOrderAmount())
                .discountAmount(settlement.getDiscountAmount())
                .freight(settlement.getFreight())
                .totalAmount(settlement.getTotalAmount())
                .platformFee(settlement.getPlatformFee())
                .platformCommissionRate(settlement.getPlatformCommissionRate())
                .settlementAmount(settlement.getSettlementAmount())
                .settlementStatus(settlement.getSettlementStatus())
                .settlementPeriodId(settlement.getSettlementPeriodId())
                .settlementDate(settlement.getSettlementDate())
                .paymentTime(settlement.getPaymentTime())
                .deliveryTime(settlement.getDeliveryTime())
                .confirmTime(settlement.getConfirmTime())
                .confirmSettlementTime(settlement.getConfirmSettlementTime())
                .remark(settlement.getRemark())
                .createdAt(settlement.getCreatedAt())
                .updatedAt(settlement.getUpdatedAt())
                .build();
    }
}
