package com.keao.edu.user.service.impl;

import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.exception.BizException;
import com.keao.edu.common.page.PageInfo;
import com.keao.edu.common.page.QueryInfo;
import com.keao.edu.common.service.impl.BaseServiceImpl;
import com.keao.edu.common.tenant.TenantContextHolder;
import com.keao.edu.user.dao.ExamSongDao;
import com.keao.edu.user.dao.ExamSubjectDao;
import com.keao.edu.user.dao.ExamSubjectSongDao;
import com.keao.edu.user.dao.ExaminationBasicDao;
import com.keao.edu.user.dto.ExamSubjectSongDto;
import com.keao.edu.user.entity.ExamSong;
import com.keao.edu.user.entity.ExamSubject;
import com.keao.edu.user.entity.ExamSubjectSong;
import com.keao.edu.user.entity.ExaminationBasic;
import com.keao.edu.user.enums.ExamStatusEnum;
import com.keao.edu.user.page.ExamSubjectSongQueryInfo;
import com.keao.edu.user.service.ExamSubjectSongService;
import com.keao.edu.util.collection.MapUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
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 org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExamSubjectSongServiceImpl extends BaseServiceImpl<Long, ExamSubjectSong> implements ExamSubjectSongService {

	@Autowired
	private ExaminationBasicDao examinationBasicDao;
	@Autowired
	private ExamSubjectSongDao examSubjectSongDao;
	@Autowired
	private ExamSubjectDao examSubjectDao;
	@Autowired
	private ExamSongDao examSongDao;

	@Override
	public BaseDAO<Long, ExamSubjectSong> getDAO() {
		return examSubjectSongDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
	public void addExamSubjects(List<ExamSubjectSong> examSubjectSongs) {
		if(CollectionUtils.isEmpty(examSubjectSongs)){
			return;
		}
		if(Objects.isNull(examSubjectSongs.get(0).getExaminationBasicId())){
			throw new BizException("请指定考级项目");
		}
		ExaminationBasic examinationBasic = examinationBasicDao.get(examSubjectSongs.get(0).getExaminationBasicId().longValue());
		if(Objects.isNull(examinationBasic)){
			throw new BizException("考级项目不存在");
		}
		if(!ExamStatusEnum.SETTING.equals(examinationBasic.getStatus())
			&&!ExamStatusEnum.NOT_START.equals(examinationBasic.getStatus())){
			throw new BizException("此状态考级项目不支持添加考级内容");
		}

		List<ExamSubjectSong> existExamSubjectSongs=examSubjectSongDao.findByExam(examSubjectSongs.get(0).getExaminationBasicId());
		Map<Long, List<Integer>> subjectLevelMap = new HashMap<>();
		Set<Long> existSubjectIds = new HashSet<>();
		if(!CollectionUtils.isEmpty(existExamSubjectSongs)){
			subjectLevelMap = existExamSubjectSongs.stream().collect(Collectors.groupingBy(ExamSubjectSong::getExamSubjectId, Collectors.mapping(ExamSubjectSong::getLevel, Collectors.toList())));
			existSubjectIds = existExamSubjectSongs.stream().map(ExamSubjectSong::getExamSubjectId).collect(Collectors.toSet());
		}

		List<ExamSubject> newExamSubjects = new ArrayList<>();
		for (ExamSubjectSong examSubjectSong : examSubjectSongs) {
			if(Objects.isNull(examSubjectSong.getExaminationBasicId())){
				throw new BizException("请指定考级项目");
			}
			if(Objects.isNull(examSubjectSong.getExamSubjectId())){
				throw new BizException("请选择专业");
			}
			if(Objects.isNull(examSubjectSong.getLevel())){
				throw new BizException("请指定报考等级");
			}
			List<Integer> levels = subjectLevelMap.get(examSubjectSong.getExamSubjectId());
			if(!CollectionUtils.isEmpty(levels)&&levels.contains(examSubjectSong.getLevel())){
				throw new BizException("考级内容等级重复");
			}
			if(Objects.isNull(examSubjectSong.getRegistrationFee())){
				throw new BizException("请指定报名费用");
			}

			boolean praNull = Objects.isNull(examSubjectSong.getPracticeNum());

			boolean perNull = Objects.isNull(examSubjectSong.getPerformNum());

			if(praNull&&perNull){
				throw new BizException("参数错误");
			}

			if(!praNull&&perNull){
				examSubjectSong.setPerformNum(0);
			}else if(!perNull&&praNull){
				examSubjectSong.setPracticeNum(0);
			}

			examSubjectSong.setTenantId(TenantContextHolder.getTenantId());

			if(existSubjectIds.contains(examSubjectSong.getExamSubjectId().longValue())){
				continue;
			}

			ExamSubject newExamSubject=new ExamSubject();
			newExamSubject.setExaminationBasicId(examSubjectSong.getExaminationBasicId());
			newExamSubject.setTenantId(examSubjectSong.getTenantId());
			newExamSubject.setSubjectId(examSubjectSong.getExamSubjectId().intValue());
			newExamSubject.setTenantId(TenantContextHolder.getTenantId());
			newExamSubjects.add(newExamSubject);
			existSubjectIds.add(newExamSubject.getSubjectId().longValue());
		}
		examSubjectSongDao.batchInsert(examSubjectSongs);
		if(!CollectionUtils.isEmpty(newExamSubjects)){
			examSubjectDao.batchInsert(newExamSubjects);
		}
	}

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

		List<ExamSubjectSongDto> dataList = new ArrayList<>();
		int count = examSubjectSongDao.countExamSubjectSongs(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = examSubjectSongDao.queryExamSubjectSongs(params);
			List<Integer> examSongIds=new ArrayList<>();
			if(!CollectionUtils.isEmpty(dataList)){
				for (ExamSubjectSongDto examSubjectSongDto : dataList) {
					if(StringUtils.isNotBlank(examSubjectSongDto.getPracticeSongIdList())){
						for (String s : examSubjectSongDto.getPracticeSongIdList().split(",")) {
							if(!examSongIds.contains(Integer.valueOf(s))){
								examSongIds.add(Integer.valueOf(s));
							}
						}
					}
					if(StringUtils.isNotBlank(examSubjectSongDto.getPerformSongIdList())){
						for (String s : examSubjectSongDto.getPerformSongIdList().split(",")) {
							if(!examSongIds.contains(Integer.valueOf(s))){
								examSongIds.add(Integer.valueOf(s));
							}
						}
					}
				}
				List<ExamSong> examSongs = new ArrayList<>();
				if(!CollectionUtils.isEmpty(examSongIds)){
					examSongs = examSongDao.getWithIds(examSongIds);
				}
				Map<Integer, ExamSong> idExamSongMap = examSongs.stream().collect(Collectors.toMap(ExamSong::getId, e -> e));
				for (ExamSubjectSongDto examSubjectSongDto : dataList) {
					if(StringUtils.isNotBlank(examSubjectSongDto.getPracticeSongIdList())){
						List<String> songNames=new ArrayList<>();
						for (String s : examSubjectSongDto.getPracticeSongIdList().split(",")) {
							if(idExamSongMap.containsKey(Integer.valueOf(s))){
								songNames.add(idExamSongMap.get(Integer.valueOf(s)).getSongName());
							}
						}
						examSubjectSongDto.setPracticeSongNames(StringUtils.join(songNames, ","));
					}
					if(StringUtils.isNotBlank(examSubjectSongDto.getPerformSongIdList())){
						List<String> songNames=new ArrayList<>();
						for (String s : examSubjectSongDto.getPerformSongIdList().split(",")) {
							if(examSongIds.contains(Integer.valueOf(s))){
								ExamSong examSong = idExamSongMap.get(Integer.valueOf(s));
								if(Objects.nonNull(examSong)){
									songNames.add(examSong.getSongName());
								}
							}
						}
						examSubjectSongDto.setPerformSongNames(StringUtils.join(songNames, ","));
					}
				}
			}
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public void deleteExamSubjectSong(Long id) {
		if(Objects.isNull(id)){
			throw new BizException("参数错误");
		}
		ExamSubjectSong examSubjectSong = examSubjectSongDao.get(id);
		if(Objects.isNull(examSubjectSong)){
			throw new BizException("数据错误");
		}
		ExaminationBasic examinationBasic = examinationBasicDao.get(examSubjectSong.getExaminationBasicId().longValue());
		if(Objects.isNull(examinationBasic)){
			throw new BizException("考级项目不存在");
		}
		if(!ExamStatusEnum.SETTING.equals(examinationBasic.getStatus())
			&&!ExamStatusEnum.NOT_START.equals(examinationBasic.getStatus())){
			throw new BizException("此状态无法删除");
		}
		int i = examSubjectSongDao.countExamSongsWithSubject(examSubjectSong.getExaminationBasicId().longValue(),examSubjectSong.getExamSubjectId().intValue());
		examSubjectSongDao.delete(id);
		if(i<=1){
			examSubjectDao.deleteWithExamSubject(examSubjectSong.getExaminationBasicId().longValue(), examSubjectSong.getExamSubjectId().intValue());
		}
	}

	@Override
    public List<ExamSong> getExamSubjectSong(Integer examinationBasicId,Long examSubjectId, Integer level) {
		List<ExamSong> examSongs = new ArrayList<>();
		ExamSubjectSong examSubjectSong = examSubjectSongDao.getExamSubjectSong(examinationBasicId,examSubjectId, level);
		if(examSubjectSong == null){
			return examSongs;
		}
		List<ExamSong> practiceSong = examSongDao.getExamSongs(examSubjectSong.getPracticeSongIdList());
		if(practiceSong != null){
			examSongs.addAll(practiceSong);
		}
		List<ExamSong> performSong = examSongDao.getExamSongs(examSubjectSong.getPerformSongIdList());
		if(performSong != null){
			examSongs.addAll(performSong);
		}
		return examSongs;
	}

    @Override
    public List<ExamSubjectSong> getExamSubjectLevels(Integer examinationBasicId, Long examSubjectId) {
		return examSubjectSongDao.getExamSubjectLevels(examinationBasicId,examSubjectId);
    }
}
