package com.yc.ship.module.trade.service.report.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.excel.core.util.ExcelUtils;
import com.yc.ship.module.trade.controller.admin.report.vo.DistributorBalancePageReqVO;
import com.yc.ship.module.trade.controller.admin.report.vo.DistributorBalanceRespVO;
import com.yc.ship.module.trade.dal.mysql.report.DistributorBalanceMapper;
import com.yc.ship.module.trade.service.report.DistributorBalanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 预存款余额表 Service 实现类
 *
 * @author 管理员
 */
@Service
@Slf4j
public class DistributorBalanceServiceImpl implements DistributorBalanceService {

    @Resource
    private DistributorBalanceMapper distributorBalanceMapper;

    /**
     * 查询预存款余额表分页
     *
     * @param pageReqVO 分页查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<DistributorBalanceRespVO> getDistributorBalancePage(DistributorBalancePageReqVO pageReqVO) {
        IPage<DistributorBalanceRespVO> page = distributorBalanceMapper.selectDistributorBalancePage(
                new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize()), pageReqVO);
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    /**
     * 导出预存款余额表 Excel
     *
     * @param pageReqVO 查询条件
     * @param response  HTTP响应
     * @throws IOException IO异常
     */
    @Override
    public void exportDistributorBalanceExcel(DistributorBalancePageReqVO pageReqVO,
                                               HttpServletResponse response) throws IOException {
        // 1. 查询所有数据（不分页）
        List<DistributorBalanceRespVO> list = distributorBalanceMapper.selectDistributorBalanceExportList(pageReqVO);
        if (CollUtil.isEmpty(list)) {
            log.warn("[exportDistributorBalanceExcel] 无数据可导出");
        } else {
            // 2. 计算合计行并追加到列表末尾
            DistributorBalanceRespVO summary = calculateSummary(list);
            list.add(summary);
        }
        // 3. 导出 Excel（数字字段使用 @NumberFormat 注解确保导出为数字格式）
        ExcelUtils.write(response, "预存款余额表.xls", "预存款余额表", DistributorBalanceRespVO.class, list);
    }

    /**
     * 计算合计行数据
     */
    private DistributorBalanceRespVO calculateSummary(List<DistributorBalanceRespVO> list) {
        DistributorBalanceRespVO summary = new DistributorBalanceRespVO();
        summary.setTravelAgency("合计");

        BigDecimal totalRechargeAmount = BigDecimal.ZERO;
        BigDecimal totalConsumeAmount = BigDecimal.ZERO;
        BigDecimal totalBalance = BigDecimal.ZERO;

        for (DistributorBalanceRespVO item : list) {
            totalRechargeAmount = totalRechargeAmount.add(
                    item.getTotalRechargeAmount() != null ? item.getTotalRechargeAmount() : BigDecimal.ZERO);
            totalConsumeAmount = totalConsumeAmount.add(
                    item.getTotalConsumeAmount() != null ? item.getTotalConsumeAmount() : BigDecimal.ZERO);
            totalBalance = totalBalance.add(
                    item.getBalance() != null ? item.getBalance() : BigDecimal.ZERO);
        }

        summary.setTotalRechargeAmount(totalRechargeAmount);
        summary.setTotalConsumeAmount(totalConsumeAmount);
        summary.setBalance(totalBalance);
        return summary;
    }

}
