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

import com.yonge.cooleshow.biz.dal.dao.SysMusicCompareRecordDao;
import com.yonge.cooleshow.biz.dal.dao.SysMusicCompareWeekDataDao;
import com.yonge.cooleshow.biz.dal.entity.SysMusicCompareWeekData;
import com.yonge.cooleshow.biz.dal.enums.HeardLevelEnum;
import com.yonge.cooleshow.biz.dal.service.SysMusicCompareWeekDataService;
import com.yonge.toolset.mybatis.dal.BaseDAO;
import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import com.yonge.toolset.utils.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
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
	public SysMusicCompareWeekDataDao getDao() {
		return sysMusicCompareWeekDataDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateUserWeekTrainData(Long 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);
		}
	}
}
