package com.czg.service.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.czg.order.entity.ShopTableOrderStatistic;
import com.czg.order.param.TableSummaryParam;
import com.czg.order.service.DataSummaryService;
import com.czg.order.service.ShopTableOrderStatisticService;
import com.czg.order.vo.TableSummaryInfoVo;
import com.czg.service.order.mapper.ShopTableOrderStatisticMapper;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 台桌订单统计表 服务层实现。
 *
 * @author zs
 * @since 2025-03-07
 */
@Service
@Slf4j
public class ShopTableOrderStatisticServiceImpl extends ServiceImpl<ShopTableOrderStatisticMapper, ShopTableOrderStatistic> implements ShopTableOrderStatisticService {
    @Resource
    private DataSummaryService dataSummaryService;
    @Resource
    private ShopTableOrderStatisticMapper shopTableOrderStatisticMapper;

    @Override
    public Page<ShopTableOrderStatistic> summary(Long shopId, String startTime, String endTime) {
        Page<Object> page = PageUtil.buildPage();
        PageHelper.startPage(Math.toIntExact(page.getPageNumber()), Math.toIntExact(page.getPageSize()));
        return PageUtil.convert(new PageInfo<>(mapper.selectSummary(shopId, startTime, endTime)));
    }

    @Override
    public boolean addInfo(long shopId, long tableId, long count, BigDecimal amount) {
        ShopTableOrderStatistic statistic = getOne(new QueryWrapper().eq(ShopTableOrderStatistic::getShopId, shopId).eq(ShopTableOrderStatistic::getTableId, tableId)
                .eq(ShopTableOrderStatistic::getCreateDay, DateUtil.date().toDateStr()));
        if (statistic == null) {
            statistic = new ShopTableOrderStatistic();
            statistic.setShopId(shopId);
            statistic.setTableId(tableId);
            statistic.setCreateDay(DateUtil.date().toSqlDate());
            statistic.setOrderCount(count);
            statistic.setOrderAmount(amount);
            save(statistic);
        }
        return mapper.incrInfo(shopId, tableId, count, amount, DateUtil.date().toDateStr());
    }

    @Data
    private static class StatisticTask {
        private long successCount = 0;
        private BigDecimal successAmount = BigDecimal.ZERO;
        private long refundCount = 0;
        private BigDecimal refundAmount = BigDecimal.ZERO;
    }

    @Override
    public void statistic(DateTime dateTime) {
        // 获取前一天的开始时间（00:00:00）
        DateTime startOfDay = DateUtil.beginOfDay(dateTime);
        // 获取前一天的结束时间（23:59:59）
        DateTime endOfDay = DateUtil.endOfDay(dateTime);
        List<Long> shopIdList = dataSummaryService.getShopIdList();
        if (CollUtil.isEmpty(shopIdList)) {
            return;
        }
        List<List<Long>> split = CollUtil.split(shopIdList, 5);
        for (List<Long> splitIdList : split) {
            splitIdList.parallelStream().forEach(shopId -> {
                TableSummaryParam param = new TableSummaryParam();
                param.setShopId(shopId);
                param.setBeginDate(startOfDay.toStringDefaultTimeZone());
                param.setEndDate(endOfDay.toStringDefaultTimeZone());
                // 删除之前统计数据
                getMapper()
                        .deleteByQuery(
                        new QueryWrapper()
                                .eq("shop_id", shopId)
                                .eq("create_day", dateTime.toDateStr()));
                // 重新统计数据
                List<TableSummaryInfoVo> list = shopTableOrderStatisticMapper.findSummaryList2(param);
                for (TableSummaryInfoVo dto : list) {
                    ShopTableOrderStatistic entity = new ShopTableOrderStatistic();
                    entity.setTableId(dto.getTableId());
                    entity.setTableCode(dto.getTableCode());
                    entity.setTableName(dto.getTableName());
                    entity.setAreaName(dto.getAreaName());
                    entity.setOrderCount(dto.getOrderCount());
                    entity.setOrderAmount(dto.getOrderAmount());
                    entity.setRefundCount(dto.getRefundCount());
                    entity.setRefundAmount(dto.getRefundAmount());
                    entity.setShopId(shopId);
                    entity.setCreateDay(dateTime.toJdkDate());
                    if (entity.getOrderCount() == 0L && entity.getRefundCount() == 0L) {
                        log.info("店铺：{}，{}，没有要存档的台桌统计数据", shopId, dateTime.toDateStr());
                    } else {
                        save(entity);
                    }
                }
            });
        }
    }

}
