package com.fs.course.service.impl;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.fs.common.utils.DateUtils;
import com.fs.course.param.FsCourseTrafficLogParam;
import com.fs.course.vo.FsCourseTrafficLogListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.course.mapper.FsCourseTrafficLogMapper;
import com.fs.course.domain.FsCourseTrafficLog;
import com.fs.course.service.IFsCourseTrafficLogService;

/**
 * 短链课程流量记录Service业务层处理
 *
 * @author fs
 * @date 2024-10-31
 */
@Service
@Slf4j
public class FsCourseTrafficLogServiceImpl implements IFsCourseTrafficLogService
{
    @Autowired
    private FsCourseTrafficLogMapper fsCourseTrafficLogMapper;

    /**
     * 查询短链课程流量记录
     *
     * @param logId 短链课程流量记录主键
     * @return 短链课程流量记录
     */
    @Override
    public FsCourseTrafficLog selectFsCourseTrafficLogByLogId(Long logId)
    {
        return fsCourseTrafficLogMapper.selectFsCourseTrafficLogByLogId(logId);
    }

    /**
     * 查询短链课程流量记录列表
     *
     * @param fsCourseTrafficLog 短链课程流量记录
     * @return 短链课程流量记录
     */
    @Override
    public List<FsCourseTrafficLog> selectFsCourseTrafficLogList(FsCourseTrafficLog fsCourseTrafficLog)
    {
        return fsCourseTrafficLogMapper.selectFsCourseTrafficLogList(fsCourseTrafficLog);
    }

    /**
     * 新增短链课程流量记录
     *
     * @param fsCourseTrafficLog 短链课程流量记录
     * @return 结果
     */
    @Override
    public int insertFsCourseTrafficLog(FsCourseTrafficLog fsCourseTrafficLog)
    {
        fsCourseTrafficLog.setCreateTime(DateUtils.getNowDate());
        return fsCourseTrafficLogMapper.insertFsCourseTrafficLog(fsCourseTrafficLog);
    }

    /**
     * 修改短链课程流量记录
     *
     * @param fsCourseTrafficLog 短链课程流量记录
     * @return 结果
     */
    @Override
    public int updateFsCourseTrafficLog(FsCourseTrafficLog fsCourseTrafficLog)
    {
        return fsCourseTrafficLogMapper.updateFsCourseTrafficLog(fsCourseTrafficLog);
    }

    /**
     * 批量删除短链课程流量记录
     *
     * @param logIds 需要删除的短链课程流量记录主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseTrafficLogByLogIds(Long[] logIds)
    {
        return fsCourseTrafficLogMapper.deleteFsCourseTrafficLogByLogIds(logIds);
    }

    /**
     * 删除短链课程流量记录信息
     *
     * @param logId 短链课程流量记录主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseTrafficLogByLogId(Long logId)
    {
        return fsCourseTrafficLogMapper.deleteFsCourseTrafficLogByLogId(logId);
    }

    @Override
    public List<FsCourseTrafficLogListVO> selectTrafficByCompany(FsCourseTrafficLogParam param) {
        return fsCourseTrafficLogMapper.selectTrafficByCompany(param);
    }


    @Override
    public void saveCourseTrafficLog() {
        Integer count = fsCourseTrafficLogMapper.saveCourseTrafficLogByTwoDaysLaterCount();
        Integer limit = 1000;
        log.info("总数: {}", count);

        // Start timing
        long startTime = System.currentTimeMillis();
        log.info("开始处理，时间: {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        // 计算需要查询的次数
        int totalPages = (count + limit - 1) / limit; // 向上取整
        for (int page = 0; page < totalPages; page++) {
            int offset = page * limit;

            log.info("开始查询");
            List<FsCourseTrafficLog> redPacketLogs = fsCourseTrafficLogMapper.selectCourseTrafficLogByTwoDaysLater(0,limit);
            log.info("查询结果: {}", redPacketLogs);
            // 处理当前批次的1000条数据
            if (redPacketLogs==null ||redPacketLogs.isEmpty()) {
                log.info("没有数据");
                continue;
            }
            fsCourseTrafficLogMapper.insertCourseTrafficLogByTwoDaysLaterBatch(redPacketLogs);
            Long[] delArray = redPacketLogs.stream()
                    .map(FsCourseTrafficLog::getLogId)
                    .toArray(Long[]::new);
            fsCourseTrafficLogMapper.deleteFsCourseTrafficLogByLogIds(delArray);

            // 打印进度
            log.info("已处理: {}/{} ({:.2f}%)",
                    Math.min(offset + limit, count),
                    count,
                    (double)(offset + limit) / count * 100);

            // Calculate estimated remaining time
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - startTime;
            double timePerBatch = (double)elapsedTime / (page + 1);
            long estimatedRemaining = (long)(timePerBatch * (totalPages - page - 1));

            log.info("当前批次耗时: {:.2f}s, 预计剩余时间: {}",
                    timePerBatch / 1000,
                    formatDuration(estimatedRemaining));
        }

        // End timing
        long endTime = System.currentTimeMillis();
        log.info("处理完成，时间: {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        log.info("总耗时: {}", formatDuration(endTime - startTime));
    }

    private static String formatDuration(long millis) {
        long seconds = millis / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;

        return String.format("%02d:%02d:%02d",
                hours,
                minutes % 60,
                seconds % 60);
    }
}
