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

import com.ym.mec.biz.dal.dao.SysMusicCompareRecordDao;
import com.ym.mec.biz.dal.entity.SysMusicCompareRecord;
import com.ym.mec.biz.dal.enums.HeardLevelEnum;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.util.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.biz.dal.entity.SysMusicCompareWeekData;
import com.ym.mec.biz.service.SysMusicCompareWeekDataService;
import com.ym.mec.biz.dal.dao.SysMusicCompareWeekDataDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.time.LocalDate;
import java.util.Objects;

@Service
public class SysMusicCompareWeekDataServiceImpl extends BaseServiceImpl<Integer, SysMusicCompareWeekData> implements SysMusicCompareWeekDataService{

	@Autowired
	private SysMusicCompareWeekDataDao sysMusicCompareWeekDataDao;
	@Autowired
	private SysMusicCompareRecordDao sysMusicCompareRecordDao;

	@Override
	public BaseDAO<Integer, SysMusicCompareWeekData> getDAO() {
		return sysMusicCompareWeekDataDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
	public void updateUserWeekTrainData(Integer userId, LocalDate monday) {
		SysMusicCompareWeekData userWeekData = sysMusicCompareWeekDataDao.getWithUserAndMonday(userId, monday.toString());

		SysMusicCompareWeekData userWeekCompareData = sysMusicCompareRecordDao.getUserWeekCompareData(userId, monday.toString());
		userWeekCompareData.setUserId(userId);
		userWeekCompareData.setMonday(Date.from(monday.atStartOfDay(DateUtil.zoneId).toInstant()));
		userWeekCompareData.setBeginnerMaxScoreId(sysMusicCompareRecordDao.getUserWeekMaxMusicScoreId(userId, monday.toString(), HeardLevelEnum.BEGINNER));
		userWeekCompareData.setAdvancedMaxScoreId(sysMusicCompareRecordDao.getUserWeekMaxMusicScoreId(userId, monday.toString(), HeardLevelEnum.ADVANCED));
		userWeekCompareData.setPerformerMaxScoreId(sysMusicCompareRecordDao.getUserWeekMaxMusicScoreId(userId, monday.toString(), HeardLevelEnum.PERFORMER));

		if(Objects.isNull(userWeekData)){
			sysMusicCompareWeekDataDao.insert(userWeekCompareData);
		}else{
			sysMusicCompareWeekDataDao.update(userWeekCompareData);
		}
	}
}
