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

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import com.yonge.cooleshow.biz.dal.service.ActivityEvaluationRecordService;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.biz.dal.dao.MusicSheetDao;
import com.yonge.cooleshow.biz.dal.dao.StudentDao;
import com.yonge.cooleshow.biz.dal.dao.SysMusicCompareRecordDao;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.dto.IndexBaseDto;
import com.yonge.cooleshow.biz.dal.dto.IndexBaseMonthData;
import com.yonge.cooleshow.biz.dal.dto.StudentTrainChartDto;
import com.yonge.cooleshow.biz.dal.dto.StudentTrainOverviewDto;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.entity.SysMusicCompareRecord;
import com.yonge.cooleshow.biz.dal.enums.FeatureType;
import com.yonge.cooleshow.biz.dal.enums.IndexDataType;
import com.yonge.cooleshow.biz.dal.queryInfo.SysMusicCompareRecordQueryInfo;
import com.yonge.cooleshow.biz.dal.service.SysMessageService;
import com.yonge.cooleshow.biz.dal.service.SysMusicCompareRecordService;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.dal.BaseDAO;
import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import com.yonge.toolset.utils.collection.MapUtil;
import com.yonge.toolset.utils.date.DateUtil;

@Service
public class SysMusicCompareRecordServiceImpl extends BaseServiceImpl<Long, SysMusicCompareRecord>  implements SysMusicCompareRecordService {

	private final static Logger log = LoggerFactory.getLogger(SysMusicCompareRecordServiceImpl.class);
	@Autowired
	private SysMusicCompareRecordDao sysMusicCompareRecordDao;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private StudentDao studentDao;
	@Autowired
	private SysMessageService sysMessageService;
	
    @Autowired
    private SysUserFeignService sysUserFeignService;

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private ActivityEvaluationRecordService activityEvaluationRecordService;

	@Autowired
	private MusicSheetDao musicSheetDao;

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

	@Override
	public long insert(SysMusicCompareRecord bean) {
		// 保存评测记录
		long insert = super.insert(bean);

		return insert;
	}

	@Override
	@Transactional
	public void saveMusicCompareData(SysMusicCompareRecord sysMusicCompareRecord) {
		
		sysMusicCompareRecordDao.update(sysMusicCompareRecord);

	}

	@Override
	public Object getLastEvaluationMusicalNotesPlayStats(Long 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("customConfiguration", userLastEvaluationData.getCustomConfiguration());
		if(userLastEvaluationData.getCreateTime() == null) {
			jsonObject.put("expire", 1);
		} else {
			LocalDateTime localDateTime = userLastEvaluationData.getCreateTime()
																.toInstant()
																.atZone(ZoneId.systemDefault())
																.toLocalDateTime();
			if (localDateTime.plusDays(Long.parseLong(getExpireTime())).compareTo(LocalDateTime.now()) <0) {
				jsonObject.put("expire", 1);
			} else {
				jsonObject.put("expire", 0);
			}
		}

		MusicSheet sysMusicScore = musicSheetDao.selectById(userLastEvaluationData.getMusicSheetId());
		if(Objects.nonNull(sysMusicScore)){
			jsonObject.put("sysMusicScoreName", sysMusicScore.getMusicSheetName());
		}
		return jsonObject;
	}

	@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);

		params.put("expireTime",getExpireTime());
		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);
		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<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;
	}


	private String getExpireTime() {

		String homeworkExpireTime = sysConfigService.findConfigValue(SysConfigConstant.HOMEWORK_EXPIRE_TIME);
		if (org.springframework.util.StringUtils.isEmpty(homeworkExpireTime)) {
			return "9999";
		}
		return homeworkExpireTime;
	}
}
