package com.yiqi.core.service.impl;

import java.util.*;
import java.math.BigDecimal;
import java.util.stream.Collectors;

import cn.binarywang.wx.miniapp.api.WxMaShopAfterSaleService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.common.enums.*;
import com.yiqi.common.utils.CurrencyUtil;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.core.service.ISettlementManageBillService;
import com.yiqi.core.service.ISettlementStoreClothStatisticsService;
import com.yiqi.order.domain.OrderRecharge;
import com.yiqi.order.domain.OrderRechargeRefund;
import com.yiqi.order.domain.dto.SettlementFactoryStatisticsDto;
import com.yiqi.order.service.IOrderRechargeRefundService;
import com.yiqi.order.service.IOrderRechargeService;
import com.yiqi.settlement.domain.dto.OrderStatisticsVO;
import com.yiqi.settlement.domain.dto.PaymentStatisticsVO;
import com.yiqi.settlement.domain.dto.StoreBillStatistics;
import com.yiqi.settlement.domain.dto.StoreChargeStatistics;
import com.yiqi.system.domain.ManageFactory;
import com.yiqi.system.domain.SysStore;
import com.yiqi.system.service.IManageFactoryService;
import com.yiqi.system.service.ISysStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yiqi.core.mapper.SettlementStoreStatisticsMapper;
import com.yiqi.core.domain.SettlementStoreStatistics;
import com.yiqi.core.service.ISettlementStoreStatisticsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

/**
 * 门店每日统计Service业务层处理
 *
 * @author douya
 * @date 2025-03-21
 */
@Slf4j
@Service
public class SettlementStoreStatisticsServiceImpl extends ServiceImpl<SettlementStoreStatisticsMapper, SettlementStoreStatistics> implements ISettlementStoreStatisticsService {

    @Autowired
    private ISettlementManageBillService settlementManageBillService;

    @Autowired
    private ISysStoreService storeService;

    @Autowired
    private IOrderRechargeService orderRechargeService;

    @Autowired
    private IOrderRechargeRefundService orderRechargeRefundService;

    @Autowired
    private ISettlementStoreClothStatisticsService settlementStoreClothStatisticsService;

    @Autowired
    private IManageFactoryService factoryService;

    /**
     * 查询门店每日统计
     *
     * @param id 门店每日统计主键
     * @return 门店每日统计
     */
    @Override
    public SettlementStoreStatistics selectSettlementStoreStatisticsById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<SettlementStoreStatistics> queryStoreStatisticsByDate(Long storeId, Date start, Date end) {
        Integer startDay = Integer.parseInt(DateUtil.format(start, "yyyyMMdd"));
        Integer endDay = Integer.parseInt(DateUtil.format(end, "yyyyMMdd"));
        List<SettlementStoreStatistics> result = baseMapper.queryStoreStatisticsByDate(storeId, startDay, endDay);
        return result;
    }

    @Override
    public SettlementStoreStatistics orderStatistics(Long storeId, Date start, Date end) {
        Integer startDay = start != null ? Integer.parseInt(DateUtil.format(start, "yyyyMMdd")) : null;
        Integer endDay = end != null ? Integer.parseInt(DateUtil.format(end, "yyyyMMdd")) : null;
        if (startDay != null && startDay.equals(endDay)) {
            return baseMapper.orderStatisticsByDate(storeId, startDay);
        }
        return baseMapper.orderStatistics(storeId, startDay, endDay);
    }

    @Override
    public List<SettlementStoreStatistics> generatePlatformStatisticsByDate(Date start, Date end) {
        Integer startDay = Integer.parseInt(DateUtil.format(start, "yyyyMMdd"));
        Integer endDay = Integer.parseInt(DateUtil.format(end, "yyyyMMdd"));
        List<SettlementStoreStatistics> result = baseMapper.totalByDate(startDay, endDay);
        return result;
    }

    @Override
    public List<SettlementStoreStatistics> generatePlatformStatisticsByStore(Date start, Date end) {
        Integer startDay = Integer.parseInt(DateUtil.format(start, "yyyyMMdd"));
        Integer endDay = Integer.parseInt(DateUtil.format(end, "yyyyMMdd"));
        List<SettlementStoreStatistics> result = baseMapper.totalByStore(startDay, endDay);
        for (SettlementStoreStatistics settlementStoreStatistics : result) {
            settlementStoreStatistics.setStoreName(storeService.getById(settlementStoreStatistics.getStoreId()).getName());
        }
        return result;
    }


    @Override
    public List<SettlementStoreStatistics> generateStoreStatisticsByStore(Long storeId, Date start, Date end) {
        Integer startDay = Integer.parseInt(DateUtil.format(start, "yyyyMMdd"));
        Integer endDay = Integer.parseInt(DateUtil.format(end, "yyyyMMdd"));
        List<SettlementStoreStatistics> result = baseMapper.orderStatisticsByStore(storeId, startDay, endDay);
        for (SettlementStoreStatistics settlementStoreStatistics : result) {
            settlementStoreStatistics.setStoreName(storeService.getById(settlementStoreStatistics.getStoreId()).getName());
        }
        return result;
    }

    @Override
    public List<SettlementStoreStatistics> generateStatisticsByDay(Long storeId, Date start, Date end) {
        // 1. 获取日期范围内的所有日期
        List<Date> dateList = new ArrayList<>();
        Date currentDate = end;
        while (currentDate.after(start)) {
            dateList.add(currentDate);
            currentDate = DateUtils.addDays(currentDate, -1);
        }
        List<SettlementStoreStatistics> statisticsList = new ArrayList<>();
        // 3. 为每个日期生成统计数据
        for (Date date : dateList) {
            SettlementStoreStatistics statistics = orderStatistics(storeId, date, date);
            statistics.setDay(Integer.parseInt(DateUtil.format(date, "yyyyMMdd")));
            statisticsList.add(statistics);
        }
        return statisticsList;
    }

    @Override
    public List<SettlementFactoryStatisticsDto> generateStatisticsByFactory(Long factoryId, Date start, Date end) {
        // 1. 获取日期范围内的所有日期
        List<ManageFactory> factoryList = factoryService.list(new QueryWrapper<ManageFactory>().lambda()
                .eq(factoryId != null, ManageFactory::getId, factoryId)
                .eq(ManageFactory::getStatus, StatusType.OK.getCode())
                .eq(ManageFactory::getDelFlag, StatusType.OK.getCode()));
        List<SettlementFactoryStatisticsDto> statisticsList = new ArrayList<>();
        // 3. 为每个日期生成统计数据
        for (ManageFactory factory : factoryList) {
            SettlementFactoryStatisticsDto statistics = settlementStoreClothStatisticsService.totalByCondition(factory.getId(), null, start, end);
            statistics.setFactoryName(factory.getFactoryName());
            statisticsList.add(statistics);
        }
        return statisticsList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateDayStatistics(Date date) {
        // 1. 获取所有有效门店
        List<SysStore> storeList = storeService.list(new QueryWrapper<SysStore>().lambda()
                        .gt(SysStore::getId, 0)
                .eq(SysStore::getDelFlag, DeleteStatus.OK.getCode()));
        if (CollUtil.isEmpty(storeList)) {
            return;
        }
        //删除旧数据
        baseMapper.delete(new QueryWrapper<SettlementStoreStatistics>().lambda()
                .eq(SettlementStoreStatistics::getDay, Integer.parseInt(DateUtil.format(date, "yyyyMMdd"))));

        // 2. 遍历门店生成统计数据
        for (SysStore store : storeList) {
            SettlementStoreStatistics settlementStoreStatistics = generateStoreStatistics(date, store.getId());
            //充值统计
            StoreChargeStatistics storeChargeStatistics = generateChargeStatistics(date, store.getId());
            settlementStoreStatistics.setChargeAmount(storeChargeStatistics.getRechargePayAmount());
            settlementStoreStatistics.setChargeCount(storeChargeStatistics.getRechargeCount());
            settlementStoreStatistics.setChargeRefundCount(storeChargeStatistics.getRefundCount());
            settlementStoreStatistics.setChargeRefundAmount(storeChargeStatistics.getRefundAmount());
            settlementStoreStatistics.setChargeArriveAmount(CurrencyUtil.add(storeChargeStatistics.getArriveCashAmount(), storeChargeStatistics.getArriveGiveAmount(), storeChargeStatistics.getArriveWelfareAmount()));
            settlementStoreStatistics.setChargeRefundArriveAmount(CurrencyUtil.add(storeChargeStatistics.getArriveCashRefundAmount(), storeChargeStatistics.getArriveGiveRefundAmount(), storeChargeStatistics.getArriveWelfareRefundAmount()));
            // 插入新的统计数据
            baseMapper.insert(settlementStoreStatistics);
        }
        //生成平台商品统计
        SettlementStoreStatistics settlementStoreStatistics = generateStoreStatistics(date, 0L);
//        StoreChargeStatistics storeChargeStatistics = generateChargeStatistics(date, null);
//        settlementStoreStatistics.setChargeAmount(storeChargeStatistics.getRechargePayAmount());
//        settlementStoreStatistics.setChargeCount(storeChargeStatistics.getRechargeCount());
//        settlementStoreStatistics.setChargeRefundCount(storeChargeStatistics.getRefundCount());
//        settlementStoreStatistics.setChargeRefundAmount(storeChargeStatistics.getRefundAmount());
//        settlementStoreStatistics.setChargeArriveAmount(CurrencyUtil.add(storeChargeStatistics.getArriveCashAmount(), storeChargeStatistics.getArriveGiveAmount(), storeChargeStatistics.getArriveWelfareAmount()));
//        settlementStoreStatistics.setChargeRefundArriveAmount(CurrencyUtil.add(storeChargeStatistics.getArriveCashRefundAmount(), storeChargeStatistics.getArriveGiveRefundAmount(), storeChargeStatistics.getArriveWelfareRefundAmount()));

        // 插入新的统计数据
        baseMapper.insert(settlementStoreStatistics);
    }

    @Override
    public StoreChargeStatistics chargeTotal(Long storeId) {
        return baseMapper.chargeTotal(storeId);
    }

    @Override
    public SettlementStoreStatistics generateStoreStatistics(Date date, Long storeId) {
        // 2.1 获取门店当日统计数据
        StoreBillStatistics statistics = null;
        if (storeId == 0L) {
            //获取平台统计
            statistics = settlementManageBillService.platformBillSettlement(
                    DateUtils.getStartTime(date),
                    DateUtils.getEndTime(date)
            );
        } else {
            statistics = settlementManageBillService.storeBillSettlement(
                    storeId,
                    DateUtils.getStartTime(date),
                    DateUtils.getEndTime(date)
            );
        }

        // 2.2 构建门店统计实体
        SettlementStoreStatistics storeStatistics = new SettlementStoreStatistics();
        storeStatistics.setStoreId(storeId);
        storeStatistics.setDay(Integer.valueOf(DateUtil.format(date, "yyyyMMdd")));
        storeStatistics.setCreateTime(DateUtils.getNowDate());

        // 2.3 设置洗衣订单统计
        OrderStatisticsVO clothStats = statistics.getClothOrderStats();
        if (clothStats != null) {
            storeStatistics.setClothOrderCount(clothStats.getOrderCount());
            storeStatistics.setClothCount(clothStats.getGoodsCount());
            storeStatistics.setClothOrderAmount(clothStats.getTotalAmount());
            storeStatistics.setClothReceiveAmount(clothStats.getTransactionAmount());
            storeStatistics.setClothWechatAmount(clothStats.getWechatAmount());
            storeStatistics.setClothAlipayAmount(clothStats.getAlipayAmount());
            storeStatistics.setClothCashAmount(clothStats.getCashAmount());
            storeStatistics.setClothMemberAmount(clothStats.getMemberAmount());
            storeStatistics.setClothRefundAmount(clothStats.getRefundAmount());
            storeStatistics.setClothAlipayRefundAmount(clothStats.getAlipayRefundAmount());
            storeStatistics.setClothWechatRefundAmount(clothStats.getWechatRefundAmount());
            storeStatistics.setClothCashRefundAmount(clothStats.getCashRefundAmount());
            storeStatistics.setClothUnionRefundAmount(clothStats.getUnionRefundAmount());
            storeStatistics.setClothMemberRefundAmount(clothStats.getMemberRefundAmount());
        }

        // 2.4 设置商品订单统计
        OrderStatisticsVO goodsStats = statistics.getGoodsOrderStats();
        if (goodsStats != null) {
            storeStatistics.setGoodsOrderCount(goodsStats.getOrderCount());
            storeStatistics.setGoodsCount(goodsStats.getGoodsCount());
            storeStatistics.setGoodsOrderAmount(goodsStats.getTotalAmount());
            storeStatistics.setGoodsWechatAmount(goodsStats.getWechatAmount());
            storeStatistics.setGoodsAlipayAmount(goodsStats.getAlipayAmount());
            storeStatistics.setGoodsCashAmount(goodsStats.getCashAmount());
            storeStatistics.setGoodsMemberAmount(goodsStats.getMemberAmount());
            storeStatistics.setGoodsRefundAmount(goodsStats.getRefundAmount());

            storeStatistics.setGoodsAlipayRefundAmount(goodsStats.getAlipayRefundAmount());
            storeStatistics.setGoodsWechatRefundAmount(goodsStats.getWechatRefundAmount());
            storeStatistics.setGoodsCashRefundAmount(goodsStats.getCashRefundAmount());
            storeStatistics.setGoodsUnionRefundAmount(goodsStats.getUnionRefundAmount());
            storeStatistics.setGoodsMemberRefundAmount(goodsStats.getMemberRefundAmount());
            storeStatistics.setGoodsReceiveAmount(goodsStats.getTransactionAmount());
        }
        return storeStatistics;
    }

    @Override
    public StoreChargeStatistics generateChargeStatistics(Date date, Long storeId) {
        try {
            // 1. 查询门店当日充值记录
            List<OrderRecharge> rechargeList = orderRechargeService.list(new QueryWrapper<OrderRecharge>().lambda()
                    .eq(storeId != null, OrderRecharge::getStoreId, storeId)
                    .eq(OrderRecharge::getPayStatus, PayStatus.HAS_PAY.getCode())
                    .eq(OrderRecharge::getDelFlag, StatusType.OK.getCode())
                    .between(OrderRecharge::getPayTime, DateUtils.getStartTime(date), DateUtils.getEndTime(date)));

            // 2. 查询门店当日充值退款记录
            List<OrderRechargeRefund> refundList = orderRechargeRefundService.list(new QueryWrapper<OrderRechargeRefund>().lambda()
                    .eq(storeId != null, OrderRechargeRefund::getStoreId, storeId)
                    .eq(OrderRechargeRefund::getRefundStatus, RechargeRefundStatusType.REFUND_SUCCESS.getCode())
                    .eq(OrderRechargeRefund::getDelFlag, StatusType.OK.getCode())
                    .between(OrderRechargeRefund::getRefundTime, DateUtils.getStartTime(date), DateUtils.getEndTime(date)));
            // 3. 构建统计实体
            StoreChargeStatistics statistics = new StoreChargeStatistics();
            statistics.setStoreId(storeId);
            statistics.setDay(Integer.valueOf(DateUtil.format(date, "yyyyMMdd")));
            genStoreChargeStatistics(statistics, rechargeList, refundList);
            return statistics;

        } catch (Exception e) {
            log.error("生成门店[{}]充值统计失败: {}", storeId, e.getMessage());
            throw new RuntimeException("生成门店充值统计失败", e);
        }
    }

    @Override
    public List<StoreChargeStatistics> generateChargeStatisticsByDate(Long storeId, Date startDate, Date endDate) {
        List<StoreChargeStatistics> resultList = new ArrayList<>();
        try {
            // 1. 查询门店当日充值记录
            List<OrderRecharge> rechargeList = orderRechargeService.list(new QueryWrapper<OrderRecharge>().lambda()
                    .eq(storeId != 0L, OrderRecharge::getStoreId, storeId)
                    .eq(OrderRecharge::getPayStatus, PayStatus.HAS_PAY.getCode())
                    .eq(OrderRecharge::getDelFlag, StatusType.OK.getCode())
                    .between(OrderRecharge::getPayTime, startDate, endDate));

            // 2. 查询门店当日充值退款记录
            List<OrderRechargeRefund> refundList = orderRechargeRefundService.list(new QueryWrapper<OrderRechargeRefund>().lambda()
                    .eq(storeId != 0L, OrderRechargeRefund::getStoreId, storeId)
                    .eq(OrderRechargeRefund::getRefundStatus, RechargeRefundStatusType.REFUND_SUCCESS.getCode())
                    .eq(OrderRechargeRefund::getDelFlag, StatusType.OK.getCode())
                    .between(OrderRechargeRefund::getRefundTime, startDate, endDate));


            // 3. 按日期分组统计
            Map<Integer, List<OrderRecharge>> dateRechargeMap = rechargeList.stream()
                    .collect(Collectors.groupingBy(recharge ->
                            Integer.valueOf(DateUtil.format(recharge.getCreateTime(), "yyyyMMdd"))));

            Map<Integer, List<OrderRechargeRefund>> dateRefundMap = refundList.stream()
                    .collect(Collectors.groupingBy(refund ->
                            Integer.valueOf(DateUtil.format(refund.getCreateTime(), "yyyyMMdd"))));

            // 4. 遍历每一天生成统计数据
            Set<Integer> allDays = new HashSet<>();
            allDays.addAll(dateRechargeMap.keySet());
            allDays.addAll(dateRefundMap.keySet());

            // 1. 获取日期范围内的所有日期
            List<Date> dateList = new ArrayList<>();
            Date currentDate = endDate;
            while (currentDate.after(startDate)) {
                dateList.add(currentDate);
                currentDate = DateUtils.addDays(currentDate, -1);
            }
            List<SettlementFactoryStatisticsDto> statisticsList = new ArrayList<>();
            // 3. 为每个日期生成统计数据
            for (Date date : dateList) {
                Integer day = Integer.parseInt(DateUtil.format(date, "yyyyMMdd"));
                List<OrderRecharge> dayRechargeList = dateRechargeMap.getOrDefault(day, new ArrayList<>());
                List<OrderRechargeRefund> dayRefundList = dateRefundMap.getOrDefault(day, new ArrayList<>());
                // 4.1 构建统计实体
                StoreChargeStatistics statistics = new StoreChargeStatistics();
                statistics.setStoreId(storeId);
                statistics.setDay(day);
                genStoreChargeStatistics(statistics, dayRechargeList, dayRefundList);
                resultList.add(statistics);
            }
        } catch (Exception e) {
            log.error("生成门店[{}]充值统计失败: {}", storeId, e.getMessage());
            throw new RuntimeException("生成门店充值统计失败", e);
        }
        return resultList;
    }

    @Override
    public Page<StoreChargeStatistics> generateChargeStatisticsByStore(Long storeId, Integer storeType, Date start, Integer pageSize, Integer pageNum) {
        // 1. 获取所有有效门店
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("del_flag", StatusType.OK.getCode());
        if (storeId != null) {
            queryWrapper.eq("store_id", storeId);
        }
        if(storeType != null){
            queryWrapper.eq("store_type", storeType);
        }
        Page<StoreChargeStatistics> pageRes = new Page<>(pageNum, pageSize);
        Page page = new Page<>(pageNum, pageSize);
        Page<SysStore> storeList = storeService.page(page, queryWrapper);
        List<StoreChargeStatistics> resultList = new ArrayList<>();
        // 2. 遍历门店生成统计数据
        for (SysStore store : storeList.getRecords()) {
            try {
                // 1. 查询门店当日充值记录
                List<OrderRecharge> rechargeList = orderRechargeService.list(new QueryWrapper<OrderRecharge>().lambda()
                        .eq(OrderRecharge::getStoreId, store.getId())
                        .eq(OrderRecharge::getPayStatus, PayStatus.HAS_PAY.getCode())
                        .eq(OrderRecharge::getDelFlag, StatusType.OK.getCode())
                        .between(OrderRecharge::getPayTime, DateUtils.getStartTime(start), DateUtils.getEndTime(start)));

                // 2. 查询门店当日充值退款记录
                List<OrderRechargeRefund> refundList = orderRechargeRefundService.list(new QueryWrapper<OrderRechargeRefund>().lambda()
                        .eq(OrderRechargeRefund::getStoreId, storeId)
                        .eq(OrderRechargeRefund::getRefundStatus, RechargeRefundStatusType.REFUND_SUCCESS.getCode())
                        .eq(OrderRechargeRefund::getDelFlag, StatusType.OK.getCode())
                        .between(OrderRechargeRefund::getRefundTime, DateUtils.getStartTime(start), DateUtils.getEndTime(start)));
                // 4.1 构建统计实体
                StoreChargeStatistics statistics = new StoreChargeStatistics();
                statistics.setStoreId(storeId);
                statistics.setStoreName(store.getName());
                statistics.setDay(Integer.valueOf(DateUtil.format(start, "yyyyMMdd")));
                genStoreChargeStatistics(statistics, rechargeList, refundList);
                resultList.add(statistics);
            } catch (Exception e) {
                // 记录错误日志，继续处理下一个门店
                log.error("统计门店[{}]每日充值统计失败: {}", store.getId(), e.getMessage());
            }
        }
        pageRes.setRecords(resultList);
        pageRes.setTotal(storeList.getTotal());
        return pageRes;
    }


    private void genStoreChargeStatistics(StoreChargeStatistics statistics, List<OrderRecharge> rechargeList, List<OrderRechargeRefund> refundList) {

        // 4. 计算充值统计
        BigDecimal totalRechargeAmount = BigDecimal.ZERO;
        BigDecimal rechargePayAmount = BigDecimal.ZERO;
        BigDecimal totalWelfareAmount = BigDecimal.ZERO;
        BigDecimal totalGiveAmount = BigDecimal.ZERO;
        int rechargeCount = 0;

        // 5. 计算支付方式统计
        BigDecimal wxPayAmount = BigDecimal.ZERO;
        BigDecimal aliPayAmount = BigDecimal.ZERO;
        BigDecimal cashPayAmount = BigDecimal.ZERO;
        BigDecimal passwordCardAmount = BigDecimal.ZERO;

        for (OrderRecharge recharge : rechargeList) {
            // 累加充值金额
            rechargePayAmount = rechargePayAmount.add(recharge.getPayAmount());
            totalRechargeAmount = totalRechargeAmount.add(recharge.getRechargeAmount());
            totalWelfareAmount = totalWelfareAmount.add(recharge.getWelfareAmount());
            totalGiveAmount = totalGiveAmount.add(recharge.getGiveAmount());
            rechargeCount++;
            if (recharge.getPayType() == PayType.RECHARGE_CARD.getCode()) {
                passwordCardAmount = passwordCardAmount.add(recharge.getRechargeAmount());
            } else {
                // 累加支付方式金额
                wxPayAmount = wxPayAmount.add(recharge.getWxPayAmount());
                aliPayAmount = aliPayAmount.add(recharge.getAliPayAmount());
                cashPayAmount = cashPayAmount.add(recharge.getCashPayAmount());
            }
        }

        BigDecimal totalRechargeRefundAmount = BigDecimal.ZERO;
        BigDecimal totalWelfareRefundAmount = BigDecimal.ZERO;
        BigDecimal totalGiveRefundAmount = BigDecimal.ZERO;

        // 6. 计算退款统计
        BigDecimal totalRefundAmount = BigDecimal.ZERO;
        BigDecimal wxRefundAmount = BigDecimal.ZERO;
        BigDecimal aliRefundAmount = BigDecimal.ZERO;
        BigDecimal cashRefundAmount = BigDecimal.ZERO;
        BigDecimal passwordCardRefundAmount = BigDecimal.ZERO;
        int refundCount = 0;

        for (OrderRechargeRefund refund : refundList) {
            refundCount++;
            // 累加充值金额
            totalRechargeRefundAmount = totalRechargeRefundAmount.add(refund.getRechargeBalance());
            totalWelfareRefundAmount = totalWelfareRefundAmount.add(refund.getWelfareBalance());
            totalGiveRefundAmount = totalGiveRefundAmount.add(refund.getGiveBalance());
            totalRefundAmount = totalRefundAmount.add(refund.getRefundAmount());

            if (refund.getRefundType() == PayType.RECHARGE_CARD.getCode()) {
                passwordCardRefundAmount = passwordCardRefundAmount.add(refund.getRechargeBalance());
            } else {
                // 累加支付方式金额
                wxRefundAmount = wxRefundAmount.add(refund.getWxRefundAmount());
                aliRefundAmount = aliRefundAmount.add(refund.getAliRefundAmount());
                cashRefundAmount = cashRefundAmount.add(refund.getCashRefundAmount());
            }
        }

        // 7. 设置统计数据
        statistics.setRechargeCount(rechargeCount);
        statistics.setRechargePayAmount(rechargePayAmount);
        statistics.setArriveWelfareAmount(totalWelfareAmount);
        statistics.setArriveGiveAmount(totalGiveAmount);
        statistics.setArriveCashAmount(totalRechargeAmount);

        // 8. 设置支付方式统计
        statistics.setWechatPayAmount(wxPayAmount);
        statistics.setAlipayAmount(aliPayAmount);
        statistics.setCashPayAmount(cashPayAmount);
        statistics.setCardPayAmount(passwordCardAmount);

        // 9. 设置退款统计
        statistics.setRefundCount(refundCount);
        statistics.setRefundAmount(totalRefundAmount);
        statistics.setWechatRefundAmount(wxRefundAmount);
        statistics.setAlipayRefundAmount(aliRefundAmount);
        statistics.setCashRefundAmount(cashRefundAmount);
        statistics.setCardRefundAmount(passwordCardRefundAmount);

        // 9. 设置退款统计
        statistics.setArriveWelfareRefundAmount(totalWelfareRefundAmount);
        statistics.setArriveGiveRefundAmount(totalGiveRefundAmount);
        statistics.setArriveCashRefundAmount(totalRechargeRefundAmount);
    }

    /**
     * 查询门店每日统计列表
     *
     * @param settlementStoreStatistics 门店每日统计
     * @return 门店每日统计
     */
    @Override
    public List<SettlementStoreStatistics> selectSettlementStoreStatisticsList(SettlementStoreStatistics settlementStoreStatistics) {
        return baseMapper.selectSettlementStoreStatisticsList(settlementStoreStatistics);
    }

    /**
     * 新增门店每日统计
     *
     * @param settlementStoreStatistics 门店每日统计
     * @return 结果
     */
    @Override
    public int insertSettlementStoreStatistics(SettlementStoreStatistics settlementStoreStatistics) {
        settlementStoreStatistics.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(settlementStoreStatistics);
    }

    /**
     * 修改门店每日统计
     *
     * @param settlementStoreStatistics 门店每日统计
     * @return 结果
     */
    @Override
    public int updateSettlementStoreStatistics(SettlementStoreStatistics settlementStoreStatistics) {
        settlementStoreStatistics.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(settlementStoreStatistics);
    }

    /**
     * 批量删除门店每日统计
     *
     * @param ids 需要删除的门店每日统计主键
     * @return 结果
     */
    @Override
    public int deleteSettlementStoreStatisticsByIds(Long[] ids) {
        return baseMapper.deleteSettlementStoreStatisticsByIds(ids);
    }

    /**
     * 删除门店每日统计信息
     *
     * @param id 门店每日统计主键
     * @return 结果
     */
    @Override
    public int deleteSettlementStoreStatisticsById(Long id) {
        return baseMapper.deleteSettlementStoreStatisticsById(id);
    }


}
