package com.ruoyi.mall.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.weixin.utils.WeiXinUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.Bo.CheckingOutParamBo;
import com.ruoyi.mall.domain.Bo.MatchSchoolBO;
import com.ruoyi.mall.domain.Vo.*;
import com.ruoyi.mall.mapper.*;
import com.ruoyi.mall.service.IContrastRecordService;
import com.ruoyi.mall.service.IMallMemberCollectSchoolService;
import com.ruoyi.mall.service.IMallSchoolAcceptRecordService;
import com.ruoyi.mall.service.IMallSchoolService;
import com.ruoyi.set.domain.SetRegion;
import com.ruoyi.set.mapper.SetRegionMapper;
import com.ruoyi.set.service.ISetRegionService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 学校Service业务层处理
 *
 * @author lsm
 * @date 2023-10-18
 */
@Service
public class MallSchoolServiceImpl implements IMallSchoolService {
    @Resource
    private MallSchoolMapper mallSchoolMapper;

    @Resource
    private MallFacultyInfoMapper mallFacultyInfoMapper;

    @Resource
    private MallMajorClassMapper mallMajorClassMapper;

    @Resource
    private MallSchoolIntroduceMapper mallSchoolIntroduceMapper;

    @Resource
    private MallSchoolSceneryMapper mallSchoolSceneryMapper;

    @Resource
    private MallSchoolTagMapper mallSchoolTagMapper;

    @Resource
    private MallSchoolAcceptRecordMapper mallSchoolAcceptRecordMapper;

    @Resource
    private MallSchoolAcceptMapper mallSchoolAcceptMapper;

    @Resource
    private MallSchoolAppraiseMapper mallSchoolAppraiseMapper;

    @Resource
    private MallSchoolAcceptRulesMapper mallSchoolAcceptRulesMapper;

    @Resource
    private MallAcceptPlanMapper mallAcceptPlanMapper;

    @Resource
    private MallLinkMajorSchoolMapper mallLinkMajorSchoolMapper;

    @Resource
    private MallBatchMapper mallBatchMapper;

    @Resource
    private MallConfigLevelMapper mallConfigLevelMapper;

    @Resource
    private MallCountMethodServiceImpl mallCountMethodService;

    @Resource
    private MallMemberUserMapper mallMemberUserMapper;

    @Resource
    private IMallMemberCollectSchoolService mallMemberCollectSchoolService;

    @Resource
    private MallAcceptRateSettingMapper mallAcceptRateSettingMapper;

    @Resource
    private MallMemberTargetSchoolMapper mallMemberTargetSchoolMapper;

    @Resource
    private IContrastRecordService contrastRecordService;

    @Resource
    private SetRegionMapper setRegionMapper;

    @Resource
    private MallConfigTypeMapper mallConfigTypeMapper;

    @Resource
    private ContrastRecordMapper contrastRecordMapper;

    @Resource
    private MallSchoolMasterRecordMapper mallSchoolMasterRecordMapper;

    @Resource
    private MallSchoolBatchLinkMapper mallSchoolBatchLinkMapper;

    @Resource
    private MallSchoolLevelMapper mallSchoolLevelMapper;

    @Resource
    private MallSubjectClassMapper mallSubjectClassMapper;

    @Resource
    private MallAcceptRuleMapper mallAcceptRuleMapper;

    @Resource
    private MallExamDataMapper mallExamDataMapper;

    @Resource
    private WeiXinUtils weiXinUtils;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询学校
     *
     * @param schoolId 学校主键
     * @return 学校
     */
    @Override
    public MallSchool selectMallSchoolBySchoolId(Long schoolId) {

        MallSchool mallSchool = mallSchoolMapper.selectMallSchoolBySchoolId(schoolId);
        if (ObjectUtils.isNotEmpty(mallSchool)){
            // 学校批次查询
            List<Long> list = mallSchoolBatchLinkMapper.selectMallSchoolBatchLinkBySchoolId(mallSchool.getSchoolId());
            Long[] Longs = list.toArray(new Long[list.size()]);
            mallSchool.setBatchList(Longs);

            // 查询层次
            MallSchoolLevel mallSchoolLevel = mallSchoolLevelMapper.selectMallSchoolLevelBySchoolId(schoolId);
            if(ObjectUtils.isNotEmpty(mallSchoolLevel)){
                mallSchool.setConfigLevelId(mallSchoolLevel.getConfigLevelId());
                mallSchool.setConfigLevelName(mallSchoolLevel.getConfigLevelName());
            }
        }

        return mallSchool;
    }

    /**
     * 查询学校列表
     *
     * @param mallSchool 学校
     * @return 学校
     */
    @Override
    public List<MallSchool> selectMallSchoolList(MallSchool mallSchool) {
        List<MallSchool> list = mallSchoolMapper.selectMallSchoolList(mallSchool);
        return list;
    }

    /**
     * 查询学校列表 for excel
     *
     * @param mallSchool 学校
     * @return 学校
     */
    @Override
    public List<MallSchool> selectMallSchoolListForExcel(MallSchool mallSchool) {
        List<MallSchool> list = mallSchoolMapper.selectMallSchoolList(mallSchool);
        // if (!list.isEmpty()){
        //     List<MallSchoolLevel> mallSchoolLevels = mallSchoolLevelMapper.selectMallSchoolLevelBySchoolIds(
        //                     list.stream().map(MallSchool::getSchoolId).collect(Collectors.toList()));
        //     if (CollectionUtil.isNotEmpty(mallSchoolLevels)){
        //         Map<Long, MallSchoolLevel> collect = mallSchoolLevels.stream().collect(Collectors.toMap(MallSchoolLevel::getSchoolId, e -> e));
        //         list.stream().peek(l -> {
        //             MallSchoolLevel mallSchoolLevel = collect.get(l.getSchoolId());
        //             if (ObjectUtils.isNotEmpty(mallSchoolLevel)){
        //                 l.setConfigLevelId(mallSchoolLevel.getConfigLevelId());
        //                 l.setConfigLevelName(mallSchoolLevel.getConfigLevelName());
        //             }
        //         }).collect(Collectors.toList());
        //     }
        //     // for (MallSchool school : list) {
        //     //     // 查询层次
        //     //     MallSchoolLevel mallSchoolLevel = mallSchoolLevelMapper.selectMallSchoolLevelBySchoolId(school.getSchoolId());
        //     //     if(ObjectUtils.isNotEmpty(mallSchoolLevel)){
        //     //         school.setConfigLevelId(mallSchoolLevel.getConfigLevelId());
        //     //         school.setConfigLevelName(mallSchoolLevel.getConfigLevelName());
        //     //     }
        //     // }
        // }
        return list;
    }

    /**
     * 新增学校
     *
     * @param mallSchool 学校
     * @return 结果
     */
    @Override
    public int insertMallSchool(MallSchool mallSchool) {
        if (mallSchool.getProvinceId() != null) {
            SetRegion setRegion = setRegionMapper.selectSetRegionById(mallSchool.getProvinceId());
            if (setRegion != null) {
                mallSchool.setProvinceName(setRegion.getName());
            }
        }
        if (mallSchool.getCityId() != null) {
            SetRegion setRegion = setRegionMapper.selectSetRegionById(mallSchool.getCityId());
            if (setRegion != null) {
                mallSchool.setCityName(setRegion.getName());
            }
        }
        if (mallSchool.getAreaId() != null) {
            SetRegion setRegion = setRegionMapper.selectSetRegionById(mallSchool.getAreaId());
            if (setRegion != null) {
                mallSchool.setAreaName(setRegion.getName());
            }
        }

        MallConfigType mallConfigType = mallConfigTypeMapper.selectMallConfigTypeByConfigTypeId(mallSchool.getConfigTypeId());
        mallSchool.setConfigTypeName(mallConfigType.getConfigTypeName());
        mallSchool.setCreateAt(DateUtils.getTime());
        int i = mallSchoolMapper.insertMallSchool(mallSchool);

        // 批次学校关联
        Long[] batchList = mallSchool.getBatchList();
        if (batchList.length > 0){
            for (Long l : batchList) {
                // 批次查询
                MallBatch mallBatch = mallBatchMapper.selectMallBatchByBatchId(l);
                MallSchoolBatchLink mallSchoolBatchLink = new MallSchoolBatchLink();
                mallSchoolBatchLink.setSchoolId(mallSchool.getSchoolId());
                mallSchoolBatchLink.setBatchId(l);
                mallSchoolBatchLink.setBatchName(mallBatch.getBatchName());
                mallSchoolBatchLink.setCreateAt(DateUtils.getTime());
                mallSchoolBatchLink.setDelFlag("0");
                mallSchoolBatchLinkMapper.insertMallSchoolBatchLink(mallSchoolBatchLink);
            }
        }

        // 学校层次关联
        Long configLevelId = mallSchool.getConfigLevelId();
        // 查询层次列表
        MallConfigLevel mallConfigLevel = mallConfigLevelMapper.selectMallConfigLevelByConfigLevelId(configLevelId);
        MallSchoolLevel schoolLevel = new MallSchoolLevel();
        schoolLevel.setSchoolId(mallSchool.getSchoolId());
        schoolLevel.setConfigLevelId(configLevelId);
        schoolLevel.setConfigLevelName(mallConfigLevel.getConfigLevelName());
        schoolLevel.setCreateAt(DateUtils.getTime());
        schoolLevel.setDelFlag("0");
        mallSchoolLevelMapper.insertMallSchoolLevel(schoolLevel);


        return i;
    }

    /**
     * 修改学校
     *
     * @param mallSchool 学校
     * @return 结果
     */
    @Override
    public int updateMallSchool(MallSchool mallSchool) {
        if (mallSchool.getProvinceId() != null) {
            SetRegion setRegion = setRegionMapper.selectSetRegionById(mallSchool.getProvinceId());
            if (setRegion != null) {
                mallSchool.setProvinceName(setRegion.getName());
            }
        }
        if (mallSchool.getCityId() != null) {
            SetRegion setRegion = setRegionMapper.selectSetRegionById(mallSchool.getCityId());
            if (setRegion != null) {
                mallSchool.setCityName(setRegion.getName());
            }
        }
        if (mallSchool.getAreaId() != null) {
            SetRegion setRegion = setRegionMapper.selectSetRegionById(mallSchool.getAreaId());
            if (setRegion != null) {
                mallSchool.setAreaName(setRegion.getName());
            }
        }

        // 批次学校关联
        Long[] batchList = mallSchool.getBatchList();
        if (batchList.length > 0){
            // 删除不许要的批次
            mallSchoolBatchLinkMapper.deleteSchoolBatchBySchoolId(mallSchool.getSchoolId());
            for (Long l : batchList) {
                MallSchoolBatchLink link = mallSchoolBatchLinkMapper.selectSchoolBatchLinkBySchoolIdAndBatchId(mallSchool.getSchoolId(), Long.valueOf(l));
                if (ObjectUtils.isEmpty(link)){
                    // 新增
                    MallBatch mallBatch = mallBatchMapper.selectMallBatchByBatchId(Long.valueOf(l));
                    MallSchoolBatchLink mallSchoolBatchLink = new MallSchoolBatchLink();
                    mallSchoolBatchLink.setSchoolId(mallSchool.getSchoolId());
                    mallSchoolBatchLink.setBatchId(Long.valueOf(l));
                    mallSchoolBatchLink.setBatchName(mallBatch.getBatchName());
                    mallSchoolBatchLink.setCreateAt(DateUtils.getTime());
                    mallSchoolBatchLink.setDelFlag("0");
                    mallSchoolBatchLinkMapper.insertMallSchoolBatchLink(mallSchoolBatchLink);
                }
            }
        }

        // 学校层次关联
        Long configLevelId = mallSchool.getConfigLevelId();
        MallSchoolLevel schoolLevel = mallSchoolLevelMapper.selectMallSchoolLevelBySchoolId(mallSchool.getSchoolId());
        MallConfigLevel mallConfigLevel = mallConfigLevelMapper.selectMallConfigLevelByConfigLevelId(configLevelId);
        if (ObjectUtils.isNotEmpty(schoolLevel)){
            // 查询层次列表
            schoolLevel.setConfigLevelId(configLevelId);
            schoolLevel.setConfigLevelName(mallConfigLevel.getConfigLevelName());
            schoolLevel.setUpdateAt(DateUtils.getTime());
            mallSchoolLevelMapper.updateMallSchoolLevel(schoolLevel);
        } else {
            MallSchoolLevel level = new MallSchoolLevel();
            level.setSchoolId(mallSchool.getSchoolId());
            level.setConfigLevelId(configLevelId);
            level.setConfigLevelName(mallConfigLevel.getConfigLevelName());
            level.setCreateAt(DateUtils.getTime());
            mallSchoolLevelMapper.insertMallSchoolLevel(level);
        }



        MallConfigType mallConfigType = mallConfigTypeMapper.selectMallConfigTypeByConfigTypeId(mallSchool.getConfigTypeId());
        mallSchool.setConfigTypeName(mallConfigType.getConfigTypeName());
        return mallSchoolMapper.updateMallSchool(mallSchool);
    }

    /**
     * 批量删除学校
     *
     * @param schoolIds 需要删除的学校主键
     * @return 结果
     */
    @Override
    public int deleteMallSchoolBySchoolIds(Long[] schoolIds) {
        return mallSchoolMapper.deleteMallSchoolBySchoolIds(schoolIds);
    }

    /**
     * 删除学校信息
     *
     * @param schoolId 学校主键
     * @return 结果
     */
    @Override
    public int deleteMallSchoolBySchoolId(Long schoolId) {
        return mallSchoolMapper.deleteMallSchoolBySchoolId(schoolId);
    }

    /**
     * 查询学校列表
     *
     * @param schoolName    学校名称
     * @param batchId       批次id
     * @param configLevelId 层次id
     * @param configTypeId  学校类型id
     * @param provinceId    省份id
     * @param cityId        城市id
     * @param pageNum       页码
     * @param pageSize      每页个数
     * @return 结果
     */
    @Override
    public PageInfo<SchoolVO> selectSchoolList(String schoolName,
                                               Long batchId,
                                               Long configLevelId,
                                               Long configTypeId,
                                               Long provinceId,
                                               Long cityId,
                                               Integer pageNum,
                                               Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SchoolVO> schoolList = mallSchoolMapper.selectSchoolList(schoolName, batchId, configLevelId, configTypeId, provinceId, cityId, null,null);

        if (schoolList.size() > 0) {
            for (SchoolVO schoolVO : schoolList) {
                if (StringUtils.isNotBlank(schoolVO.getTags())) {
                    // 查询标签列表
                    List<String> list = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                    schoolVO.setTagList(list);
                }
            }
        }

        return new PageInfo<>(schoolList);
    }

    /**
     * 大学对比学校列表
     * @param schoolName 学校名称
     * @param batchId 批次id
     * @param configLevelId 层次id
     * @param configTypeId 学校类型id
     * @param provinceId 省份id
     * @param cityId 城市id
     * @param pageNum 页码
     * @param pageSize 每页个数
     * @return 结果
     */
    @Override
    public AjaxResult selectMatchSchoolList(String schoolName,
                                                    Long batchId,
                                                    Long configLevelId,
                                                    Long configTypeId,
                                                    Long provinceId,
                                                    Long cityId,
                                                    Long id,
                                                    Integer pageNum,
                                                    Integer pageSize) {
        // 查询用户成绩
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        if (ObjectUtils.isEmpty(mallMemberUser.getMajorScore()) || ObjectUtils.isEmpty(mallMemberUser.getCultureScore())){
            return AjaxResult.error("请先录入成绩");
        }
        Integer majorScore = mallMemberUser.getMajorScore();
        Integer cultureScore = mallMemberUser.getCultureScore();
        //选科：0-文科，1-理科
        String subjectType = mallMemberUser.getSubjectType();

        PageHelper.startPage(pageNum, pageSize);
        List<SchoolVO> schoolList = mallSchoolMapper.selectMatchSchoolList(schoolName, batchId, configLevelId, configTypeId, provinceId, cityId, null, subjectType);

        if (schoolList.size() > 0) {
            for (SchoolVO schoolVO : schoolList) {
                //查询该学校 该批次 学生是否已添加
                ContrastRecord contrastRecord = new ContrastRecord();
                contrastRecord.setBatchId(batchId);
                contrastRecord.setUserId(id);
                contrastRecord.setSchoolId(schoolVO.getSchoolId());
                List<ContrastRecord> contrastRecords = contrastRecordService.selectContrastRecordList(contrastRecord);
                if(null != contrastRecords && contrastRecords.size()>0){//已添加
                    schoolVO.setRecordType("1");
                }else{//未添加
                    schoolVO.setRecordType("0");
                }
                // 查询标签列表
                if (StringUtils.isNotBlank(schoolVO.getTags())) {
                    List<String> list = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                    schoolVO.setTagList(list);
                }

                //// 学校录取率
                //Map<String, Object> result = mallCountMethodService.getAcceptRate(subjectType, schoolVO.getSchoolId(), batchId, cultureScore, majorScore);
                //if (!result.isEmpty() && new BigDecimal(result.get("acceptRate").toString()).compareTo(BigDecimal.ZERO) > 0 ){
                //    schoolVO.setAcceptRate(new BigDecimal(result.get("acceptRate").toString()));
                //    schoolVO.setShowAcceptRate(schoolVO.getAcceptRate() + "%");
                //    schoolVO.setRateType((Integer)result.get("rateType"));
                //}
            }
        }
        PageInfo<SchoolVO> pageInfo = new PageInfo<>(schoolList);
        return AjaxResult.success(pageInfo);
    }

    /**
     * 学校概述
     *
     * @param schoolId 学校id
    * @param batchId 批次id
     * @param id 用户id
     * @return 结果
     */
    @Override
    public SchoolVO selectSchoolDetail(Long id, Long schoolId, Long batchId) {
        // 学校基础信息
        SchoolVO schoolVO = mallSchoolMapper.selectSchoolDetail(schoolId);

        if (StringUtils.isNotBlank(schoolVO.getTags())) {
            // 查询标签列表
            List<String> list = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
            schoolVO.setTagList(list);
        }

        // 学校学院专业列表
        SchoolFacultyVO schoolFacultyVO = mallFacultyInfoMapper.selectSchoolFacultyDetail(schoolId);
        if (ObjectUtils.isNotEmpty(schoolFacultyVO)) {

            String facultyMajor = schoolFacultyVO.getFacultyMajor();
            if (StringUtils.isNotBlank(facultyMajor)) {
                // 查询专业列表
                List<FacultyMajorVO> majorVOList = mallMajorClassMapper.selectMajorShortInfoByMajorId(facultyMajor);
                schoolFacultyVO.setFacultyMajorList(majorVOList);
                schoolVO.setSchoolFaculty(schoolFacultyVO);
            }
        }

        // 学校特色介绍
        List<SchoolIntroduceVO> schoolIntroduceVOS = mallSchoolIntroduceMapper.selectSchoolIntroduceList(schoolId);
        schoolVO.setSchoolIntroduceList(schoolIntroduceVOS);

        // 是否加入对比
        List<Long> longs = contrastRecordMapper.selectSchoolContrastStatus(id, schoolId, batchId);
        if (longs.isEmpty()){
            schoolVO.setRecordType("0");
        }else{
            schoolVO.setRecordType("1");
            schoolVO.setRecordId(longs.get(0));
        }

        return schoolVO;
    }

    /**
     * 校园风景
     *
     * @param schoolId 学校id
     * @param pageNum  页码
     * @param pageSize 每页个数
     * @return 结果
     */
    @Override
    public PageInfo<SchoolSceneryVO> selectSchoolSceneryList(Long schoolId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SchoolSceneryVO> schoolSceneryVOS = mallSchoolSceneryMapper.selectSchoolSceneryList(schoolId);
        return new PageInfo<>(schoolSceneryVOS);
    }

    /**
     * 学校介绍详情
     *
     * @param schoolId 学校id
     * @return 结果
     */
    @Override
    public SchoolVO selectSchoolIntroduceDetail(Long schoolId) {
        return mallSchoolMapper.selectSchoolIntroduceDetail(schoolId);
    }

    /**
     * 学校录取数据
     * @param schoolId     学校id
     * @param batchId      批次id
     * @return 结果
     */
    @Override
    public AjaxResult selectSchoolRecord( Long schoolId, Long batchId, Long id) {

        // 查询用户信息
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        if (StringUtils.isBlank(mallMemberUser.getSubjectType())){
            return AjaxResult.error("请先完善学科信息");
        }

        String subjectType = mallMemberUser.getSubjectType();
        // 院校录取数据
        List<SchoolAcceptRecordVO> recordList = mallSchoolAcceptRecordMapper.selectAcceptRecordList(schoolId, batchId, subjectType);

        // 专业录取数据
        List<SchoolMajorAcceptRecordVO> majorRecordList = mallSchoolAcceptMapper.selectSchoolMajorRecordList(schoolId, batchId , subjectType);
        // 有参考分的计算录取率
        for (SchoolMajorAcceptRecordVO schoolMajorAcceptRecordVO : majorRecordList) {

            if (batchId == 4L){
                // 专科
                if (schoolMajorAcceptRecordVO.getAcceptLowest() != null ){
                    if ( mallMemberUser.getCultureScore() != null &&  mallMemberUser.getMajorScore() != null){

                        Map<String, Object> resultRate = mallCountMethodService.zhuankegetAcceptRateForReport(schoolMajorAcceptRecordVO.getAcceptLowest(), schoolMajorAcceptRecordVO.getAcceptRuleId(), mallMemberUser.getCultureScore(), mallMemberUser.getMajorScore());

                        schoolMajorAcceptRecordVO.setAcceptRate(resultRate.get("acceptRate") + "%");
                    }else{
                        schoolMajorAcceptRecordVO.setAcceptRate("0");
                    }
                }
            }else{
                // 本科
                if (schoolMajorAcceptRecordVO.getIsReference() != null &&schoolMajorAcceptRecordVO.getIsReference().equals(1)){

                    if ( mallMemberUser.getCultureScore() != null &&  mallMemberUser.getMajorScore() != null){

                        Map<String, Object> resultRate = mallCountMethodService.getAcceptRateForReport(schoolMajorAcceptRecordVO.getReference(), schoolMajorAcceptRecordVO.getAcceptRuleId(), mallMemberUser.getCultureScore(), mallMemberUser.getMajorScore());

                        schoolMajorAcceptRecordVO.setAcceptRate(resultRate.get("acceptRate") + "%");
                    }else{
                        schoolMajorAcceptRecordVO.setAcceptRate("0");
                    }


                }
            }

        }

        List<SchoolMajorAcceptGroupVO> majorRecordCollect = new ArrayList<>();
        if (majorRecordList.size() > 0) {
            Map<String, List<SchoolMajorAcceptRecordVO>> collect = majorRecordList.stream().collect(Collectors.groupingBy(SchoolMajorAcceptRecordVO::getAcceptYear));

            Set<String> years = collect.keySet();
            List<String> sortedYears = years.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
            for (String sortedYear : sortedYears) {
                Integer isReference = 0;
                List<SchoolMajorAcceptRecordVO> collect1 = majorRecordList.stream().filter(item -> item.getAcceptYear().equals(sortedYear)).collect(Collectors.toList());
                if (collect1.get(0).getIsReference() != null && collect1.get(0).getIsReference() == 1 && sortedYears.indexOf(sortedYear) == 0){
                    isReference = 1;
                }
                SchoolMajorAcceptGroupVO schoolMajorAcceptGroup = new SchoolMajorAcceptGroupVO();
                schoolMajorAcceptGroup.setYear(sortedYear);
                schoolMajorAcceptGroup.setIsReference(isReference);

                List<SchoolMajorAcceptRecordVO> subList = collect.get(sortedYear).stream()
                        .sorted(Comparator.comparing(SchoolMajorAcceptRecordVO::getAcceptRuleId))
                        .collect(Collectors.toList());

                // 录取原则分组划前端横线
                if (subList.size() > 0){
                    List<List<SchoolMajorAcceptRecordVO>> list = new ArrayList<>();
                    Map<String, List<SchoolMajorAcceptRecordVO>> listMap = subList.stream().collect(Collectors.groupingBy(SchoolMajorAcceptRecordVO::getAcceptRuleStr));
                    for (String s : listMap.keySet()) {
                        list.add(listMap.get(s));
                    }
                    schoolMajorAcceptGroup.setList(list);
                }
                majorRecordCollect.add(schoolMajorAcceptGroup);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("recordList", recordList);
        result.put("majorRecordList", majorRecordCollect);

        return AjaxResult.success(result);
    }

    /**
     * 我的综合分
     * @param schoolId
     * @param batchId
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> myTotalScore(Long schoolId, Long batchId, Long id) {
        // 查询用户信息
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        BigDecimal totalScore = BigDecimal.ZERO;
        // 专业录取数据
        Long ruleId = mallSchoolAcceptMapper.selectNewAccept(schoolId, batchId , mallMemberUser.getSubjectType());
        if (null != ruleId && null != mallMemberUser.getCultureScore() && null != mallMemberUser.getMajorScore()){
            // 计算综合分
             totalScore = mallCountMethodService.getTotalScore(mallMemberUser.getCultureScore(), mallMemberUser.getMajorScore(), ruleId);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("score", totalScore);
        return map;
    }

    /**
     * 院校录取数据详情
     * @param schoolAcceptRecordId 数据id
     * @return 结果
     */
    @Override
    public AjaxResult selectSchoolRecordDetail(Long schoolAcceptRecordId) {
        return AjaxResult.success(mallSchoolAcceptRecordMapper.selectSchoolRecordDetail(schoolAcceptRecordId));
    }

    /**
     * 学校评估列表
     * @param schoolId 学校id
     * @return 结果
     */
    @Override
    public List<SchoolAppraiseVO> selectSchoolAppraiseList(Long schoolId) {
        return mallSchoolAppraiseMapper.selectSchoolAppraiseList(schoolId);
    }

    /**
     * 学校招生简章
     * @param schoolId 学校id
     * @return 结果
     */
    @Override
    public AjaxResult schoolAboutInfo(Long schoolId, Long batchId, Long id) {

        // 批次名称
        MallBatch mallBatch = mallBatchMapper.selectMallBatchByBatchId(batchId);
        String batchName = mallBatch.getBatchName();

        // 招生简章
        List<SchoolRulesVO> schoolRulesList = mallSchoolAcceptRulesMapper.selectSchoolRulesList(schoolId);

        // 用户信息
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        if (StringUtils.isBlank(mallMemberUser.getSubjectType())){
            return AjaxResult.error("请先完善用户学科信息");
        }
        String subjectType = mallMemberUser.getSubjectType();

        // 招生计划
        List<SchoolAcceptPlanVO> planList = mallAcceptPlanMapper.selectAcceptPlanList(schoolId, batchId, subjectType);

        //for (SchoolAcceptPlanVO schoolAcceptPlanVO : planList) {

            //// 投档公式
            //Long acceptRuleId = schoolAcceptPlanVO.getAcceptRuleId();
            //String countMethodStr = mallCountMethodService.getCountMethodStr(acceptRuleId);
            //schoolAcceptPlanVO.setAcceptRuleStr(countMethodStr);


            //// 专业名称处理
            //Long majorId = schoolAcceptPlanVO.getMajorId();
            //List<String> list = mallLinkMajorSchoolMapper.selectSchoolMajorByParentId(schoolId, majorId);
            //if (list.size() > 0){
            //    StringBuilder sb = new StringBuilder();
            //    for (String s : list) {
            //        sb.append(s).append(",");
            //    }
            //    String str = sb.toString();
            //    String result = str.substring(0, str.length() - 1);
            //    schoolAcceptPlanVO.setMajorStr(schoolAcceptPlanVO.getMajorName() + "(" + result + ")");
            //}else{
            //    schoolAcceptPlanVO.setMajorStr(schoolAcceptPlanVO.getMajorName());
            //}

        //}

        List<SchoolAcceptPlanGroupVO> groupList = new ArrayList<>();
        if (planList.size() > 0){
            Map<String, List<SchoolAcceptPlanVO>> collect = planList.stream().collect(Collectors.groupingBy(SchoolAcceptPlanVO::getPlanYear));

            Set<String> planYears = collect.keySet();
            List<String> yearsList = planYears.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

            for (String year : yearsList) {
                List<SchoolAcceptPlanVO> sortedList = collect.get(year).stream().sorted(Comparator.comparing(SchoolAcceptPlanVO::getPlanYear)).collect(Collectors.toList());
                // 查询专业
                SchoolAcceptPlanGroupVO acceptPlanGroupVO = new SchoolAcceptPlanGroupVO();
                acceptPlanGroupVO.setYear(year);
                acceptPlanGroupVO.setBatchName(batchName);
                acceptPlanGroupVO.setPlanList(sortedList);
                groupList.add(acceptPlanGroupVO);
            }
        }

        // 更新时间
        String updateRange = "";
        Map<String, String> map = mallAcceptPlanMapper.selectUpdateTime(schoolId, batchId);
        if (ObjectUtils.isNotEmpty(map)){
            String startTime = map.get("startTime");
            String endTime = map.get("endTime");
            String start = DateUtils.format(DateUtils.parseDate(startTime), "M-dd");
            String end = DateUtils.format(DateUtils.parseDate(endTime), "M-dd");

            if (start.equals(end)){
                updateRange = start;
            }else{
                if (end == null){
                    updateRange = start;
                }else{
                    updateRange = start + "~" + end;
                }

            }
        }


        Map<String, Object> result = new HashMap<>();
        result.put("acceptRules", schoolRulesList);
        result.put("acceptPlan", groupList);
        result.put("updateRange", updateRange);

        return AjaxResult.success(result);
    }

    /**
     * 3个层次院校列表
     * @param configLevelId 层次id
     * @param batchId 批次id
     * @return 结果
     */
    @Override
    public AjaxResult selectSchoolListByLevel(Long configLevelId, Long batchId, Long schoolId, Long id) {
        // 查询当前层次
        List<SchoolLevelVO> allLevelList = mallConfigLevelMapper.selectLevelList();
        Long higherLevelId = null;
        Long lowerLevelId = null;

        if (!(allLevelList.size() > 0)){
            return AjaxResult.error("层次信息异常");
        }
        List<SchoolLevelVO> collect = allLevelList.stream().filter(item -> item.getConfigLevelId().equals(configLevelId)).collect(Collectors.toList());
        if (!(collect.size() > 0)){
            return AjaxResult.error("当前层次不存在");
        }

        SchoolLevelVO schoolLevelVO = collect.get(0);
        int i = allLevelList.indexOf(schoolLevelVO);
        if (allLevelList.size() > 1){

            if (i == 0){

                lowerLevelId = allLevelList.get(i + 1).getConfigLevelId();
            }else if (i == allLevelList.size()-1){
                higherLevelId = allLevelList.get(i - 1).getConfigLevelId();
            }else{
                higherLevelId = allLevelList.get(i - 1).getConfigLevelId();
                lowerLevelId = allLevelList.get(i + 1).getConfigLevelId();
            }
        }

        List<SchoolVO> higherLevelList = new ArrayList<>();
        List<SchoolVO> sameLevelList = new ArrayList<>();
        List<SchoolVO> lowerLevelList = new ArrayList<>();

        Map<String, Object> higherMap = new HashMap<>();
        Map<String, Object> sameMap = new HashMap<>();
        Map<String, Object> lowerMap = new HashMap<>();

        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        if (StringUtils.isBlank(mallMemberUser.getSubjectType())){
            return AjaxResult.error("请先完善学科信息");
        }
        String subjectType = mallMemberUser.getSubjectType();

        // 高一层次
        if (!ObjectUtils.isEmpty(higherLevelId)){
             higherLevelList = this.selectLevelSchoolList(higherLevelId, batchId, schoolId, subjectType);
            higherMap.put("higherLevelId", higherLevelId);
            higherMap.put("higherLevelList", higherLevelList);
        }
        // 同一层次
        if (!ObjectUtils.isEmpty(configLevelId)){
             sameLevelList = this.selectLevelSchoolList(configLevelId, batchId, schoolId, subjectType);
             sameMap.put("sameLevelId", configLevelId);
             sameMap.put("sameLevelList", sameLevelList);
        }

        // 低一层次
        if (!ObjectUtils.isEmpty(lowerLevelId)){
             lowerLevelList = this.selectLevelSchoolList(lowerLevelId, batchId, schoolId, subjectType);
             lowerMap.put("lowerLevelId", lowerLevelId);
             lowerMap.put("lowerLevelList", lowerLevelList);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("higherLevelSchoolList", higherMap);
        result.put("sameLevelSchoolList", sameMap);
        result.put("lowLevelSchoolList", lowerMap);

        return AjaxResult.success(result);

    }

    /**
     * 查询当前层次学校列表
     * @param configLevelId 层次id
     * @param batchId 批次id
     * @return
     */
    public List<SchoolVO> selectLevelSchoolList(Long configLevelId, Long batchId, Long schoolId, String subjectType){
        // 查询该层次下学校列表
        PageHelper.startPage(1, 3);
        List<SchoolVO> schoolList = mallSchoolMapper.selectSchoolListByLevelId( batchId, configLevelId , schoolId, subjectType);

        if (schoolList.size() > 0){
            for (SchoolVO schoolVO : schoolList) {
                if (StringUtils.isNotBlank(schoolVO.getTags())) {
                    // 查询标签列表
                    List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                    schoolVO.setTagList(tagList);
                }
            }
        }

        return schoolList;

    }

    /**
     * 层级院校列表
     * @param configLevelId 层级id
     * @param batchId 批次id
     * @param pageNum 页码
     * @param pageSize 每页个数
     * @return
     */
    @Override
    public PageInfo<SchoolVO> selectSchoolListByLevelId(Long configLevelId, Long batchId, Long schoolId, Long id, Integer pageNum, Integer pageSize) {
        // 查询用户信息
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);

        PageHelper.startPage(pageNum, pageSize);
        List<SchoolVO> schoolVOS = mallSchoolMapper.selectSchoolListByLevelId(batchId, configLevelId, schoolId, mallMemberUser.getSubjectType() );

        if (schoolVOS.size() > 0){
            for (SchoolVO schoolVO : schoolVOS) {
                if (StringUtils.isNotBlank(schoolVO.getTags())) {
                    // 查询标签列表
                    List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                    schoolVO.setTagList(tagList);
                }
            }
        }
        return new PageInfo<>(schoolVOS);
    }

    /**
     * 联考成绩分析
     * @param schoolId 学校id
     * @param batchId 批次id
     * @param id 用户id
     * @param pageNum 页码
     * @param pageSize 每页个数
     * @return 结果
     */
    @Override
    public AjaxResult selectUnionTestAnalysisList(Long schoolId, Long batchId, Long id, Integer pageNum, Integer pageSize) {

        // 查询用户成绩
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        if (StringUtils.isBlank(mallMemberUser.getSubjectType())){
            return AjaxResult.error("请先完善用户学科信息");
        }

        // 查询院校录取信息
        PageHelper.startPage(pageNum, pageSize);
        List<UnionTestAnalysisVO> list = mallSchoolAcceptRecordMapper.selectUnionTestAnalysisList(schoolId, batchId, mallMemberUser.getSubjectType());

        if (list.size() > 0){
            for (UnionTestAnalysisVO unionTestAnalysisVO : list) {
                // 计算所需文化分
                Integer majorScore = mallMemberUser.getMajorScore();
                BigDecimal acceptLowest = unionTestAnalysisVO.getAcceptLowest();
                BigDecimal cultureLowest = unionTestAnalysisVO.getCultureLowest();
                if (ObjectUtils.isNotEmpty(majorScore) && ObjectUtils.isNotEmpty(acceptLowest) ){
                    Long acceptRuleId = unionTestAnalysisVO.getAcceptRuleId();
                    MallAcceptRule mallAcceptRule = mallAcceptRuleMapper.selectMallAcceptRuleByAcceptRuleId(acceptRuleId);
                    BigDecimal needCultureScore = null;
                    // 如果录取原则没有文化分,则需要文化分为过线文化分
                    if (!mallAcceptRule.getRuleStr().contains("文化")){
                        needCultureScore = cultureLowest;
                    }else{
                        needCultureScore = mallCountMethodService.getNeedCultureScore(majorScore, acceptLowest, acceptRuleId);
                    }
                    unionTestAnalysisVO.setNeedCultureScore(needCultureScore);
                }

            }
        }
        PageInfo<UnionTestAnalysisVO> pageInfo = new PageInfo<>(list);

        return AjaxResult.success(pageInfo);
    }

    /**
     * 综合成绩分析
     * @param schoolId 学校id
     * @param batchId 批次id
     * @param id 用户id
     * @param pageNum 页码
     * @param pageSize 每页个数
     * @return 结果
     */
    @Override
    public AjaxResult selectUserScoreAnalysisList(Long schoolId, Long batchId, Long id, Integer pageNum, Integer pageSize) {
        // 用户录取信息
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);

        if (StringUtils.isBlank(mallMemberUser.getSubjectType())){
            return AjaxResult.error("请先完善用户学科信息");
        }
        String subjectType = mallMemberUser.getSubjectType();
        // 专业录取信息
        PageHelper.startPage(pageNum, pageSize);
        List<UserScoreAnalysisVO> list = mallSchoolAcceptRecordMapper.selectUserScoreAnalysisList(schoolId, batchId, subjectType);

        if(ObjectUtils.isNotEmpty(mallMemberUser.getCultureScore()) && ObjectUtils.isNotEmpty(mallMemberUser.getMajorScore())){
            // 计算综合分
            if (!list.isEmpty()){
                for (UserScoreAnalysisVO userScoreAnalysisVO : list) {
                    BigDecimal totalScore = mallCountMethodService.getTotalScore(mallMemberUser.getCultureScore(), mallMemberUser.getMajorScore(), userScoreAnalysisVO.getAcceptRuleId());
                    userScoreAnalysisVO.setMyScore(totalScore);
                    if (userScoreAnalysisVO.getAcceptLowest() != null) {
                        userScoreAnalysisVO.setScoreDifference(totalScore.subtract(new BigDecimal(userScoreAnalysisVO.getAcceptLowest().toString())));
                    }

                }
            }
        }
        PageInfo<UserScoreAnalysisVO> pageInfo = new PageInfo<>(list);

        return AjaxResult.success(pageInfo);
    }

    /**
     * 智能匹配大学
     * @param matchSchoolBO 匹配参数
     * @return 结果
     */
    @Override
    public AjaxResult matchSchoolList(MatchSchoolBO matchSchoolBO) {
        Long batchId = matchSchoolBO.getBatchId();
        Integer cultureScore = matchSchoolBO.getCultureScore();
        Integer majorScore = matchSchoolBO.getMajorScore();
        Long subjectId = matchSchoolBO.getSubjectId();

        // 查询学科
        //MallSubjectClass mallSubjectClass = mallSubjectClassMapper.selectMallSubjectClassBySubjectId(subjectId);
        //String subjectType = "文科".equals(mallSubjectClass.getSubjectName()) || "文".equals(mallSubjectClass.getSubjectName())? "0" : "1";
        String subjectType = subjectId == 1L? "0" : "1";
        // 查询批次大学列表
        List<SchoolVO> schoolVOS = mallSchoolMapper.selectSchoolList(null, batchId, null, null, null, null, null, subjectType);

        // 判断是否符合批次
        List<Map<String, Object>> resultList = new ArrayList<>();

        // 分组结果集
        Map<String, Object> result0 = new HashMap<>();
        Map<String, Object> result1 = new HashMap<>();
        Map<String, Object> result2 = new HashMap<>();
        Map<String, Object> result3 = new HashMap<>();

        // 分组
        List<SchoolVO> list0 = new ArrayList<>();
        List<SchoolVO> list1 = new ArrayList<>();
        List<SchoolVO> list2 = new ArrayList<>();
        List<SchoolVO> list3 = new ArrayList<>();
        if (!schoolVOS.isEmpty()){
            //List<MallSchoolTag> allTag = mallSchoolTagMapper.selectTagList();
            // 学校录取率计算
            try {
                CountDownLatch countDownLatch = new CountDownLatch(schoolVOS.size());

                for (SchoolVO schoolVO : schoolVOS) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            MallSchoolAccept mallSchoolAccept = new MallSchoolAccept();
                            Map<String, Object> result = new HashMap<>();
                            if(batchId == 4L){
                                // 专科
                                System.out.println("========" + Thread.currentThread().getName() + schoolVO.getSchoolId());
                                mallSchoolAccept = mallSchoolAcceptMapper.selectZhuankeAcceptBySchoolId(schoolVO.getSchoolId(), batchId, subjectType);
                                // 计算专科
                                if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                                    result = mallCountMethodService.zhuankegetAcceptRateForReport(mallSchoolAccept.getAcceptLowest(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
                                }else {
                                    result.put("acceptRate", BigDecimal.ZERO);
                                    result.put("rateType", -2);
                                }
                            }else{
                                // 本科
                                mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(schoolVO.getSchoolId(), batchId, subjectType);
                                // 计算
                                if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                                    result = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
                                }else {
                                    result.put("acceptRate", "0");
                                    result.put("rateType", -2);
                                }
                            }


                            schoolVO.setAcceptRate(new BigDecimal(result.get("acceptRate").toString()));
                            schoolVO.setShowAcceptRate(schoolVO.getAcceptRate() + "%");
                            schoolVO.setRateType((Integer)result.get("rateType"));

                            // 查询标签列表
                            if (StringUtils.isNotBlank(schoolVO.getTags())) {

                                List<String> list = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                                schoolVO.setTagList(list);
                            }
                            Integer rateType = schoolVO.getRateType();
                            if ( ObjectUtils.isNotEmpty(rateType) ){
                                if (rateType == 0){
                                    list0.add(schoolVO);
                                }else if (rateType == 1){
                                    list1.add(schoolVO);
                                }else if (rateType == 2){
                                    list2.add(schoolVO);
                                }else if (rateType == 3){
                                    list3.add(schoolVO);
                                }
                            }
                            countDownLatch.countDown();
                        }
                    }).start();
                }

                countDownLatch.await();
            }catch (Exception e){
                throw new ServiceException();
            }

            if (!list0.isEmpty()){
                list0.sort(Comparator.comparing(SchoolVO::getAcceptRate).reversed());
            }
            if (!list1.isEmpty()){

                list1.sort(Comparator.comparing(SchoolVO::getAcceptRate).reversed());
            }

            if (!list2.isEmpty()){

                Collections.sort(list2, (a,b)->{
                    return b.getAcceptRate().compareTo(a.getAcceptRate()) ;
                });

            }

            if (!list3.isEmpty()){
                Collections.sort(list3, (a,b)->{
                    if (a != null && b != null){
                        return a.getAcceptRate().compareTo(b.getAcceptRate()) ;
                    }
                    return 0;
                });
            }

            // 可冒险
            result0.put("rateType", 0);
            result0.put("num", list0.size());
            if (list0.size() <= 3){
                result0.put("list", list0);
            }else {
                result0.put("list", list0.subList(0,3));
            }

            // 搏一搏
            result1.put("rateType", 1);
            result1.put("num", list1.size());
            if (list1.size() <= 3){
                result1.put("list", list1);
            }else{
                result1.put("list", list1.subList(0, 3));
            }

            // 较稳妥
            result2.put("rateType", 2);
            result2.put("num", list2.size());
            if (list2.size() <= 3){
                result2.put("list", list2);
            }else{
                result2.put("list", list2.subList(0, 3));
            }

            // 可保底
            result3.put("rateType", 3);
            result3.put("num", list3.size());
            if (list3.size() <= 3){
                result3.put("list", list3);
            }else{
                result3.put("list", list3.subList(0, 3));
            }

            resultList.add(result0);
            resultList.add(result1);
            resultList.add(result2);
            resultList.add(result3);
            if (result0.size() == 0 && result1.size() == 1 && result2.size() == 2 && result3.size() == 3){
                resultList = Arrays.asList();
            }
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 根据录取概率分组标记查询学校列表
     * @param rateType 类型(0-可冒险,1-搏一搏,2-较稳妥,3-可保底)
     * @param id 用户id
     * @param batchId 批次id
     * @param cultureScore 文化分
     * @param majorScore 文化分
     * @param pageNum 页码
     * @param pageSize 每页个数
     * @return 结果
     */
    @Override
    public List<SchoolVO> matchSchoolListByType(Integer rateType,
                                                    Long id,
                                                    Long batchId,
                                                    Integer cultureScore,
                                                    Integer majorScore,
                                                    Integer pageNum,
                                                    Integer pageSize,
                                                    Integer subjectId) {

        // 查询录取率设定表
        //List<MallAcceptRateSetting> rateSettings = mallAcceptRateSettingMapper.selectRateSettingList();

        // 查询批次大学列表
        List<SchoolVO> schoolVOS = mallSchoolMapper.selectSchoolList(null, batchId, null, null, null, null, null,null);

        List<Map<String, Object>> resultList = new ArrayList<>();

        // 用户成绩查询
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);
        StringBuilder stringBuilder = new StringBuilder();
        if (null != subjectId ){
            stringBuilder.append(subjectId == 1? "0": "1");
        }else{
            stringBuilder.append(mallMemberUser.getSubjectType());
        }
        String subjectType = stringBuilder.toString();


        List<SchoolVO> list = new ArrayList<>();
        if (!schoolVOS.isEmpty()){
            // 学校录取率计算
            try {
                CountDownLatch countDownLatch = new CountDownLatch(schoolVOS.size());

                for (SchoolVO schoolVO : schoolVOS) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 查询学校最低专业录取分
                            Map<String, Object> result = new HashMap<>();
                            MallSchoolAccept mallSchoolAccept = new MallSchoolAccept();
                            if(batchId == 4L){
                                // 专科
                                mallSchoolAccept = mallSchoolAcceptMapper.selectZhuankeAcceptBySchoolId(schoolVO.getSchoolId(), batchId, subjectType);
                                // 计算专科
                                if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                                    result = mallCountMethodService.zhuankegetAcceptRateForReport(mallSchoolAccept.getAcceptLowest(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
                                }else {
                                    result.put("acceptRate", BigDecimal.ZERO);
                                    result.put("rateType", -2);
                                }
                            }else{
                                 mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(schoolVO.getSchoolId(), batchId, subjectType);
                                if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                                    result = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);

                                }else{
                                    result.put("acceptRate", 0);
                                    result.put("rateType", -2);
                                }
                            }



                            if (!result.isEmpty() && new BigDecimal(result.get("acceptRate").toString()).compareTo(BigDecimal.ZERO) > 0 ){
                                schoolVO.setAcceptRate(new BigDecimal(result.get("acceptRate").toString()));
                                schoolVO.setShowAcceptRate(schoolVO.getAcceptRate() + "%");
                                schoolVO.setRateType((Integer)result.get("rateType"));
                            }

                            if (StringUtils.isNotBlank(schoolVO.getTags())) {
                                // 查询标签列表
                                List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                                schoolVO.setTagList(tagList);
                            }
                            countDownLatch.countDown();
                        }
                    }).start();
                }

                countDownLatch.await();
            }catch (Exception e){
                throw new ServiceException();
            }

            // 选择类型
            list = schoolVOS.stream().filter(item -> item.getRateType()!=null && item.getRateType().equals(rateType)).collect(Collectors.toList());

            if (!list.isEmpty()){
                list.sort(Comparator.comparing(SchoolVO::getAcceptRate).reversed());
            }

        }
        return list;
    }

    /**
     * 升学规划- 我的目标
     * @param id 用户id
     * @param batchId 批次id
     * @param schoolName 学校名称
     * @param majorId 专业id
     * @return 结果
     */
    @Override
    public PageInfo<SchoolVO> enterPlanTargetList(Long id, Long batchId, String schoolName, Long majorId, Integer pageNum, Integer pageSize) {

        // 用户信息
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);

        List<SchoolVO> schoolList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(mallMemberUser.getCultureScore()) && ObjectUtils.isNotEmpty(mallMemberUser.getMajorScore())){
            String subjectType = mallMemberUser.getSubjectType();
            // 录取率设定信息
            //List<MallAcceptRateSetting> settingList = mallAcceptRateSettingMapper.selectRateSettingList();
            // 我的目标学校
            PageHelper.startPage(pageNum, pageSize);
            // 专业名称
            String twoClassName = "";
            if (majorId != null){
                MallMajorClass majorClass = mallMajorClassMapper.selectMallMajorClassByMajorId(majorId);
                twoClassName = majorClass.getMajorName();
            }

            schoolList = mallMemberTargetSchoolMapper.selectTargetSchoolListByUserId(id, batchId, schoolName, twoClassName, subjectType);

            if (!schoolList.isEmpty()){
                for (SchoolVO schoolVO : schoolList) {

                    // 目标学校状态
                    schoolVO.setTargetStatus(1);

                    // 查询标签列表
                    if (StringUtils.isNotBlank(schoolVO.getTags())) {
                        List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                        schoolVO.setTagList(tagList);
                    }

                    // 计算录取率
                    // 查询学校最低专业录取分
                    Map<String, Object> result = new HashMap<>();
                    MallSchoolAccept mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(schoolVO.getSchoolId(), batchId, subjectType);
                    if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                        result = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), mallMemberUser.getCultureScore(), mallMemberUser.getMajorScore());
                    }else{
                        result.put("acceptRate", new BigDecimal("1"));
                        result.put("rateType", -2);
                    }
                    if (!result.isEmpty() && new BigDecimal(result.get("acceptRate").toString()).compareTo(BigDecimal.ZERO) > 0 ){
                        schoolVO.setAcceptRate(new BigDecimal(result.get("acceptRate").toString()));
                        schoolVO.setShowAcceptRate(schoolVO.getAcceptRate() + "%");
                        schoolVO.setRateType((Integer)result.get("rateType"));
                    }else{//录取率为0
                        schoolVO.setAcceptRate(BigDecimal.ZERO);
                        schoolVO.setShowAcceptRate(schoolVO.getAcceptRate().toPlainString() + "%");
                        schoolVO.setRateType((Integer)result.get("rateType"));
                    }
                    if (schoolVO.getRateType() == 2 || schoolVO.getRateType() == 3){
                        // 较安全
                        schoolVO.setWarnStatus(1);
                    }else{
                        schoolVO.setWarnStatus(0);
                    }
                }

                // 按照录取率从低到高
                schoolList.sort(Comparator.comparing(SchoolVO::getAcceptRate));
            }
        }

        return new PageInfo<>(schoolList);
    }

    /**
     * 升学规划分类查询学校列表
     * @param rateType 类型
     * @param id 用户id
     * @param batchId 批次id
     * @param pageNum 页码
     * @param pageSize 每页个数
     * @return 结果
     */
    @Override
    public AjaxResult enterPlanSchoolListByType(Integer rateType, Long id, Long batchId, String schoolName,  Long majorId, Integer pageNum, Integer pageSize) {

        // 选择类型
        List<SchoolVO> collect = new ArrayList<>();


        List<SchoolVO> list = new ArrayList<>();
        // 查询用户分
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(id);

        if (ObjectUtils.isEmpty(mallMemberUser)){
            return AjaxResult.error("用户信息异常");
        }

        if(ObjectUtils.isNotEmpty(mallMemberUser.getCultureScore()) && ObjectUtils.isNotEmpty(mallMemberUser.getMajorScore())){
            // 文化分和专业分
            Integer cultureScore = mallMemberUser.getCultureScore();
            Integer majorScore = mallMemberUser.getMajorScore();
            String subjectType = mallMemberUser.getSubjectType();



            // 查询录取控制线
            List<MallExamData> lineList = mallExamDataMapper.selectLineList();

            // 查询二级分类
            String twoClassName = "";
            if (majorId != null){
                MallMajorClass majorClass = mallMajorClassMapper.selectMallMajorClassByMajorId(majorId);
                twoClassName = majorClass.getMajorName();
            }

            // 查询批次大学列表
            List<SchoolVO> schoolVOS = mallSchoolMapper.selectSchoolList(schoolName, batchId, null, null, null, null, twoClassName, subjectType);

            if (!schoolVOS.isEmpty()){
                try{
                    CountDownLatch countDownLatch = new CountDownLatch(schoolVOS.size());

                    // 学校录取率计算
                    for (SchoolVO schoolVO : schoolVOS) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Map<String, Object> result = new HashMap<>();
                                MallSchoolAccept mallSchoolAccept = new MallSchoolAccept();
                                // 学校录取专业最低分
                                if (batchId == 4L){
                                    // 专科
                                    mallSchoolAccept = mallSchoolAcceptMapper.selectZhuankeAcceptBySchoolId(schoolVO.getSchoolId(), batchId, subjectType);
                                    // 计算专科
                                    if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                                        result = mallCountMethodService.zhuankegetAcceptRateForReport(mallSchoolAccept.getAcceptLowest(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
                                    }else {
                                        result.put("acceptRate", BigDecimal.ZERO);
                                        result.put("rateType", -2);
                                    }
                                }else{
                                    // 本科
                                     mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(schoolVO.getSchoolId(), batchId, subjectType);
                                    if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                                        result = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference() != null?mallSchoolAccept.getReference() : new BigDecimal("500") ,  mallSchoolAccept.getAcceptRuleId(), mallMemberUser.getCultureScore(), mallMemberUser.getMajorScore());
                                    }else{
                                        result.put("acceptRate", BigDecimal.ZERO);
                                        result.put("rateType", -2);
                                    }
                                }

                                schoolVO.setAcceptRate(new BigDecimal(result.get("acceptRate").toString()));
                                schoolVO.setShowAcceptRate(schoolVO.getAcceptRate() + "%");
                                schoolVO.setRateType((Integer)result.get("rateType"));

                                if (StringUtils.isNotBlank(schoolVO.getTags())) {
                                    // 查询标签列表
                                    List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                                    schoolVO.setTagList(tagList);
                                }
                                countDownLatch.countDown();
                            }
                        }).start();
                    }
                    countDownLatch.await();

                }catch (Exception e){
                    e.printStackTrace();
                    throw new ServiceException();
                }

                if(rateType == -1){
                    collect = schoolVOS;
                }else{
                    collect = schoolVOS.stream().filter(item -> item.getRateType()!=null && item.getRateType().equals(rateType)).collect(Collectors.toList());

                }

                // 排序并处理分页
                if (!collect.isEmpty()){
                    // 排序

                    if (rateType == 3){
                        collect.sort(Comparator.comparing(SchoolVO:: getAcceptRate));

                    }else if (rateType == -1){
                        collect.sort(Comparator.comparing(SchoolVO:: getSchoolId));

                    }else{
                        collect.sort(Comparator.comparing(SchoolVO:: getAcceptRate).reversed());
                    }

                }

            }
        }
        //java8 stream实现list分页
        List<SchoolVO> pageList = collect.stream().sorted().skip((long) (pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        PageInfo<SchoolVO> pageInfo = new PageInfo<SchoolVO>(pageList);
        //获取PageInfo其他参数
        pageInfo.setTotal(collect.size());

        int endRow = pageInfo.getEndRow() == 0 ? 0 : (int)((pageNum - 1) * pageSize + pageInfo.getEndRow() + 1);
        pageInfo.setEndRow(endRow);
        boolean hasNextPage = collect.size() <= pageSize * pageNum ? false : true;
        pageInfo.setHasNextPage(hasNextPage);
        boolean hasPreviousPage = pageNum == 1 ? false : true;
        pageInfo.setHasPreviousPage(hasPreviousPage);
        pageInfo.setIsFirstPage(!hasPreviousPage);
        boolean isLastPage = (collect.size() > pageSize * (pageNum - 1) && collect.size() <= pageSize * pageNum) ? true : false;
        pageInfo.setIsLastPage(isLastPage);
        int pages = collect.size() % pageSize == 0 ? collect.size() / pageSize : (collect.size() / pageSize) + 1;
        pageInfo.setNavigateLastPage(pages);
        int[] navigatePageNums = new int[pages];
        for (int i = 1; i < pages; i++) {
            navigatePageNums[i - 1] = i;
        }
        pageInfo.setNavigatepageNums(navigatePageNums);
        int nextPage = pageNum < pages ? pageNum + 1 : 0;
        pageInfo.setNextPage(nextPage);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPages(pages);
        pageInfo.setPrePage(pageNum - 1);
        pageInfo.setSize(pageInfo.getList().size());
        int starRow = collect.size() < pageSize * pageNum ? 1 + pageSize * (pageNum - 1) : 0;
        pageInfo.setStartRow(starRow);
        return AjaxResult.success(pageInfo);
    }
    /**志愿自主选择 筛选学校*/
    @Override
    public List<Long> getAstrictSchoolIds(CheckingOutParamBo bo) {
        return mallSchoolMapper.selectSchoolByParams(bo);
    }

    /**志愿自主选择 获取学校信息*/
    @Override
    public List<SchoolMajorVO> schoolListInfoForReport(List<Long> sIds) {
        return mallSchoolMapper.schoolListInfoForReport(sIds);
    }

    /**
     * 保研率学校列表
     * @param schoolName 学校名
     * @param batchId 批次id
     * @param configLevelId 层次id
     * @param configTypeId 办学类型id
     * @param provinceId 省份
     * @param cityId 城市
     * @param pageNum 页码
     * @param pageSize 每页个数
     * @return 结果
     */
    @Override
    public PageInfo<SchoolVO> selectSchoolListForMaster(String schoolName, Long batchId, Long configLevelId, Long configTypeId, Long provinceId, Long cityId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SchoolVO> schoolList = mallSchoolMapper.selectSchoolListForMaster(schoolName, batchId, configLevelId, configTypeId, provinceId, cityId);

        if (!schoolList.isEmpty()){
            for (SchoolVO schoolVO : schoolList) {
                if (StringUtils.isNotBlank(schoolVO.getTags())) {
                    // 查询标签列表
                    List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                    schoolVO.setTagList(tagList);
                }

                // 查询保研率
                List<MasterRateVO> masterRateVOS = mallSchoolMasterRecordMapper.selectMasterRecordListBySchoolId(schoolVO.getSchoolId());
                schoolVO.setMasterRateList(masterRateVOS);
            }
        }

        return new PageInfo<>(schoolList);
    }

    /**
     * 专业开设学校
     * @param schoolName 学校名称
     * @param batchId 批次id
     * @param configLevelId 层次id
     * @param configTypeId 类型id
     * @param provinceId 省份id
     * @param cityId 城市id
     * @param type  类型(0-强校,1-硕士点)
     * @return 结果
     */
    @Override
    public PageInfo<SchoolVO> selectSchoolListByMajorId(String schoolName,
                                                        Long batchId,
                                                        Long configLevelId,
                                                        Long configTypeId,
                                                        Long provinceId,
                                                        Long cityId,
                                                        Integer type,
                                                        Long majorId,
                                                        Integer pageNum,
                                                        Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SchoolVO> list = mallSchoolMapper.selectSchoolListByMajorId(schoolName, batchId, configLevelId, configTypeId, provinceId, cityId, type, majorId);
        if (!list.isEmpty()){
            for (SchoolVO schoolVO : list) {
                if (StringUtils.isNotBlank(schoolVO.getTags())) {
                    // 查询标签列表
                    List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolVO.getTags());
                    schoolVO.setTagList(tagList);
                }
            }
        }

        return new PageInfo<>(list);
    }

    /**
     * 修改学校重复数据
     * @param schoolId 保留的学校ID
     * @param deleteSchoolId 删除的学校ID
     * @return 结果
     */
    @Override
    public AjaxResult updateSchoolDuplicateData(Long schoolId, Long deleteSchoolId, String schoolName) {
        mallSchoolMapper.updateMallAcceptPlanDuplicateData(schoolId, deleteSchoolId);
        mallSchoolMapper.updateMallSchoolAcceptDuplicateData(schoolId, deleteSchoolId);
        mallSchoolMapper.updateMallSchoolAcceptRecordDuplicateData(schoolId, deleteSchoolId);

        mallSchoolMapper.updateMallSchoolBatchLinkDuplicateData(schoolId, deleteSchoolId);
        mallSchoolMapper.updateMallLinkMajorSchoolDuplicateData(schoolId, deleteSchoolId, schoolName);

        mallSchoolMapper.updateMallSchoolSceneryDuplicateData(schoolId, deleteSchoolId);
        mallSchoolMapper.updateMallSchoolIntroduceDuplicateData(schoolId, deleteSchoolId);

        mallSchoolMapper.deleteMallSchoolBySchoolId(deleteSchoolId);
        return AjaxResult.success();
    }

    @Override
    public List<MallSchool> selectMallSchoolNumberRepetitionList() {
        return mallSchoolMapper.selectMallSchoolNumberRepetitionList();
    }

    @Override
    public List<MallSchool> selectMallSchoolNumberList(String schoolNumber) {
        return mallSchoolMapper.selectMallSchoolNumberList(schoolNumber);
    }

    /**
     * 新增系统学校用户
     *
     * @param mallSchool 学校
     * @return 结果
     */
    @Override
    public AjaxResult submitSchoolUser(MallSchool mallSchool) {
        MallSchool school = mallSchoolMapper.selectMallSchoolBySchoolId(mallSchool.getSchoolId());

        String account = mallSchool.getSysUserName();// 账号
        String password = mallSchool.getSysUserPassword();// 密码

        MallSchool updateSchool = new MallSchool();
        updateSchool.setSchoolId(mallSchool.getSchoolId());
        updateSchool.setSysUserName(account);
        updateSchool.setSysUserPassword(password);
        updateSchool.setSysUserStatus(mallSchool.getSysUserStatus());


        if (school.getSysUserId() == 0 || school.getSysUserId() == null) {
            MallSchool sysUserName = mallSchoolMapper.selectSchoolBySysUserName(mallSchool.getSysUserName());
            // 新增
            if (sysUserName != null) {
                return AjaxResult.error("账号已存在");
            }

            // 新增系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName(account);
            sysUser.setNickName(school.getSchoolName());
            sysUser.setStatus(mallSchool.getSysUserStatus().toString());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUserMapper.insertUser(sysUser);

            // 新增用户与角色管理
            List<SysUserRole> userRoleList = new ArrayList<>();
            SysUserRole ur = new SysUserRole();
            ur.setUserId(sysUser.getUserId());
            ur.setRoleId(103L);
            userRoleList.add(ur);
            sysUserRoleMapper.batchUserRole(userRoleList);

            updateSchool.setSysUserId(sysUser.getUserId());

        } else {
            MallSchool sysUserName = mallSchoolMapper.selectSchoolBySysUserName(mallSchool.getSysUserName());
            // 修改
            if (sysUserName != null && !sysUserName.getSchoolId().equals(mallSchool.getSchoolId())) {
                return AjaxResult.error("账号已存在");
            }

            // 修改系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserId(school.getSysUserId());
            sysUser.setUserName(account);
            sysUser.setNickName(school.getSchoolName());
            sysUser.setStatus(mallSchool.getSysUserStatus().toString());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUserMapper.updateUser(sysUser);
        }

        if (StringUtils.isBlank(school.getQrCode())) {
            String qrCode = "";
            // 小程序码
            Long schoolId = mallSchool.getSchoolId();
            String key =  schoolId + ".png";
            qrCode = weiXinUtils.getSchoolQRCode(schoolId, key);
            updateSchool.setQrCode(qrCode);
        }

        mallSchoolMapper.updateSchoolUser(updateSchool);
        return AjaxResult.success();
    }

    /**
     * 查询学校
     *
     * @param sysUserId 系统用户ID
     * @return 学校
     */
    @Override
    public MallSchool selectMallSchoolBySysUserId(Long sysUserId) {
        return mallSchoolMapper.selectMallSchoolBySysUserId(sysUserId);
    }
}
