package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dao.ExposureRecordDao;
import com.yonge.cooleshow.biz.dal.entity.ExposureRecord;
import com.yonge.cooleshow.biz.dal.service.CourseGroupService;
import com.yonge.cooleshow.biz.dal.service.ExposureRecordService;
import com.yonge.cooleshow.biz.dal.service.MusicSheetService;
import com.yonge.cooleshow.biz.dal.service.VideoLessonGroupService;
import com.yonge.cooleshow.biz.dal.wrapper.ExposureRecordWrapper;
import com.yonge.toolset.utils.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ExposureRecordServiceImpl extends ServiceImpl<ExposureRecordDao, ExposureRecord> implements ExposureRecordService {
    private final static Logger log = LoggerFactory.getLogger(ExposureRecordServiceImpl.class);

    @Resource
    private CourseGroupService courseGroupService;
    @Resource
    private MusicSheetService musicSheetService;
    @Resource
    private VideoLessonGroupService videoLessonGroupService;

    public ExposureRecordDao getDao() {
        return baseMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void record(List<ExposureRecordWrapper.SaveExposureRecordDto> exposureRecordDto) {
        Date now = new Date();
        String exposureTime = DateUtil.format(now, DateUtil.DEFAULT_PATTERN);
        exposureRecordDto.forEach(e->e.setExposureTime(exposureTime));
        baseMapper.saveExposureRecord(exposureRecordDto);
        //按类型分组
        Map<String, List<ExposureRecordWrapper.SaveExposureRecordDto>> typeMap = exposureRecordDto.stream().collect(Collectors.groupingBy(ExposureRecordWrapper.SaveExposureRecordDto::getObjectType));
        typeMap.forEach((k,v)->{
            List<ExposureRecordWrapper.SaveExposureRecordDto> saveExposureReportDtos = typeMap.get(k);
            //按对象id分组，并获取集合数量
            Map<Long, Integer> exposureNumMap = saveExposureReportDtos.stream().collect(Collectors.groupingBy(ExposureRecordWrapper.SaveExposureRecordDto::getObjectId, Collectors.summingInt(e -> 1)));
            exposureNumMap.forEach((objectId,exposureNum)-> {
                if ("LIVE".equals(k)) {
                    courseGroupService.getDao().updateExposureNum(objectId, exposureNum);
                } else if ("VIDEO".equals(k)) {
                    videoLessonGroupService.getDao().updateExposureNum(objectId, exposureNum);
                }else if ("MUSIC".equals(k)) {
                    musicSheetService.getDao().updateExposureNum(objectId, exposureNum);
                }
            });
        });
    }
}