package com.ym.mec.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.IndexBaseMonthData;
import com.ym.mec.biz.dal.entity.SysMusicCompareRecord;
import com.ym.mec.biz.dal.entity.SysMusicScore;
import com.ym.mec.biz.dal.enums.FeatureType;
import com.ym.mec.biz.dal.enums.HeardLevelEnum;
import com.ym.mec.biz.dal.enums.IndexDataType;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.page.SysMusicCompareRecordQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SysMusicCompareRecordServiceImpl extends BaseServiceImpl<Long, SysMusicCompareRecord>  implements SysMusicCompareRecordService {
	
	@Autowired
	private SysMusicCompareRecordDao sysMusicCompareRecordDao;
	@Autowired
	private SysMusicCompareWeekDataService sysMusicCompareWeekDataService;
	@Autowired
	private SysMusicCompareWeekDataDao sysMusicCompareWeekDataDao;
	@Autowired
	private SysMusicScoreDao sysMusicScoreDao;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private StudentDao studentDao;
	@Autowired
	private StudentVisitDao studentVisitDao;
	@Autowired
	private SysMessageService sysMessageService;
	
    @Autowired
    private SysUserFeignService sysUserFeignService;

	@Autowired
	private SysConfigDao sysConfigDao;
	@Autowired
	private SysTenantConfigService sysTenantConfigService;

	@Autowired
	private MusicGroupDao musicGroupDao;

	@Override
	public BaseDAO<Long, SysMusicCompareRecord> getDAO() {
		return sysMusicCompareRecordDao;
	}

	@Override
	public long insert(SysMusicCompareRecord bean) {
		long insert = super.insert(bean);
		if(Objects.nonNull(bean.getUserId())){
			studentDao.addStudentCloudStudySequenceDays(bean.getUserId());
			sysMusicCompareWeekDataService.updateUserWeekTrainData(bean.getUserId(), LocalDate.now().with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.MONDAY.getValue()));
		}
		return insert;
	}

	@Override
	public void saveMusicCompareData(String phone, SoundCompareHelper soundCompareInfo) {
		SysUser user = teacherDao.getUserWithPhone(phone);
		if(Objects.isNull(user)){
			return;
		}
		SysMusicCompareRecord sysMusicCompareRecord = new SysMusicCompareRecord();
		sysMusicCompareRecord.setUserId(user.getId());
		sysMusicCompareRecord.setSysMusicScoreId(soundCompareInfo.getMusicScoreId());
		sysMusicCompareRecord.setHeardLevel(soundCompareInfo.getHeardLevel());
		sysMusicCompareRecord.setBehaviorId(soundCompareInfo.getBehaviorId());
		sysMusicCompareRecord.setSpeed(soundCompareInfo.getSpeed());
		Map<String, Object> scoreData = new HashMap<>();
		scoreData.put("userMeasureScore", soundCompareInfo.getUserMeasureScoreMap());
		Map<String, Object> musicalNotesPlayStats = new HashMap<>();
		musicalNotesPlayStats.put("detailId", soundCompareInfo.getDetailId());
		musicalNotesPlayStats.put("examSongId", soundCompareInfo.getExamSongId());
		musicalNotesPlayStats.put("xmlUrl", soundCompareInfo.getXmlUrl());
		musicalNotesPlayStats.put("notesData", soundCompareInfo.getMusicalNotesPlayStats());
		scoreData.put("musicalNotesPlayStats", musicalNotesPlayStats);
		sysMusicCompareRecord.setScoreData(JSON.toJSONString(scoreData));
		if (Objects.nonNull(soundCompareInfo.getUserMeasureScoreMap()) && soundCompareInfo.getUserMeasureScoreMap().containsKey(-1)){
			Map<String, Object> finalScore = soundCompareInfo.getUserMeasureScoreMap().get(-1);
			sysMusicCompareRecord.setScore((BigDecimal) finalScore.get("score"));
			sysMusicCompareRecord.setIntonation((BigDecimal) finalScore.get("intonation"));
			sysMusicCompareRecord.setCadence((BigDecimal) finalScore.get("cadence"));
			sysMusicCompareRecord.setIntegrity((BigDecimal) finalScore.get("integrity"));
		}
		sysMusicCompareRecord.setRecordFilePath(soundCompareInfo.getRecordFilePath());
		sysMusicCompareRecord.setDeviceType(soundCompareInfo.getDeviceType());
		sysMusicCompareRecord.setClientId(soundCompareInfo.getClientId());
		if(!CollectionUtils.isEmpty(soundCompareInfo.getMusicXmlInfos())){
			MusicPitchDetailDto lastMeasure = soundCompareInfo.getMusicXmlInfos().stream().max(Comparator.comparing(MusicPitchDetailDto::getTimeStamp)).get();
			sysMusicCompareRecord.setSourceTime((lastMeasure.getTimeStamp()+lastMeasure.getDuration())/1000);
		}
		if(Objects.nonNull(soundCompareInfo.getFile())){
			sysMusicCompareRecord.setPlayTime(soundCompareInfo.getFile().length()/(SoundCompareHandler.soundCompareConfig.audioFormat.getFrameSize()*SoundCompareHandler.soundCompareConfig.audioFormat.getFrameRate()));
		}
		sysMusicCompareRecord.setFeature(FeatureType.CLOUD_STUDY_EVALUATION);
		sysMusicCompareRecord.setId(soundCompareInfo.getRecordId());
		if(Objects.nonNull(sysMusicCompareRecord.getId())){
			sysMusicCompareRecordDao.update(sysMusicCompareRecord);
		}else{
			sysMusicCompareRecordDao.insert(sysMusicCompareRecord);
		}
		studentDao.addStudentCloudStudySequenceDays(user.getId());
		sysMusicCompareWeekDataService.updateUserWeekTrainData(user.getId(), LocalDate.now().with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.MONDAY.getValue()));
	}

	@Override
	@Transactional
	public void saveMusicCompareData(SysMusicCompareRecord sysMusicCompareRecord) {
		
		Integer userId = sysMusicCompareRecord.getUserId();
		
		sysMusicCompareRecordDao.update(sysMusicCompareRecord);
		studentDao.addStudentCloudStudySequenceDays(userId);
		sysMusicCompareWeekDataService
				.updateUserWeekTrainData(userId, LocalDate.now().with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.MONDAY.getValue()));
	}

	@Override
	public Object getLastEvaluationMusicalNotesPlayStats(Integer userId, Long recordId) {
		SysMusicCompareRecord userLastEvaluationData;
		if(Objects.nonNull(recordId)){
			userLastEvaluationData = sysMusicCompareRecordDao.get(recordId);
		}else{
			userLastEvaluationData = sysMusicCompareRecordDao.getUserLastEvaluationData(userId);
		}
		if(Objects.isNull(userLastEvaluationData)){
			return null;
		}
		if(StringUtils.isBlank(userLastEvaluationData.getScoreData())){
			return null;
		}

		JSONObject jsonObject = JSON.parseObject(userLastEvaluationData.getScoreData());
		jsonObject.put("recordId", userLastEvaluationData.getId());
		jsonObject.put("score", userLastEvaluationData.getScore());
		jsonObject.put("cadence", userLastEvaluationData.getCadence());
		jsonObject.put("intonation", userLastEvaluationData.getIntonation());
		jsonObject.put("integrity", userLastEvaluationData.getIntegrity());
		jsonObject.put("heardLevel", userLastEvaluationData.getHeardLevel());
		jsonObject.put("videoFilePath", userLastEvaluationData.getVideoFilePath());
		jsonObject.put("partIndex", userLastEvaluationData.getPartIndex());
		jsonObject.put("expire",DateUtil.isOverdue(userLastEvaluationData.getCreateTime(),
				sysConfigDao.findConfigValue("file_expiration_time")));

		SysMusicScore sysMusicScore = sysMusicScoreDao.get(userLastEvaluationData.getSysMusicScoreId());
		if(Objects.nonNull(sysMusicScore)){
			jsonObject.put("sysMusicScoreName", sysMusicScore.getName());
		}
		return jsonObject;
	}

	@Override
	public StatDto rankingList(SysMusicCompareRecordQueryInfo queryInfo) {
		StatDto result = new StatDto();
		MusicCompareRankingDto head = new MusicCompareRankingDto();
		head.setUserId(queryInfo.getUserId());
		List<MusicCompareRankingDto> userTrainStat = sysMusicCompareWeekDataDao.getUserTrainStat(queryInfo.getStartTime(),
				queryInfo.getOrderType(),
				Objects.isNull(queryInfo.getHeardLevel())?null:queryInfo.getHeardLevel().getCode(),
				queryInfo.getOrganId(),
				queryInfo.getTenantId());
		List<MusicCompareRankingDto> detail = new ArrayList<>();

		List<Integer> studentIds = userTrainStat.stream().limit(10).map(MusicCompareRankingDto::getUserId).collect(Collectors.toList());
		Map<Integer, String> studentSubjectMap = new HashMap<>();
		if(!CollectionUtils.isEmpty(studentIds)){
			List<Map<Integer, String>> studentSubjectMapList = studentDao.getStudentSubjectMapList(studentIds);
			studentSubjectMap = MapUtil.convertIntegerMap(studentSubjectMapList);
		}

		int rankNum = 0;
		for (int i = 0; i < userTrainStat.size(); i++) {
			if(userTrainStat.get(i).getUserId().equals(queryInfo.getUserId())){
				head = userTrainStat.get(i);
			}
			userTrainStat.get(i).setTrainTime(userTrainStat.get(i).getTrainTime()/60);
			if(userTrainStat.get(i).getVipUser() <= 0){
				continue;
			}
			userTrainStat.get(i).setRankNum(++rankNum);
			if(studentSubjectMap.containsKey(userTrainStat.get(i).getUserId())){
				userTrainStat.get(i).setSubjectName(studentSubjectMap.get(userTrainStat.get(i).getUserId()));
			}
			if(detail.size()<10){
				detail.add(userTrainStat.get(i));
			}
		}
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("tenantId", queryInfo.getTenantId());
		List<Integer> organIds = new ArrayList<Integer>();
		organIds.add(queryInfo.getOrganId());
		params.put("organIds", organIds);
		
		head.setStudentNum(studentDao.countStudentsWithOrgan(params));
		if(StringUtils.isBlank(head.getAvatar())){
			SysUser user = sysUserFeignService.queryUserById(queryInfo.getUserId());
			if(user != null){
				head.setAvatar(user.getAvatar());
			}
		}
		result.setHead(head);
		detail.sort(Comparator.comparing(MusicCompareRankingDto::getRankNum).thenComparing(MusicCompareRankingDto::getUserId));
		result.setDetail(detail);
		return result;
	}

	@Override
	public void curWeekStudentTrainRemind() {
		Set<Integer> validVipStudentIds = studentDao.getValidVipStudentIds();
		LocalDate monday = LocalDate.now().with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.MONDAY.getValue());
		LocalDate sunday = LocalDate.now().with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.SUNDAY.getValue());
		List<MusicCompareRankingDto> userTrainStat = sysMusicCompareRecordDao.getUserTrainStat(monday.toString(), sunday.toString(), null);

		Set<Integer> trainStudentIds = new HashSet<>();
		Set<Integer> ranStudentIds = new HashSet<>();

		if(!CollectionUtils.isEmpty(userTrainStat)){
			trainStudentIds = userTrainStat.stream().map(MusicCompareRankingDto::getUserId).collect(Collectors.toSet());
			//时长榜
			Set<Integer> collect1 = userTrainStat.stream().sorted(Comparator.comparing(MusicCompareRankingDto::getTrainTime, Comparator.reverseOrder())).limit(10).map(MusicCompareRankingDto::getUserId).collect(Collectors.toSet());
			ranStudentIds.addAll(collect1);
			Set<Integer> collect2 = userTrainStat.stream().sorted(Comparator.comparing(MusicCompareRankingDto::getTrainDays, Comparator.reverseOrder())).limit(10).map(MusicCompareRankingDto::getUserId).collect(Collectors.toSet());
			ranStudentIds.addAll(collect2);
		}
		List<MusicCompareRankingDto> userTrainStat3 = sysMusicCompareRecordDao.getUserTrainStat(monday.toString(), sunday.toString(), HeardLevelEnum.BEGINNER);
		if(!CollectionUtils.isEmpty(userTrainStat3)){
			Set<Integer> collect3 = userTrainStat3.stream().sorted(Comparator.comparing(MusicCompareRankingDto::getScore, Comparator.reverseOrder())).limit(10).map(MusicCompareRankingDto::getUserId).collect(Collectors.toSet());
			ranStudentIds.addAll(collect3);
		}
		List<MusicCompareRankingDto> userTrainStat4 = sysMusicCompareRecordDao.getUserTrainStat(monday.toString(), sunday.toString(), HeardLevelEnum.ADVANCED);
		if(!CollectionUtils.isEmpty(userTrainStat4)){
			Set<Integer> collect4 = userTrainStat4.stream().sorted(Comparator.comparing(MusicCompareRankingDto::getScore, Comparator.reverseOrder())).limit(10).map(MusicCompareRankingDto::getUserId).collect(Collectors.toSet());
			ranStudentIds.addAll(collect4);
		}
		List<MusicCompareRankingDto> userTrainStat5 = sysMusicCompareRecordDao.getUserTrainStat(monday.toString(), sunday.toString(), HeardLevelEnum.PERFORMER);
		if(!CollectionUtils.isEmpty(userTrainStat5)){
			Set<Integer> collect5 = userTrainStat5.stream().sorted(Comparator.comparing(MusicCompareRankingDto::getScore, Comparator.reverseOrder())).limit(10).map(MusicCompareRankingDto::getUserId).collect(Collectors.toSet());
			ranStudentIds.addAll(collect5);
		}

		Map<Integer, String> userMap1 = new HashMap<>();
		Map<Integer, String> userMap2 = new HashMap<>();
		Map<Integer, String> userMap3 = new HashMap<>();
		for (Integer studentId : validVipStudentIds) {
			if (trainStudentIds.contains(studentId) && !ranStudentIds.contains(studentId)){
				userMap1.put(studentId, studentId.toString());
			}
			if(ranStudentIds.contains(studentId)){
				userMap2.put(studentId, studentId.toString());
			}
			if(!trainStudentIds.contains(studentId)){
				userMap3.put(studentId, studentId.toString());
			}
		}
		String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");
		sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TRAIN_NO_RANK_STUDENT_PUSH,userMap1,
				null, 0, "5?"+baseApiUrl+"/#/cloudRanking", "STUDENT");
		sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TRAIN_RANK_STUDENT_PUSH,userMap2,
				null, 0, "5?"+baseApiUrl+"/#/cloudRanking", "STUDENT");
		sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.NO_TRAIN_STUDENT_PUSH,userMap3,
				null, 0, "5?"+baseApiUrl+"/#/cloudRanking", "STUDENT");
	}

	@Override
	public Map<String, Object> studentTrainData(SysMusicCompareRecordQueryInfo queryInfo) {
		StudentTrainOverviewDto userTrainOverView = new StudentTrainOverviewDto();

		List<StudentTrainChartDto> userTrainChartData = new ArrayList<>();
		if(queryInfo.getPage()==1){
			userTrainOverView = sysMusicCompareRecordDao.getUserTrainOverView(queryInfo.getUserId());
			userTrainChartData = sysMusicCompareRecordDao.getUserTrainChartData(queryInfo.getUserId(), queryInfo.getStartTime(), queryInfo.getEndTime());
		}

		if(CollectionUtils.isEmpty(userTrainChartData)||userTrainChartData.size()!=7){
			Set<LocalDate> trainDates = userTrainChartData.stream().map(StudentTrainChartDto::getTrainDate).collect(Collectors.toSet());
			LocalDate startLocalDate = LocalDate.parse(queryInfo.getStartTime(), DateUtil.dateFormatter);
			for (int i = 1; i <= 7; i++) {
				if(!trainDates.contains(startLocalDate)){
					userTrainChartData.add(new StudentTrainChartDto(0, 0, startLocalDate));
				}
				startLocalDate=startLocalDate.plusDays(1);
			}
		}

		PageInfo<SysMusicCompareRecord> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<>();
		queryInfo.setFeatureType(FeatureType.CLOUD_STUDY_EVALUATION);
		MapUtil.populateMap(params, queryInfo);

		List<SysMusicCompareRecord> dataList = null;
		int count = this.findCount(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = this.getDAO().queryPage(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		Function<Date,Boolean> expirationFun = (submitTime)->DateUtil.isOverdue(submitTime,sysConfigDao.findConfigValue("file_expiration_time"));
		dataList.forEach(e->e.setExpire(expirationFun.apply(e.getCreateTime())));

		pageInfo.setRows(dataList);
		Map<String, Object> result = new HashMap<>();
		userTrainOverView.setTrainTime(userTrainOverView.getTrainTime()/60);
		result.put("userTrainOverView",userTrainOverView);

		List<IndexBaseDto> userTrainChartResult = new ArrayList<>();
		List<IndexBaseMonthData> trainNumData = new ArrayList<>();
		List<IndexBaseMonthData> trainTimeData = new ArrayList<>();

		for (StudentTrainChartDto data : userTrainChartData) {
			Date trainDate = Date.from(data.getTrainDate().atStartOfDay(DateUtil.zoneId).toInstant());
			trainTimeData.add(new IndexBaseMonthData(trainDate, null, new BigDecimal(data.getTrainTime()/60)));
			trainNumData.add(new IndexBaseMonthData(trainDate, null, new BigDecimal(data.getTrainNum())));
		}

		trainNumData.sort(Comparator.comparing(IndexBaseMonthData::getMonth));
		trainTimeData.sort(Comparator.comparing(IndexBaseMonthData::getMonth));

		userTrainChartResult.add(new IndexBaseDto(IndexDataType.CLOUD_STUDY_TRAIN_TIME, trainTimeData));
		userTrainChartResult.add(new IndexBaseDto(IndexDataType.CLOUD_STUDY_TRAIN_NUM, trainNumData));

		result.put("userTrainChartData", userTrainChartResult);
		result.put("detail",pageInfo);
		return result;
	}

	@Override
	public PageInfo<MusicCompareRankingDto> queryMusicGroupStudentTrainData(SysMusicCompareRecordQueryInfo queryInfo) {
		PageInfo<MusicCompareRankingDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List<MusicCompareRankingDto> dataList = new ArrayList<>();
		int count = sysMusicCompareRecordDao.countMusicGroupStudentTrainData(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList =sysMusicCompareRecordDao.queryMusicGroupStudentTrainData(params);
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public PageInfo<SysMusicCompareRecord> queryStudentTrainData(SysMusicCompareRecordQueryInfo queryInfo) {
		PageInfo<SysMusicCompareRecord> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);

		List<SysMusicCompareRecord> dataList = null;
		int count = this.findCount(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = this.getDAO().queryPage(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

    @Override
    public PageInfo<CountStudentTrainDataDto> countStudentTrain(SysMusicCompareRecordQueryInfo queryInfo) {
		if(queryInfo.getStartTime() == null || queryInfo.getEndTime() == null){
			throw new BizException("请选择训练时间");
		}
		PageInfo<CountStudentTrainDataDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		String sort = queryInfo.getSort();
		if(StringUtils.isNotEmpty(sort)){
			queryInfo.setSort(sort.equals("trainNum")?"train_num_":sort.equals("totalPlayTime")?"total_play_time_":sort.equals("recordNum")?"record_num_":"train_day_");
		}
		Integer tenantId = TenantContextHolder.getTenantId();
		MapUtil.populateMap(params, queryInfo);
		Integer visitFlag = 0;
		if(queryInfo.getVisitFlag() != null && queryInfo.getVisitFlag()){
			//获取乐团在读，有vip网管课的学员列表
			List<Integer> hasCourseUserIds = studentDao.getStudentByHasCourse(queryInfo.getTeacherId());
			if(hasCourseUserIds == null || hasCourseUserIds.size() == 0){
				return pageInfo;
			}
			params.put("hasCourseUserIds",hasCourseUserIds);
			//获取所选时间段下一周的日期
			Date addDays1 = DateUtil.addDays(DateUtil.toDate(queryInfo.getEndTime()), 1);
			Date addDays3 = DateUtil.addDays(DateUtil.toDate(queryInfo.getEndTime()), 3);
			//有回访过的学员列表
			List<Integer> studentIds = studentVisitDao.queryRecordVisitStudentIds(queryInfo.getTeacherId(),addDays1,addDays3);
			if(studentIds != null && studentIds.size() > 0){
				params.put("visitStudents",studentIds);
			}
			Date date = DateUtil.toDate(DateUtil.format(new Date(),DateUtil.ISO_EXPANDED_DATE_FORMAT));
			int daysBetween = DateUtil.daysBetween(addDays1, date);
			//每周只有前三天可以回访
			if(daysBetween >= 0 && daysBetween <= 2){
				visitFlag = 1;
			}
			params.put("having",1);
		}
		String totalTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.STUDENT_CLOUD_TEACHER_TOTAL_PLAY_TIME,tenantId);
		if(StringUtils.isEmpty(totalTime)){
			totalTime = "80";
		}
		params.put("totalTime",Integer.parseInt(totalTime));
		String trainNum = sysTenantConfigService.getTenantConfigValue(SysConfigService.STUDENT_CLOUD_TEACHER_TRAIN_NUM,tenantId);
		if(StringUtils.isEmpty(trainNum)){
			trainNum = "4";
		}
		params.put("trainNum",Integer.parseInt(trainNum));
		int count = sysMusicCompareRecordDao.queryStudentTrain(params).size();
		List<CountStudentTrainDataDto> dataList = new ArrayList<>();
		if(count > 0){
			params.put("offset", pageInfo.getOffset());
			dataList = sysMusicCompareRecordDao.queryStudentTrain(params);
			List<Integer> studentIds = dataList.stream().map(e -> e.getUserId()).collect(Collectors.toList());
			//获取学员在读，进行中的乐团名称
			Map<Integer,String> groupNameMap = MapUtil.convertMybatisMap(musicGroupDao.queryNormalGroupName(studentIds));
			pageInfo.setTotal(count);
			for (CountStudentTrainDataDto e : dataList) {
				e.setMusicGroupName(groupNameMap.get(e.getUserId()));
				if(visitFlag == 1){
					e.setVisitFlag(visitFlag);
				}
			}
		}
		pageInfo.setRows(dataList);
		return pageInfo;
    }

	@Override
	public int queryCurrentDatePlayTimeByUserId(Integer userId) {
		return sysMusicCompareRecordDao.queryCurrentDatePlayTimeByUserId(userId);
	}
}
