package org.dromara.mall.statistics.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mall.statistics.domain.bo.StatisticsQueryBo;
import org.dromara.mall.statistics.domain.vo.MemberStatisticsVo;
import org.dromara.mall.statistics.domain.vo.TransactionStatisticsVo;
import org.dromara.mall.statistics.mapper.MallStatisticsMapper;
import org.dromara.mall.statistics.service.MallStatisticsService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计服务实现类
 *
 * @author pengles
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MallStatisticsServiceImpl implements MallStatisticsService {

    private final MallStatisticsMapper statisticsMapper;

    /**
     * 获取交易统计
     */
    @Override
    public TransactionStatisticsVo getTransactionStatistics(StatisticsQueryBo queryBo) {
        Date startDate = queryBo != null ? queryBo.getStartDate() : null;
        Date endDate = queryBo != null ? queryBo.getEndDate() : null;
        Integer limit = queryBo != null && queryBo.getLimit() != null ? queryBo.getLimit() : 10;

        TransactionStatisticsVo vo = new TransactionStatisticsVo();

        // 统计总订单数和总金额
        Map<String, Object> orderStats = statisticsMapper.countOrderStatistics(startDate, endDate);
        if (orderStats != null) {
            vo.setTotalOrderCount(getLongValue(orderStats, "totalOrderCount"));
            vo.setTotalSalesAmount(getLongValue(orderStats, "totalSalesAmount"));
        }

        // 统计已支付订单数和金额
        Map<String, Object> paidStats = statisticsMapper.countPaidOrderStatistics(startDate, endDate);
        if (paidStats != null) {
            vo.setPaidOrderCount(getLongValue(paidStats, "paidOrderCount"));
            vo.setPaidAmount(getLongValue(paidStats, "paidAmount"));
        }

        // 统计退款金额
        Long refundAmount = statisticsMapper.sumRefundAmount(startDate, endDate);
        vo.setRefundAmount(refundAmount != null ? refundAmount : 0L);

        // 今日统计（如果没有指定日期范围，计算今日）
        if (startDate == null && endDate == null) {
            Date todayStart = DateUtil.beginOfDay(new Date());
            Date todayEnd = DateUtil.endOfDay(new Date());

            Map<String, Object> todayOrderStats = statisticsMapper.countOrderStatistics(todayStart, todayEnd);
            if (todayOrderStats != null) {
                vo.setTodayOrderCount(getLongValue(todayOrderStats, "totalOrderCount"));
                vo.setTodaySalesAmount(getLongValue(todayOrderStats, "totalSalesAmount"));
            } else {
                vo.setTodayOrderCount(0L);
                vo.setTodaySalesAmount(0L);
            }
        } else {
            // 如果指定了日期范围，今日统计为0或null
            vo.setTodayOrderCount(0L);
            vo.setTodaySalesAmount(0L);
        }

        // 趋势数据
        List<TransactionStatisticsVo.DailyStatisticsVo> trendData = statisticsMapper.countDailyOrderStatistics(startDate, endDate);
        vo.setTrendData(trendData != null ? trendData : CollUtil.newArrayList());

        // 商品销售排行
        List<TransactionStatisticsVo.ProductSalesRankVo> productRank = statisticsMapper.queryProductSalesRank(startDate, endDate, limit);
        vo.setProductSalesRank(productRank != null ? productRank : CollUtil.newArrayList());

        return vo;
    }

    /**
     * 获取会员统计
     */
    @Override
    public MemberStatisticsVo getMemberStatistics(StatisticsQueryBo queryBo) {
        // TODO: 实现会员统计功能
        // 由于会员模块可能不在mall模块中，这里先返回基础结构
        MemberStatisticsVo vo = new MemberStatisticsVo();
        vo.setTotalMemberCount(0L);
        vo.setTodayNewMemberCount(0L);
        vo.setActiveMemberCount(0L);
        vo.setGrowthTrend(CollUtil.newArrayList());
        vo.setConsumptionStats(CollUtil.newArrayList());
        return vo;
    }

    /**
     * 从Map中获取Long值
     */
    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return 0L;
        }
        if (value instanceof Long) {
            return (Long) value;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.parseLong(value.toString());
        } catch (Exception e) {
            log.warn("无法转换值 {} 为Long类型: {}", value, e.getMessage());
            return 0L;
        }
    }

}
