package com.fs.live.service.impl;


import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.live.domain.LiveRewardRecord;
import com.fs.live.mapper.LiveRewardRecordMapper;
import com.fs.live.service.ILiveRewardRecordService;
import com.fs.live.vo.LiveRewardRecordStatisticsVo;
import com.fs.live.vo.LiveRewardRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 用户直播间奖励记录Service业务层处理
 *
 * @author fs
 * @date 2025-08-27
 */
@Service
public class LiveRewardRecordServiceImpl implements ILiveRewardRecordService {
    @Autowired
    private LiveRewardRecordMapper baseMapper;

    /**
     * 查询用户直播间奖励记录
     *
     * @param id 用户直播间奖励记录主键
     * @return 用户直播间奖励记录
     */
    @Override
    public LiveRewardRecord selectLiveRewardRecordById(Long id)
    {
        return baseMapper.selectLiveRewardRecordById(id);
    }

    /**
     * 查询用户直播间奖励记录列表
     *
     * @param liveRewardRecord 用户直播间奖励记录
     * @return 用户直播间奖励记录
     */
    @Override
    public List<LiveRewardRecord> selectLiveRewardRecordList(LiveRewardRecord liveRewardRecord)
    {
        return baseMapper.selectLiveRewardRecordList(liveRewardRecord);
    }

    /**
     * 新增用户直播间奖励记录
     *
     * @param liveRewardRecord 用户直播间奖励记录
     * @return 结果
     */
    @Override
    public int insertLiveRewardRecord(LiveRewardRecord liveRewardRecord)
    {
        liveRewardRecord.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertLiveRewardRecord(liveRewardRecord);
    }

    /**
     * 修改用户直播间奖励记录
     *
     * @param liveRewardRecord 用户直播间奖励记录
     * @return 结果
     */
    @Override
    public int updateLiveRewardRecord(LiveRewardRecord liveRewardRecord)
    {
        return baseMapper.updateLiveRewardRecord(liveRewardRecord);
    }

    /**
     * 批量删除用户直播间奖励记录
     *
     * @param ids 需要删除的用户直播间奖励记录主键
     * @return 结果
     */
    @Override
    public int deleteLiveRewardRecordByIds(Long[] ids)
    {
        return baseMapper.deleteLiveRewardRecordByIds(ids);
    }

    /**
     * 删除用户直播间奖励记录信息
     *
     * @param id 用户直播间奖励记录主键
     * @return 结果
     */
    @Override
    public int deleteLiveRewardRecordById(Long id)
    {
        return baseMapper.deleteLiveRewardRecordById(id);
    }


    @Override
    public R statistics(LiveRewardRecordVo param) {
        SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM");
        List<LiveRewardRecord> liveRewardRecords;
        if(param.getCompanyId() == null) param.setCompanyId(0L);
        if (param.getCompanyId() == 0L) {
            liveRewardRecords = baseMapper.selectLiveRewardRecordListByStep(param.getStep());
        } else {
            liveRewardRecords = baseMapper.selectLiveRewardRecordListByCompanyId(param.getStep(), param.getCompanyId());
        }
        Map<Long, Map<String, BigDecimal>> monthLiveMap = liveRewardRecords.stream()
                .collect(Collectors.groupingBy(
                        LiveRewardRecord::getLiveId,
                        Collectors.groupingBy(
                                record -> dayFormat.format(record.getCreateTime()),
                                Collectors.reducing(BigDecimal.ZERO, LiveRewardRecord::getNum, BigDecimal::add)
                        )
                ));
        Map<Long, LiveRewardRecord> compnayNameMap = liveRewardRecords.stream().collect(Collectors.toMap(LiveRewardRecord::getLiveId, item -> item,(existing, replacement) -> replacement  ));
        // 1. 生成完整的时间序列（天或月）
        List<String> timeSeries = generateMonthTimeSeries(param.getStep(), dayFormat);
        List<LiveRewardRecordVo> dayLiveList = formatNestedMap(monthLiveMap, timeSeries,compnayNameMap);
        return R.ok().put("data", dayLiveList).put("timeSeries",timeSeries);
    }

    @Override
    public List<LiveRewardRecordStatisticsVo> selectRewardSummary(LiveRewardRecordVo param) {
        return baseMapper.selectRewardSummary(param);
    }


    // 将嵌套Map（liveId -> 时间->数值）转换为List<LiveTimeData>（每个liveId对应完整时间序列）
    private List<LiveRewardRecordVo> formatNestedMap(Map<Long, Map<String, BigDecimal>> nestedMap, List<String> timeSeries,Map<Long, LiveRewardRecord> compnayNameMap) {
        return nestedMap.entrySet().stream()
                .map(entry -> {
                    Long liveId = entry.getKey();
                    LiveRewardRecord liveRewardRecord = compnayNameMap.get(liveId);
                    if (liveRewardRecord != null) {
                        Map<String, BigDecimal> timeDataMap = entry.getValue();
                        // 为当前liveId生成完整时间序列的数值列表（缺失补0）
                        List<BigDecimal> dataList = timeSeries.stream()
                                .map(time -> timeDataMap.getOrDefault(time, BigDecimal.ZERO))
                                .collect(Collectors.toList());
                        return new LiveRewardRecordVo(liveRewardRecord.getLiveName(), dataList,liveRewardRecord.getCompanyName());
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
    // 生成从start到end的所有月份（yyyy-MM）
    private List<String> generateMonthTimeSeries(List<Date> step, SimpleDateFormat format) {
        List<String> timeSeries = new ArrayList<>();
        for (Date date : step) {
            timeSeries.add(format.format(date));
        }
        return timeSeries;
    }
}
