package com.fs.hisStore.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.fs.common.utils.DateUtils;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.google.common.collect.Lists;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.hisStore.mapper.FsUserCourseCountScrmMapper;
import com.fs.hisStore.domain.FsUserCourseCountScrm;
import com.fs.hisStore.service.IFsUserCourseCountScrmService;

/**
 * 用户看课统计Service业务层处理
 *
 * @author fs
 * @date 2025-04-02
 */
@Service
public class FsUserCourseCountScrmServiceImpl implements IFsUserCourseCountScrmService
{
    @Autowired
    private FsUserCourseCountScrmMapper fsUserCourseCountMapper;

    @Autowired
    private FsCourseWatchLogMapper fsCourseWatchLogMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询用户看课统计
     *
     * @param id 用户看课统计ID
     * @return 用户看课统计
     */
    @Override
    public FsUserCourseCountScrm selectFsUserCourseCountById(Long id)
    {
        return fsUserCourseCountMapper.selectFsUserCourseCountById(id);
    }

    /**
     * 查询用户看课统计列表
     *
     * @param fsUserCourseCount 用户看课统计
     * @return 用户看课统计
     */
    @Override
    public List<FsUserCourseCountScrm> selectFsUserCourseCountList(FsUserCourseCountScrm fsUserCourseCount)
    {
        return fsUserCourseCountMapper.selectFsUserCourseCountList(fsUserCourseCount);
    }

    /**
     * 新增用户看课统计
     *
     * @param fsUserCourseCount 用户看课统计
     * @return 结果
     */
    @Override
    public int insertFsUserCourseCount(FsUserCourseCountScrm fsUserCourseCount)
    {
        fsUserCourseCount.setCreateTime(DateUtils.getNowDate());
        return fsUserCourseCountMapper.insertFsUserCourseCount(fsUserCourseCount);
    }

    /**
     * 修改用户看课统计
     *
     * @param fsUserCourseCount 用户看课统计
     * @return 结果
     */
    @Override
    public int updateFsUserCourseCount(FsUserCourseCountScrm fsUserCourseCount)
    {
        fsUserCourseCount.setUpdateTime(DateUtils.getNowDate());
        return fsUserCourseCountMapper.updateFsUserCourseCount(fsUserCourseCount);
    }

    /**
     * 批量删除用户看课统计
     *
     * @param ids 需要删除的用户看课统计ID
     * @return 结果
     */
    @Override
    public int deleteFsUserCourseCountByIds(Long[] ids)
    {
        return fsUserCourseCountMapper.deleteFsUserCourseCountByIds(ids);
    }

    /**
     * 删除用户看课统计信息
     *
     * @param id 用户看课统计ID
     * @return 结果
     */
    @Override
    public int deleteFsUserCourseCountById(Long id)
    {
        return fsUserCourseCountMapper.deleteFsUserCourseCountById(id);
    }

    @Override
    public FsUserCourseCountScrm findByUserId(Long userId) {
        return fsUserCourseCountMapper.findByUserId(userId);
    }

    @Override
    public void insertFsUserCourseCountTask() {
        // 1、获取统计结果
        List<FsUserCourseCountScrm> countResult = fsUserCourseCountMapper.getCountResult();

        // 查询用户-每天的最新的看课状态，和最后的心跳时间
        List<FsUserCourseCountScrm> userStatusAndLastWatchDate = fsUserCourseCountMapper.getUserStatusAndLastWatchDate();
        Map<String, FsUserCourseCountScrm> map = userStatusAndLastWatchDate.stream()
                .collect(Collectors.toMap(k -> String.format("%s-%s-%s", k.getUserId(),k.getProjectId(), k.getLastDate()), v -> v));

        for (FsUserCourseCountScrm data : countResult) {
            String key = String.format("%s-%s-%s", data.getUserId(),data.getProjectId(), data.getLastDate());
            FsUserCourseCountScrm fsUserCourseCount = map.get(key);
            if(fsUserCourseCount != null){
                data.setLastWatchDate(fsUserCourseCount.getLastWatchDate());
                data.setStatus(fsUserCourseCount.getStatus());
//                data.setStopWatchDays(fsUserCourseCount.getStopWatchDays());
            }
        }

        // 2、分批插入数据
        this.batchInsert(countResult);

    }

    private void batchInsert(List<FsUserCourseCountScrm> list) {
        // 分批次处理，一次提交500条
        List<List<FsUserCourseCountScrm>> batches = Lists.partition(list, 500);
        batches.forEach(batch -> {
            SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
            try {
                FsUserCourseCountScrmMapper mapper = sqlSession.getMapper(FsUserCourseCountScrmMapper.class);
                batch.forEach(mapper::insertFsUserCourseCountTask);
                sqlSession.commit();
            } finally {
                sqlSession.close();
            }
        });
    }
}
