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

import cfca.sadk.org.bouncycastle.apache.bzip2.BZip2Constants;
import com.keao.edu.auth.api.client.SysUserFeignService;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.entity.SysConfig;
import com.keao.edu.common.enums.MessageTypeEnum;
import com.keao.edu.common.exception.BizException;
import com.keao.edu.common.page.PageInfo;
import com.keao.edu.common.service.SysMessageService;
import com.keao.edu.common.service.impl.BaseServiceImpl;
import com.keao.edu.common.tenant.TenantContextHolder;
import com.keao.edu.thirdparty.message.provider.JiguangPushPlugin;
import com.keao.edu.thirdparty.message.provider.YimeiSmsPlugin;
import com.keao.edu.user.dao.*;
import com.keao.edu.user.dto.ExamOrganStatisticsDto;
import com.keao.edu.user.dto.ExamOrganizationRelationExtraDto;
import com.keao.edu.user.entity.*;
import com.keao.edu.user.enums.ExamStatusEnum;
import com.keao.edu.user.enums.TransStatusEnum;
import com.keao.edu.user.enums.YesOrNoEnum;
import com.keao.edu.user.page.ExamOrganizationRelationQueryInfo;
import com.keao.edu.user.service.ExamOrganizationRelationService;
import com.keao.edu.user.service.OrganizationService;
import com.keao.edu.user.service.ShortUrlService;
import com.keao.edu.user.service.SysConfigService;
import com.keao.edu.util.collection.MapUtil;
import com.keao.edu.util.date.DateUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
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.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExamOrganizationRelationServiceImpl extends BaseServiceImpl<Long, ExamOrganizationRelation> implements ExamOrganizationRelationService {
	
	@Autowired
	private ExamOrganizationRelationDao examOrganizationRelationDao;
	@Autowired
	private ExaminationBasicDao examinationBasicDao;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private OrganizationDao organizationDao;
	@Autowired
	private ShortUrlService shortUrlService;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SysConfigService sysConfigService;
	@Autowired
	private TenantInfoDao tenantInfoDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private ExamLifecycleLogDao examLifecycleLogDao;
	@Autowired
	private ExamRegistrationPaymentDao examRegistrationPaymentDao;
	@Autowired
	private ExamManualLedgerDao examManualLedgerDao;

	public static final Set<ExamStatusEnum> EDIT_ABLE_EXAM_STATUS=new HashSet<>(Arrays.asList(ExamStatusEnum.SETTING,ExamStatusEnum.NOT_START,ExamStatusEnum.APPLYING,ExamStatusEnum.APPLIED));

	@Override
	public BaseDAO<Long, ExamOrganizationRelation> getDAO() {
		return examOrganizationRelationDao;
	}

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

		List<Integer> nextLevelOrganIds = organizationService.getNextLevelOrganIds(queryInfo.getOrganId(), false);
		params.put("organIds", nextLevelOrganIds);

		List<ExamOrganizationRelationExtraDto> dataList = new ArrayList<>();
		int count = examOrganizationRelationDao.countExamOrgans(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = examOrganizationRelationDao.queryExamOrgans(params);
			List<Integer> organIds = dataList.stream().map(ExamOrganizationRelation::getOrganId).collect(Collectors.toList());
			for (ExamOrganizationRelationExtraDto examOrganizationRelation : dataList) {
				if(examOrganizationRelation.getOrganId().equals(queryInfo.getOrganId())){
					examOrganizationRelation.setSelfOrgan(1);
				}
			}
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public List<ExamOrganizationRelationExtraDto> getChildOrgans(Long examId, Integer organId) {
		List<Integer> childOrganIds = organizationService.getChildOrganIds(organId, true);
		return examOrganizationRelationDao.getExamChildOrgans(examId,childOrganIds);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addExamOrganizations(Long examId, String orgainIdsStr) {
		if(Objects.isNull(examId)){
			throw new BizException("请指定考级项目");
		}
		if(StringUtils.isBlank(orgainIdsStr)){
			throw new BizException("请指定合作单位");
		}
		ExaminationBasic examinationBasic = examinationBasicDao.get(examId.longValue());
		if(Objects.isNull(examinationBasic)){
			throw new BizException("考级项目不存在");
		}
		if(!EDIT_ABLE_EXAM_STATUS.contains(examinationBasic.getStatus())){
			throw new BizException("当前状态暂不可添加合作单位");
		}

		Set<Integer> organIdsWithExam = examOrganizationRelationDao.getOrganIdsWithExam(examId.intValue());
		List<Integer> organIds = Arrays.stream(orgainIdsStr.split(",")).map(e -> Integer.valueOf(e)).collect(Collectors.toList());
		List<Organization> organs = organizationDao.getOrgans(organIds);
		if(organs.size()!=organIds.size()){
			throw new BizException("合作单位信息错误");
		}

		SysConfig baseUrlConfig = sysConfigService.findByParamName(SysConfigService.BASE_H5_URL);
		String baseUrl="";
		if(Objects.nonNull(baseUrlConfig)){
			baseUrl=baseUrlConfig.getParanValue();
		}
		baseUrl = baseUrl+"/#/signUp?";

		Map<Integer, Organization> idOrganMap = organs.stream().collect(Collectors.toMap(Organization::getId, o -> o));
		List<ExamOrganizationRelation> organizationRelations=new ArrayList<>();
		for (Integer organId : organIds) {
			if(organIdsWithExam.contains(organId)){
				throw new BizException("合作单位冲突");
			}
			ExamOrganizationRelation og = new ExamOrganizationRelation();
			og.setTenantId(TenantContextHolder.getTenantId());
			og.setExaminationBasicId(examId.intValue());
			og.setOrganId(organId);
			Organization organization = idOrganMap.get(organId);
			if(Objects.isNull(organization)){
				throw new BizException("合作单位信息错误");
			}
			og.setSendUrlFlag(1);
			og.setIsAllowArrangeExam(1);
			og.setSettlementType(organization.getSettlementType());
			og.setShareProfitAmount(organization.getShareProfitAmount());
			og.setTotalRegistrationStudentNum(BigDecimal.ZERO.intValue());
			og.setTotalPaymentAmount(BigDecimal.ZERO);
			og.setTotalTransAmount(BigDecimal.ZERO);
			og.setSelfRegistrationStudentNum(BigDecimal.ZERO.intValue());
			og.setSelfPaymentAmount(BigDecimal.ZERO);
			String registrationUrl = baseUrl + "examId=" + examId + "&organId=" + organId;
			String registShortUrl = shortUrlService.createShortUrl(registrationUrl);
			og.setUrl(registShortUrl);
			organizationRelations.add(og);
		}
		examOrganizationRelationDao.batchInsert(organizationRelations);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addExamOrganizations(List<ExamOrganizationRelation> organizationRelations, Integer selfOrganId) {
		if(CollectionUtils.isEmpty(organizationRelations)){
			throw new BizException("请指定考级项目");
		}
		if(Objects.isNull(organizationRelations.get(0).getExaminationBasicId())){
			throw new BizException("请指定考级项目");
		}
		ExaminationBasic examinationBasic = examinationBasicDao.get(organizationRelations.get(0).getExaminationBasicId().longValue());
		if(Objects.isNull(examinationBasic)){
			throw new BizException("考级项目不存在");
		}
		if(!EDIT_ABLE_EXAM_STATUS.contains(examinationBasic.getStatus())){
			throw new BizException("当前状态暂不可添加合作单位");
		}

		ExamOrganStatisticsDto examOrganizationRelation = examOrganizationRelationDao.getExamOrganizationRelation(examinationBasic.getId(), selfOrganId);
		if(Objects.isNull(examOrganizationRelation)){
			throw new BizException("操作异常");
		}

		Set<Integer> organIdsWithExam = examOrganizationRelationDao.getOrganIdsWithExam(examinationBasic.getId().intValue());
		List<Integer> organIds = organizationRelations.stream().filter(e->Objects.nonNull(e.getOrganId())).map(ExamOrganizationRelation::getOrganId).collect(Collectors.toList());
		if(organIds.size()!=organizationRelations.size()){
			throw new BizException("参数错误");
		}
		List<Organization> organs = organizationDao.getOrgans(organIds);
		if(organs.size()!=organIds.size()){
			throw new BizException("合作单位信息错误");
		}

		Map<Integer, Organization> idOrganMap = organs.stream().collect(Collectors.toMap(Organization::getId, o -> o));
		for (ExamOrganizationRelation og : organizationRelations) {
			if(organIdsWithExam.contains(og.getOrganId())){
				throw new BizException("合作单位冲突");
			}
			if(Objects.isNull(og.getIsAllowArrangeExam())){
				throw new BizException("参数错误");
			}
			if(Objects.isNull(og.getSettlementType())){
				throw new BizException("参数错误");
			}
			if(Objects.isNull(og.getShareProfitAmount())){
				throw new BizException("参数错误");
			}

			if(examOrganizationRelation.getIsAllowArrangeExam()==0){
				og.setIsAllowArrangeExam(0);
			}

			og.setTenantId(TenantContextHolder.getTenantId());
			og.setExaminationBasicId(examinationBasic.getId().intValue());

			og.setSendUrlFlag(0);
			og.setTotalRegistrationStudentNum(BigDecimal.ZERO.intValue());
			og.setTotalPaymentAmount(BigDecimal.ZERO);
			og.setTotalTransAmount(BigDecimal.ZERO);
			og.setSelfRegistrationStudentNum(BigDecimal.ZERO.intValue());
			og.setSelfPaymentAmount(BigDecimal.ZERO);
		}
		examOrganizationRelationDao.batchInsert(organizationRelations);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
	public void updateExamOrganizationRelation(ExamOrganizationRelation examOrganizationRelation,Integer selfOrganId) {
		if(Objects.isNull(examOrganizationRelation.getId())){
			throw new BizException("参数错误");
		}
		ExamOrganizationRelation organizationRelation = examOrganizationRelationDao.get(examOrganizationRelation.getId());
		if(Objects.isNull(organizationRelation)){
			throw new BizException("参数错误");
		}
		ExamOrganStatisticsDto selfOrgan = examOrganizationRelationDao.getExamOrganizationRelation(organizationRelation.getExaminationBasicId().longValue(), selfOrganId);
		if(Objects.isNull(selfOrgan)){
			throw new BizException("操作异常");
		}
		if(selfOrgan.getIsAllowArrangeExam()==0&&examOrganizationRelation.getIsAllowArrangeExam()==1){
			throw new BizException("暂无权限");
		}
		if(Objects.nonNull(examOrganizationRelation.getIsAllowArrangeExam())&&examOrganizationRelation.getIsAllowArrangeExam()==0){
			List<Integer> childOrganIds = organizationService.getChildOrganIds(organizationRelation.getOrganId(), false);
			examOrganizationRelationDao.updateOrganAllowArrangeExamStatus(organizationRelation.getExaminationBasicId().longValue(), 0, childOrganIds);
		}
		examOrganizationRelationDao.update(examOrganizationRelation);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteExamOrgan(Long id) {
		if(Objects.isNull(id)){
			throw new BizException("参数错误");
		}
		ExamOrganizationRelation organizationRelation = examOrganizationRelationDao.get(id);
		if(Objects.isNull(organizationRelation)){
			throw new BizException("删除失败");
		}
		List<Integer> childOrganIds = organizationService.getChildOrganIds(organizationRelation.getOrganId(), true);
		List<ExamOrganizationRelation> examOrganizationRelations = examOrganizationRelationDao.getExamOrganizationRelations(organizationRelation.getExaminationBasicId().longValue(), childOrganIds);
		long count = examOrganizationRelations.stream().filter(e -> e.getSendUrlFlag() == 1).count();
		if(count>0){
			throw new BizException("删除失败");
		}
		examOrganizationRelationDao.deleteExamOrgans(organizationRelation.getExaminationBasicId().longValue(), childOrganIds);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sendUrl(Integer examId, Integer selfOrganId) {
		if(Objects.isNull(examId)){
			throw new BizException("请指定考级项目");
		}

		List<Integer> childOrganIds = organizationService.getNextLevelOrganIds(selfOrganId, false);

		ExamOrganStatisticsDto examOrganizationRelation = examOrganizationRelationDao.getExamOrganizationRelation(examId.longValue(), selfOrganId);
		if(Objects.isNull(examOrganizationRelation)){
			throw new BizException("数据异常");
		}
		if(examOrganizationRelation.getSendUrlFlag()==0){
			throw new BizException("发送失败");
		}

		List<ExamOrganizationRelation> examOrgans = examOrganizationRelationDao.getExamOrganizationRelations(examId.longValue(), childOrganIds);
		Set<Integer> existOrganizationIds = examOrgans.stream().map(ExamOrganizationRelation::getOrganId).collect(Collectors.toSet());

		ExaminationBasic examinationBasic = examinationBasicDao.get(examId.longValue());
		if(Objects.isNull(examinationBasic)){
			throw new BizException("考级项目不存在");
		}
		if(ExamStatusEnum.CLOSE.equals(examinationBasic.getStatus())){
			throw new BizException("考级项目已关闭");
		}

		StringBuffer expectRegistTime = new StringBuffer(DateUtil.dateToString(examinationBasic.getEnrollStartTime(), "yyyy年MM月dd日 HH时mm分"));
		expectRegistTime.append("-");
		expectRegistTime.append(DateUtil.dateToString(examinationBasic.getEnrollEndTime(), "yyyy年MM月dd日 HH时mm分"));

		TenantInfo tenantInfo = tenantInfoDao.getWithOrgan(examinationBasic.getOrganId());
		if(Objects.isNull(tenantInfo)){
			throw new BizException("考级信息错误");
		}

		SysConfig baseUrlConfig = sysConfigService.findByParamName(SysConfigService.BASE_H5_URL);
		String baseUrl="";
		if(Objects.nonNull(baseUrlConfig)){
			baseUrl=baseUrlConfig.getParanValue();
		}
		baseUrl = baseUrl+"/#/signUp?";

		List<ExamOrganizationRelation> needUpdate=new ArrayList<>();
		for (ExamOrganizationRelation examOrgan : examOrgans) {
			if(YesOrNoEnum.YES.getCode().equals(examOrgan.getSendUrlFlag())){
				continue;
			}

			String registrationUrl = baseUrl + "examId=" + examinationBasic.getId() + "&organId=" + examOrgan.getOrganId();
			String registShortUrl = shortUrlService.createShortUrl(registrationUrl);
			examOrgan.setUrl(registShortUrl);
			examOrgan.setSendUrlFlag(1);

			needUpdate.add(examOrgan);

			SysUser organUser = sysUserDao.getWithOrgan(examOrgan.getOrganId());
			Map<Integer, String> userPhoneMap = new HashMap<>();
			userPhoneMap.put(organUser.getId(), organUser.getPhone());

			sysMessageService.batchSendMessage(MessageTypeEnum.EXAM_REGISTRATION_URL_SMS,
					userPhoneMap, null, 0, null, YimeiSmsPlugin.PLUGIN_NAME,
					tenantInfo.getName(), examinationBasic.getName(), expectRegistTime.toString(), examOrgan.getUrl());
		}

		if(!CollectionUtils.isEmpty(needUpdate)){
			examOrganizationRelationDao.batchUpdate(needUpdate);

			examLifecycleLogDao.insert(new ExamLifecycleLog(examinationBasic.getId().intValue(), "发送考级连接", examinationBasic.getCreatorId()));
		}

		if(examinationBasic.getStatus().equals(ExamStatusEnum.SETTING)){
			examinationBasic.setStatus(ExamStatusEnum.NOT_START);
			examinationBasicDao.update(examinationBasic);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void examStatusChangePush(Long examId, ExamStatusEnum examStatus) {
		if(Objects.isNull(examId)||Objects.isNull(examStatus)){
			return;
		}
		ExaminationBasic exam = examinationBasicDao.get(examId);
		if(Objects.isNull(exam)){
			return;
		}

		MessageTypeEnum messageType=null;

		switch (examStatus){
			case APPLIED:
				messageType = MessageTypeEnum.EXAM_REGISTRATION_CLOSE_SMS;
				break;
			case CLOSE:
				messageType = MessageTypeEnum.EXAM_CLOSE_SMS;
				break;
		}

		if(Objects.isNull(messageType)){
			return;
		}

		TenantInfo tenantInfo = tenantInfoDao.getWithOrgan(exam.getOrganId());
		List<ExamOrganizationRelation> examOrgans = examOrganizationRelationDao.getOrganInfoWithExam(examId.intValue());
		Map<Integer, String> userPhoneMap = new HashMap<>();
		for (ExamOrganizationRelation examOrgan : examOrgans) {
			if(examOrgan.getOrganId().equals(exam.getOrganId())){
				continue;
			}
			userPhoneMap.put(examOrgan.getOrganization().getUserId(), examOrgan.getOrganization().getContactPhone());
		}

		if(CollectionUtils.isEmpty(userPhoneMap)){
			return;
		}

		sysMessageService.batchSendMessage(messageType,
				userPhoneMap, null, 0, null, YimeiSmsPlugin.PLUGIN_NAME,
				tenantInfo.getName(), exam.getName());
	}

	@Override
	public void examDateChangePush(Long examId) {
		if(Objects.isNull(examId)){
			return;
		}
		ExaminationBasic exam = examinationBasicDao.get(examId);
		if(Objects.isNull(exam)){
			return;
		}

		TenantInfo tenantInfo = tenantInfoDao.getWithOrgan(exam.getOrganId());
		List<ExamOrganizationRelation> examOrgans = examOrganizationRelationDao.getOrganInfoWithExam(examId.intValue());
		Map<Integer, String> userPhoneMap = new HashMap<>();
		for (ExamOrganizationRelation examOrgan : examOrgans) {
			if(examOrgan.getOrganId().equals(exam.getOrganId())){
				continue;
			}
			userPhoneMap.put(examOrgan.getOrganization().getUserId(), examOrgan.getOrganization().getContactPhone());
		}

		if(CollectionUtils.isEmpty(userPhoneMap)){
			return;
		}

		String enrollStartTimeStr = DateUtil.dateToString(exam.getEnrollStartTime(), "yyyy年MM月dd日 HH时mm分");
		String enrollEndTimeStr = DateUtil.dateToString(exam.getEnrollEndTime(), "yyyy年MM月dd日 HH时mm分");

		sysMessageService.batchSendMessage(MessageTypeEnum.EXAM_REGIST_TIME_CHANGE_SMS,
				userPhoneMap, null, 0, null, YimeiSmsPlugin.PLUGIN_NAME,
				tenantInfo.getName(), exam.getName(), enrollStartTimeStr, enrollEndTimeStr);
	}

	@Override
	public void examRegistCutOffPush(Long examId) {
		if(Objects.isNull(examId)){
			return;
		}
		ExaminationBasic exam = examinationBasicDao.get(examId);
		if(Objects.isNull(exam)){
			return;
		}

		TenantInfo tenantInfo = tenantInfoDao.getWithOrgan(exam.getOrganId());
		List<ExamOrganizationRelation> examOrgans = examOrganizationRelationDao.getOrganInfoWithExam(examId.intValue());
		Map<Integer, String> userPhoneMap = new HashMap<>();
		for (ExamOrganizationRelation examOrgan : examOrgans) {
			userPhoneMap.put(examOrgan.getOrganization().getUserId(), examOrgan.getOrganization().getContactPhone());
		}

		if(CollectionUtils.isEmpty(userPhoneMap)){
			return;
		}

		sysMessageService.batchSendMessage(MessageTypeEnum.EXAM_REGIST_EXPIRE_SMS,
				userPhoneMap, null, 0, null, YimeiSmsPlugin.PLUGIN_NAME,
				tenantInfo.getName(), exam.getName());
	}

	@Override
	public ExamOrganStatisticsDto getExamOrganStatistics(Integer organId, Long examId) {
		if(Objects.isNull(examId)){
			throw new BizException("请指定考级项目");
		}
		ExaminationBasic examinationBasic = examinationBasicDao.get(examId);
		if(Objects.isNull(examinationBasic)){
			throw new BizException("考级项目不存在");
		}
		ExamOrganStatisticsDto examOrganStatistics = examOrganizationRelationDao.getExamOrganizationRelation(examId, organId);
		if(Objects.isNull(examOrganStatistics)){
			examOrganStatistics=new ExamOrganStatisticsDto();
		}

		if(Objects.isNull(examOrganStatistics.getSettlementType())){
			examOrganStatistics.setIsAllowArrangeExam(1);
		}

		examOrganStatistics.setExamLifecycleLogs(examLifecycleLogDao.findWithExam(examId));

		Map<String, BigDecimal> dayTransAmount=new LinkedHashMap<>();
		Map<String, BigDecimal> dayPaymentAmount=new LinkedHashMap<>();

		LocalDate today = LocalDate.now();
		List<String> days=new ArrayList<>();
		days.add(today.toString());
		dayTransAmount.put(today.toString(), BigDecimal.ZERO);
		dayPaymentAmount.put(today.toString(), BigDecimal.ZERO);
		for (int i=-1;i>-7;i--){
			days.add(today.plusDays(i).toString());
			dayTransAmount.put(today.plusDays(i).toString(), BigDecimal.ZERO);
			dayPaymentAmount.put(today.plusDays(i).toString(), BigDecimal.ZERO);
		}

		List<ExamRegistrationPayment> examRegistrationPayments = examRegistrationPaymentDao.getWithExamOrganAndDay(examId, organId, days);
		List<ExamManualLedger> examOrganManualLedgers = examManualLedgerDao.getExamOrganManualLedgers(organId, examId, days);

		Map<String, List<ExamRegistrationPayment>> dayPaymentMap = new HashMap<>();
		if(!CollectionUtils.isEmpty(examRegistrationPayments)){
			dayPaymentMap = examRegistrationPayments.stream().filter(e-> TransStatusEnum.SUCCESS.equals(e.getTransStatus())).collect(Collectors.groupingBy(e -> DateUtil.dateToString(e.getTransSuccessedTime())));
		}
		Map<String, List<ExamManualLedger>> dayLedgerMap = new HashMap<>();
		if(!CollectionUtils.isEmpty(examOrganManualLedgers)){
			dayLedgerMap = examOrganManualLedgers.stream().collect(Collectors.groupingBy(e -> DateUtil.dateToString(e.getTransTime())));
		}

		for (String day : dayTransAmount.keySet()) {
			List<ExamManualLedger> dayLeders = dayLedgerMap.get(day);
			if(CollectionUtils.isEmpty(dayLeders)){
				continue;
			}
			BigDecimal amount = dayLeders.stream().map(ExamManualLedger::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
			dayTransAmount.put(day, amount);
		}

		for (String day : dayPaymentAmount.keySet()) {
			List<ExamRegistrationPayment> dayPayments = dayPaymentMap.get(day);
			if(CollectionUtils.isEmpty(dayPayments)){
				continue;
			}
			BigDecimal amount = dayPayments.stream().map(ExamRegistrationPayment::getTransAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
			dayPaymentAmount.put(day, amount);
		}

		examOrganStatistics.setDayTransAmount(dayTransAmount);
		examOrganStatistics.setDayPaymentAmount(dayPaymentAmount);
		return examOrganStatistics;
	}

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

		List<Integer> nextLevelOrganIds = organizationService.getNextLevelOrganIds(queryInfo.getOrganId(), false);
		params.put("organIds", nextLevelOrganIds);

		List<Organization> dataList = new ArrayList<>();
		int count = examOrganizationRelationDao.countUnRelatedOrgans(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = examOrganizationRelationDao.queryUnRelatedOrgans(params);
		}
		ExamOrganStatisticsDto examOrganizationRelation = examOrganizationRelationDao.getExamOrganizationRelation(queryInfo.getExamId().longValue(), queryInfo.getOrganId());
		pageInfo.setRows(dataList);
		Map<String, Object> result=new HashMap<>();
		result.put("pageInfo", pageInfo);
		if(Objects.nonNull(examOrganizationRelation)){
			result.put("isAllowArrangeExam",examOrganizationRelation.getIsAllowArrangeExam());
		}else{
			result.put("isAllowArrangeExam",0);
		}
		return result;
	}
}
