package com.ruoyi.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.Bo.CheckingOutParamBo;
import com.ruoyi.mall.domain.Vo.*;
import com.ruoyi.mall.mapper.*;
import com.ruoyi.mall.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.scheduling.annotation.Async;
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.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@Service
public class CheckingOutServiceImpl implements CheckingOutService {
    @Resource
    private MallAcceptRateSettingMapper mallAcceptRateSettingMapper;
    @Resource
    private MallSchoolTagMapper mallSchoolTagMapper;
    @Resource
    private MallCountMethodServiceImpl mallCountMethodService;
    @Resource
    private IMallSchoolService mallSchoolService;
    @Resource
    private IMallLinkMajorSchoolService mallLinkMajorSchoolService;
    @Resource
    private IMallAcceptPlanService mallAcceptPlanService;
    @Resource
    private IReportDraftService reportDraftService;
    @Resource
    private IReportIntelligenceService reportIntelligenceService;
    @Resource
    private MallBatchDetailMapper mallBatchDetailMapper;
    @Resource
    private MallSchoolAcceptMapper mallSchoolAcceptMapper;
    @Resource
    private MallLinkMajorSchoolMapper linkMajorSchoolMapper;
    @Resource
    private MallMemberRateMapper rateMapper;
    @Resource
    private MallSchoolMapper schoolMapper;
    @Resource
    private MallMemberRateSchoolMapper rateSchoolMapper;



    /**
     * 已更新录取率数据
     * @param bo
     * @param mallMemberUser
     * @return
     */
    @Override
    public List<SchoolMajorVO> schoolOriginal2(CheckingOutParamBo bo, MallMemberUser mallMemberUser) {

        String subjectType = mallMemberUser.getSubjectType();

        Integer rateFlag = mallMemberUser.getRateFlag();
        bo.setRateFlag(rateFlag);  // 是否更新录取率数据完毕

        if(null != subjectType){
            bo.setSubjectType(subjectType);
        }
        PageHelper.startPage(bo.getPageNum(), bo.getPageSize());
        List<SchoolMajorVO> list = schoolMapper.selectRateSchoolList(bo); // 查询学校
        if (!list.isEmpty()){
            //查询 草稿表
            List<ReportDraft> drafts = new ArrayList<>();
            if(null != bo.getReportId()){
                //查询草稿表里 关于reportId 的 草稿志愿 和 reportId本就有的志愿
                ReportDraft param = new ReportDraft();
                param.setReportId(bo.getReportId());
                drafts = reportDraftService.selectReportDraftList(param);
                ReportIntelligence reportIntelligence = new ReportIntelligence();
                reportIntelligence.setReportId(bo.getReportId());
                List<ReportIntelligence> reportItemVos = reportIntelligenceService.selectReportIntelligenceList(reportIntelligence);
                List<ReportDraft> collect = reportItemVos.stream().map(s -> BeanUtil.toBean(s, ReportDraft.class)).collect(Collectors.toList());
                drafts.addAll(collect);
            }
            else{
                //查询 uid batchid 的草稿志愿列表
                ReportDraft param = new ReportDraft();
                param.setUserId(bo.getMemberId());
                param.setBatchId(bo.getBatchId());
                drafts = reportDraftService.selectReportDraftList(param);
            }
            List<ReportDraft> drafts2 = drafts;
            CountDownLatch countDownLatch = new CountDownLatch(list.size());
                try{
                    for (SchoolMajorVO schoolMajorVO : list) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                //填充学校信息 tags
                                if (StringUtils.isNotBlank(schoolMajorVO.getTags())) {
                                    // 查询标签列表
                                    List<String> tagList = mallSchoolTagMapper.selectTagByTagId(schoolMajorVO.getTags());
                                    schoolMajorVO.setTagList(tagList);
                                }
                                // 查询学校下专业
                                List<MajorItemVo> majorItemVos = linkMajorSchoolMapper.selectMajorItemList(schoolMajorVO.getSchoolId(), bo.getBatchId(), subjectType, bo.getMajorIds(), mallMemberUser.getId(), bo.getNewAcceptType());
                                if (!majorItemVos.isEmpty()) {
                                    CountDownLatch countDownLatch2 = new CountDownLatch(majorItemVos.size());
                                    try {
                                        for (MajorItemVo majorItemVo : majorItemVos) {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                //  前两年招生人数 学费
                                                List<MajorItemVo> vos = mallAcceptPlanService.majorList(majorItemVo);
                                                if (null != vos && vos.size() > 0) {
                                                    int sort = 1;
                                                    for (MajorItemVo vo : vos) {
                                                        if (sort == 1) {
                                                            majorItemVo.setaNum(vo.getaNum());
                                                            majorItemVo.setSchoolPrice(vo.getSchoolPrice());
                                                            sort++;
                                                        } else if (sort == 2) {
                                                            majorItemVo.setbNum(vo.getaNum());
                                                        }
                                                    }
                                                }
                                                //查验添加状态
                                                if (null != drafts2 && drafts2.size() > 0) {
                                                    List<ReportDraft> collect = drafts2.stream().filter(t -> t.getBatchId().equals(majorItemVo.getBatchId()) && t.getSchoolId().equals(majorItemVo.getSchoolId()) && t.getMajorId() != null && t.getMajorId().equals(majorItemVo.getMajorId())).collect(Collectors.toList());
                                                    if (!collect.isEmpty()) {//0 未加入 ， 1已加入
                                                        majorItemVo.setTargetStatus(1);
                                                    } else {
                                                        majorItemVo.setTargetStatus(0);
                                                    }
                                                }
                                                countDownLatch2.countDown();
                                            }
                                        }).start();
                                    }
                                        countDownLatch2.await();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    schoolMajorVO.setMajorItemVos(majorItemVos);
                                }
                                countDownLatch.countDown();
                            }
                        }).start();
                    }
                    countDownLatch.await();
                }catch (Exception e){
                    e.printStackTrace();
                }

        }
        System.out.println(list);
        return list;
    }

    /*获取初始列表 带状态*/
        @Override
        public List<SchoolMajorVO> schoolOriginal( CheckingOutParamBo bo, MallMemberUser mallMemberUser) {
            String newYear = linkMajorSchoolMapper.selectMaxYear();
            Integer majorScore = mallMemberUser.getMajorScore();
            Integer cultureScore = mallMemberUser.getCultureScore();
            String subjectType = mallMemberUser.getSubjectType();
            Long userId = mallMemberUser.getId();
            Integer rateFlag = mallMemberUser.getRateFlag();
            bo.setRateFlag(rateFlag);  // 是否更新录取率数据完毕

            if(null != subjectType){
                bo.setSubjectType(subjectType);
            }
            bo.setPageNum(null);
            bo.setPageSize(null);
            //查询 草稿表
            List<ReportDraft> drafts = new ArrayList<>();
            if(null != bo.getReportId()){
                //查询草稿表里 关于reportId 的 草稿志愿 和 reportId本就有的志愿
                ReportDraft param = new ReportDraft();
                param.setReportId(bo.getReportId());
                drafts = reportDraftService.selectReportDraftList(param);
                ReportIntelligence reportIntelligence = new ReportIntelligence();
                reportIntelligence.setReportId(bo.getReportId());
                List<ReportIntelligence> reportItemVos = reportIntelligenceService.selectReportIntelligenceList(reportIntelligence);
                List<ReportDraft> collect = reportItemVos.stream().map(s -> BeanUtil.toBean(s, ReportDraft.class)).collect(Collectors.toList());
                drafts.addAll(collect);
            }
            else{
                //查询 uid batchid 的草稿志愿列表
                ReportDraft param = new ReportDraft();
                param.setUserId(bo.getMemberId());
                param.setBatchId(bo.getBatchId());
                drafts = reportDraftService.selectReportDraftList(param);
            }

            //在限制学校的基础上 限制专业 获取(学校id,专业id) 结果a

            bo.setNewYear(newYear);

            List<MajorItemVo> a = mallLinkMajorSchoolService.astrictMajorItemList(bo);
            if(null == a){
                return null;
            }
            //是否新招 获取(学校id,专业id) 结果b
            /* 新招类型 单选 不传不限 所有新招1 新招院校2 新招专业3*/
            //if(StringUtils.isNotBlank(bo.getNewAcceptType())){
            //    //
            //    List<MajorItemVo> b = mallAcceptPlanService.newAcceptList(subjectType,bo.getNewAcceptType(), bo.getBatchId());
            //    ////如果选择新招 结果a和结果b求交集 赋值给a //a=(a n b)
            //    if(null == b){
            //        return null;
            //    }
            //    a = a.stream().filter(itemInfo ->
            //            b.stream().anyMatch(item -> item.getBatchId().equals(itemInfo.getBatchId())
            //                                && item.getLinkId().equals(itemInfo.getLinkId())
            //                                && item.getSchoolId().equals(itemInfo.getSchoolId()))
            //
            //    ).collect(Collectors.toList());
            //}

            //最终返回结果
            List<SchoolMajorVO> result = new ArrayList<>();

            //去重学校id
            List<Long> sIds = a.stream().map(MajorItemVo::getSchoolId).distinct().collect(Collectors.toList());
            List<SchoolMajorVO> finalResult = new ArrayList<>();
            List<ReportDraft> finalDrafts = drafts;
            List<MajorItemVo> finalA = a;
            if(!sIds.isEmpty()) {
                //充学校信息 学校名 院校层次 省 市 综合 公办 教育部 硕士点 博士点 硕士点研究方向
                List<SchoolMajorVO> schools = mallSchoolService.schoolListInfoForReport(sIds);
                try {
                    CountDownLatch countDownLatch = new CountDownLatch(schools.size());
                    for (SchoolMajorVO s : schools) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                fillSchoolMajorInfo(finalResult,s,subjectType,cultureScore,majorScore,bo, finalA, finalDrafts, rateFlag);
                                countDownLatch.countDown();
                            }
                        }).start();
                    }
                    countDownLatch.await();
                    result = finalResult;
                }catch (Exception e){
                    throw new ServiceException();
                }
            }

            // 限制分类
            if( !"null".equals(String.valueOf(bo.getRateType())) && bo.getRateType() >= 0){
                result.removeIf(s -> s.getRateType() == null);
                result = result.stream().filter(s -> s.getRateType().equals(bo.getRateType())).collect(Collectors.toList());
            }

            if (result.size() > 0) {
                result.removeIf(majorVO -> majorVO.getShowAcceptRate() == null );
            }

            //限制排序
            //不传默认desc 和 传desc
            if(StringUtils.isNotBlank(bo.getOrderByType()) && bo.getOrderByType().equals("desc") || StringUtils.isBlank(bo.getOrderByType()) ){
                compareListForSchoolMajorVo(result,"desc");
            }
            else if(StringUtils.isNotBlank(bo.getOrderByType()) && bo.getOrderByType().equals("asc")){
                compareListForSchoolMajorVo(result,"asc");
            }

            return result;
        }/*获取初始列表 不带是否添加志愿状态的 schoolOriginal end*/

        /** 异步填充学校专业详情*/
        public void fillSchoolMajorInfo(List<SchoolMajorVO> result,SchoolMajorVO s,String subjectType,
                                        Integer cultureScore,Integer majorScore,CheckingOutParamBo bo,
                                        List<MajorItemVo> a,List<ReportDraft> drafts, Integer rateFlag){
            //填充学校信息 tags
            if (StringUtils.isNotBlank(s.getTags())) {
                // 查询标签列表
                List<String> list = mallSchoolTagMapper.selectTagByTagId(s.getTags());
                s.setTagList(list);
            }
            //填充学校信息 录取ruleId 最低分 计算录取率
            // 学校录取率
            // 查询学校最低专业录取分
            if (rateFlag != null && rateFlag == 1){
                    // 查询学校最低录取率
                    MallMemberRate mallMemberRate = rateMapper.selectMinRateBySchoolId(s.getSchoolId(), bo.getBatchId(), subjectType);
                    if (null != mallMemberRate){
                        s.setAcceptRate(mallMemberRate.getAcceptRate());
                        s.setShowAcceptRate(mallMemberRate.getShowAcceptRate());
                        s.setRateType(mallMemberRate.getRateType());
                    }
            }else{
                // 未完成更新
                Map<String, Object> r = new HashMap<>();
                MallSchoolAccept mallSchoolAccept = new MallSchoolAccept();
                if (bo.getBatchId() == 4L){
                    // 专科
                    mallSchoolAccept = mallSchoolAcceptMapper.selectZhuankeAcceptBySchoolId(s.getSchoolId(), bo.getBatchId(), subjectType);

                    if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                        r = mallCountMethodService.zhuankegetAcceptRateForReport(mallSchoolAccept.getAcceptLowest(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
                    }else{
                        r.put("acceptRate", 0);
                        r.put("rateType", -2);
                    }
                }else{
                    // 本科
                    mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(s.getSchoolId(), bo.getBatchId(), subjectType);

                    if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                        r = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
                    }else{
                        r.put("acceptRate", 0);
                        r.put("rateType", -2);
                    }
                }

                if (!r.isEmpty() ){
                    s.setAcceptRate(new BigDecimal(r.get("acceptRate").toString()));
                    s.setShowAcceptRate(s.getAcceptRate() + "%");
                    s.setRateType((Integer)r.get("rateType"));
                }
            }

            //将对应的查询结果加入
            List<MajorItemVo> smMList = a.stream().filter(item -> item.getSchoolId().equals( s.getSchoolId())).collect(Collectors.toList());
            if(  smMList.size()>0) {

                s.setMajorItemVos(smMList);
                CountDownLatch countDownLatch11 = new CountDownLatch(smMList.size());
                for (MajorItemVo majorItemVo : smMList) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            computFillMajorInfo(majorItemVo,subjectType,cultureScore,majorScore,drafts, rateFlag);
                            countDownLatch11.countDown();
                        }
                    }).start();

                }
                try {
                    countDownLatch11.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                result.add(s);
            }
        }

        public void computFillMajorInfo(MajorItemVo majorItemVo,String subjectType,
                                        Integer cultureScore,Integer majorScore,
                                        List<ReportDraft> drafts, Integer rateFlag){
            majorItemVo.setSubjectType(subjectType);
            //  前两年招生人数 学费
            List<MajorItemVo> vos = mallAcceptPlanService.majorList(majorItemVo);
            if (null != vos && vos.size() > 0) {
                int sort = 1;
                for (MajorItemVo vo : vos) {
                    if (sort == 1) {
                        majorItemVo.setaNum(vo.getaNum());
                        majorItemVo.setSchoolPrice(vo.getSchoolPrice());
                        sort++;
                    } else if (sort == 2) {
                        majorItemVo.setbNum(vo.getaNum());
                    }
                }
            }

            // 计算录取率
            // 专业录取率
            if (!(rateFlag != null && rateFlag == 1)){
                if (majorItemVo.getBatchId() == 4L){
                    if (null != majorItemVo.getLowestScore()){
                        Map<String, Object>  rate = mallCountMethodService.zhuankegetAcceptRateForReport(majorItemVo.getLowestScore(),  majorItemVo.getAcceptRuleId(), cultureScore, majorScore);
                        if (!rate.isEmpty()){
                            majorItemVo.setAcceptRate(new BigDecimal(rate.get("acceptRate").toString()));
                            majorItemVo.setShowAcceptRate(majorItemVo.getAcceptRate() + "%");
                            majorItemVo.setRateType((Integer) rate.get("rateType"));
                        }
                    }else{
                        majorItemVo.setAcceptRate(new BigDecimal(0));

                    }
                }else{
                    // 本科
                    if (null != majorItemVo.getAcceptRuleId() && null != majorItemVo.getReference()) {

                        Map<String, Object> rate = mallCountMethodService.getAcceptRateForReport(majorItemVo.getReference(), majorItemVo.getAcceptRuleId(),  cultureScore, majorScore);
                        if (!rate.isEmpty()) {
                            majorItemVo.setAcceptRate(new BigDecimal(rate.get("acceptRate").toString()));
                            majorItemVo.setShowAcceptRate(majorItemVo.getAcceptRate() + "%");
                            majorItemVo.setRateType((Integer) rate.get("rateType"));
                        }
                    } else {
                        majorItemVo.setAcceptRate(new BigDecimal(0));
                    }
                }
            }



            Boolean flag = false;
            //查验添加状态
            if (null != drafts && drafts.size() > 0) {
                flag = drafts.stream().filter(t -> t.getBatchId().equals(majorItemVo.getBatchId()) && t.getSchoolId().equals(majorItemVo.getSchoolId()) && t.getMajorId().equals(majorItemVo.getMajorId())).findAny().isPresent();
            }
            if (flag) {//0 未加入 ， 1已加入
                majorItemVo.setTargetStatus(1);
            } else {
                majorItemVo.setTargetStatus(0);
            }
        }

        /** 排序*/
        private void compareListForSchoolMajorVo(List<SchoolMajorVO> list,String type){
            //排序
            //先排序学校
            Collections.sort(list,new Comparator<SchoolMajorVO>() {
                public int compare(SchoolMajorVO firstMapEntry, SchoolMajorVO secondMapEntry) {
                    BigDecimal   tag1=(BigDecimal) firstMapEntry.getAcceptRate();
                    BigDecimal   tag2=(BigDecimal) secondMapEntry.getAcceptRate();

                    //两者相等 自反性
                    if (tag1 == null && tag2 == null) {
                        return 0;
                    }
                    if (tag1 == null) {
                        return -1;
                    }
                    if (tag2 == null) {
                        return 1;
                    }
                    if(tag1.compareTo(tag2)==0){
                        return 0;
                    }else{
                        if(type.equals("desc")){
                            return  (tag1.compareTo(tag2)==1 ?  -1: 1);
                        }else{
                            return  (tag1.compareTo(tag2)==1 ?  1: -1);
                        }
                    }
                }
            });
            //再排序专业
            for (SchoolMajorVO schoolMajorVO : list) {
                List<MajorItemVo> ms = schoolMajorVO.getMajorItemVos();
                Collections.sort(ms,new Comparator<MajorItemVo>() {
                    public int compare(MajorItemVo firstMapEntry, MajorItemVo secondMapEntry) {
                        BigDecimal   tag1=(BigDecimal) firstMapEntry.getAcceptRate();
                        BigDecimal   tag2=(BigDecimal) secondMapEntry.getAcceptRate();

                        //两者相等 自反性
                        if (tag1 == null && tag2 == null) {
                            return 0;
                        }
                        if (tag1 == null) {
                            return -1;
                        }
                        if (tag2 == null) {
                            return 1;
                        }
                        if(tag1.compareTo(tag2)==0){
                            return 0;
                        }else{
                            if(type.equals("desc")){
                                return  (tag1.compareTo(tag2)==1 ?  -1: 1);
                            }else{
                                return  (tag1.compareTo(tag2)==1 ?  1: -1);
                            }
                        }
                    }
                });
            }

        }/*排序end*/

    /**
     * 学校数量分类数字
     * @param bo
     * @param mallMemberUser
     * @return
     */
    @Override
    public RateTypeSchoolMajorVo tagNum2(CheckingOutParamBo bo, MallMemberUser mallMemberUser) {
        // 查询学校数量
        bo.setSubjectType(mallMemberUser.getSubjectType());
        return rateSchoolMapper.selectCounts(bo);
    }

    /** 标签数*/
        @Override
        public RateTypeSchoolMajorVo tagNum(CheckingOutParamBo bo, MallMemberUser mallMemberUser) {
            RateTypeSchoolMajorVo rateTypeData = new RateTypeSchoolMajorVo();
            Integer majorScore = mallMemberUser.getMajorScore();
            Integer cultureScore = mallMemberUser.getCultureScore();
            String subjectType = mallMemberUser.getSubjectType();
            if(null != subjectType){
                bo.setSubjectType(subjectType);
            }
            bo.setPageNum(null);
            bo.setPageSize(null);

            String newYear = linkMajorSchoolMapper.selectMaxYear();

            if (bo.getBatchId() == 4L){
                bo.setNewYear(newYear);
            }else{
                bo.setNewYear(newYear);
            }
            //在限制学校的基础上 限制专业 获取(学校id,专业id) 结果a
            List<MajorItemVo> a = mallLinkMajorSchoolService.astrictMajorItemList(bo);
            //是否新招 获取(学校id,专业id) 结果b
            /* 新招类型 单选 不传不限 所有新招1 新招院校2 新招专业3*/
            if(StringUtils.isNotBlank(bo.getNewAcceptType())){
                //
                List<MajorItemVo> b = mallAcceptPlanService.newAcceptList(subjectType, bo.getNewAcceptType(), bo.getBatchId());
                ////如果选择新招 结果a和结果b求交集 赋值给a //a=(a n b)
                a = a.stream().filter(itemInfo ->
                        b.stream().map(item -> item.getBatchId()).collect(Collectors.toList()).contains(itemInfo.getBatchId())
                                &&
                                b.stream().map(item -> item.getSchoolId()).collect(Collectors.toList()).contains(itemInfo.getSchoolId())
                                &&
                                b.stream().map(item -> item.getMajorId()).collect(Collectors.toList()).contains(itemInfo.getMajorId())

                ).collect(Collectors.toList());
            }
            //去重学校id
            List<Long> sIds = a.stream().map(MajorItemVo::getSchoolId).distinct().collect(Collectors.toList());
            if(null != sIds && sIds.size()>0) {
                //充学校信息 学校名 院校层次 省 市 综合 公办 教育部 硕士点 博士点 硕士点研究方向
                List<SchoolMajorVO> schools = mallSchoolService.schoolListInfoForReport(sIds);
                try{
                    CountDownLatch countDownLatch = new CountDownLatch(schools.size());
                    for (SchoolMajorVO s : schools) {
                        //不需要填充学校信息 tags
                        //填充学校信息 录取ruleId 最低分 计算录取率
                        // 学校录取率

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                computSchool(subjectType,s,bo,cultureScore,majorScore,rateTypeData);
                                countDownLatch.countDown();
                            }
                        }).start();
                    }
                    countDownLatch.await();
                }catch (Exception e){
                    throw new ServiceException();
                }

            }
            return rateTypeData;
        }/* 标签数end*/


    /**获取分类小标数*/
    @Override
    public CheckOutTagVo num(List<ReportIntelligenceVo> items,MallMemberUser user,Long batchId) {
        CheckOutTagVo result = new CheckOutTagVo();

        //计算每个志愿中学校所属类 再根据所属类 计算所属类小标
        //items去重 获取学校id列表
        List<Long> sIds = items.stream().map(ReportIntelligenceVo::getSchoolId).distinct().collect(Collectors.toList());
        if(null != sIds && sIds.size()>0) {
            //充学校信息 学校名 院校层次 省 市 综合 公办 教育部 硕士点 博士点 硕士点研究方向
            List<SchoolMajorVO> schools = mallSchoolService.schoolListInfoForReport(sIds);
            for (SchoolMajorVO s : schools) {
                //不需要填充学校信息 tags
                //填充学校信息 录取ruleId 最低分 计算录取率
                // 学校录取专业最低分 学校录取率
                MallSchoolAccept mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(s.getSchoolId(), batchId, user.getSubjectType());
                Map<String, Object> r = new HashMap<>();
                if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                     r = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), user.getCultureScore(), user.getMajorScore());

                }else{
                    r.put("acceptRate", 0);
                    r.put("rateType", -2);
                }
                 if (!r.isEmpty() ){
                    s.setAcceptRate(new BigDecimal(r.get("acceptRate").toString()));
                    s.setShowAcceptRate(s.getAcceptRate() + "%");
                    s.setRateType((Integer)r.get("rateType"));
                    //统计 该学校下的专业个数
                    Long count  = items.stream().filter(i -> s.getSchoolId().equals(i.getSchoolId())).count();
                    //0-可冒险,1-搏一搏,2-较稳妥,3-可保底
                    switch (s.getRateType()) {
                        case 0:
                            //0-可冒险
                            result.setAa(result.getAa()+count.intValue());
                            break;
                        case 1:
                            //1-搏一搏
                            result.setBb(result.getBb()+count.intValue());
                            break;
                        case 2:
                            //2-较稳妥
                            result.setCc(result.getCc()+count.intValue());
                            break;
                        case 3:
                            //3-可保底
                            result.setDd(result.getDd()+count.intValue());
                            break;
                    }
                    //全部
                    //全部志愿数
                    result.setAllNum(result.getAa()+result.getBb()+result.getCc()+result.getDd());
                }
            }
        }
        return result;
    }

    /** 填报志愿 卡片数据*/
    @Override
    public List<ReportCardVo> cardData( MallMemberUser mallMemberUser) {
        //提前批  A段 B段 专科
        //查询 当年 河南省 4个批次的列表
        List<ReportCardVo> reportCardVos = mallBatchDetailMapper.cardList();
        if(null != reportCardVos && reportCardVos.size()>0){
            String newYear = linkMajorSchoolMapper.selectMaxYear();
            CountDownLatch countDownLatch = new CountDownLatch(reportCardVos.size());
            try{
                for (ReportCardVo vo : reportCardVos) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if(vo.getBatchId() == 4L){
                                // 专科
                                CheckingOutParamBo bo = new CheckingOutParamBo();
                                bo.setMemberId(mallMemberUser.getId());
                                bo.setBatchId(4L);
                                if (mallMemberUser.getRateFlag() != null && mallMemberUser.getRateFlag() == 1){
                                    RateTypeSchoolMajorVo rateTypeSchoolMajorVo = tagNum2(bo, mallMemberUser);
                                    vo.setData(rateTypeSchoolMajorVo);
                                }else{
                                    RateTypeSchoolMajorVo rateTypeSchoolMajorVo = cardNum(mallMemberUser, vo.getBatchId(), newYear);
                                    vo.setData(rateTypeSchoolMajorVo);
                                }


                            }else{
                                // 本科
                                CheckingOutParamBo bo = new CheckingOutParamBo();
                                bo.setMemberId(mallMemberUser.getId());
                                bo.setBatchId(2L);
                                if (mallMemberUser.getRateFlag() != null && mallMemberUser.getRateFlag() == 1){
                                    RateTypeSchoolMajorVo rateTypeSchoolMajorVo = tagNum2(bo, mallMemberUser);
                                    vo.setData(rateTypeSchoolMajorVo);
                                }else{
                                    RateTypeSchoolMajorVo rateTypeSchoolMajorVo = cardNum(mallMemberUser, vo.getBatchId(), newYear);
                                    vo.setData(rateTypeSchoolMajorVo);
                                }

                            }


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

        }

        return reportCardVos;
    }

    public RateTypeSchoolMajorVo cardNum(MallMemberUser mallMemberUser,Long batchId, String newYear){
        RateTypeSchoolMajorVo rateTypeData = new RateTypeSchoolMajorVo();
        Integer majorScore = mallMemberUser.getMajorScore();
        Integer cultureScore = mallMemberUser.getCultureScore();
        String subjectType = mallMemberUser.getSubjectType();

        CheckingOutParamBo bo = new CheckingOutParamBo();
        bo.setBatchId(batchId);
        if(null != subjectType){
            bo.setSubjectType(subjectType);
        }
        bo.setNewYear(newYear);
        //在限制学校的基础上 限制专业 获取(学校id,专业id) 结果a
        List<MajorItemVo> a = mallLinkMajorSchoolService.astrictMajorItemList(bo);

        //去重学校id
        List<Long> sIds = a.stream().map(MajorItemVo::getSchoolId).distinct().collect(Collectors.toList());
        if(!sIds.isEmpty()) {
            List<SchoolMajorVO> schools = mallSchoolService.schoolListInfoForReport(sIds);
            CountDownLatch countDownLatch = new CountDownLatch(schools.size());
            try{
                for (SchoolMajorVO s : schools) {
                    //不需要填充学校信息 tags
                    //填充学校信息 录取ruleId 最低分 计算录取率
                    // 学校录取率
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                    System.out.println("========"+ s.getSchoolId() +"==" );
                            computSchool(subjectType,s,bo,cultureScore,majorScore,rateTypeData);
                            countDownLatch.countDown();
                        }
                    }).start();
                }
                countDownLatch.await();
            }catch (Exception e){
                e.printStackTrace();
                throw new ServiceException();
            }
        }
        return rateTypeData;
    }

    public void computSchool(String subjectType,SchoolMajorVO s,CheckingOutParamBo bo,Integer cultureScore,Integer majorScore,RateTypeSchoolMajorVo rateTypeData){

        // 学校录取专业最低分录取率
        Map<String, Object> r = new HashMap<>();
        MallSchoolAccept mallSchoolAccept = new MallSchoolAccept();
        if (bo.getBatchId() == 4L){
            // 专科
            mallSchoolAccept = mallSchoolAcceptMapper.selectZhuankeAcceptBySchoolId(s.getSchoolId(), bo.getBatchId(), subjectType);

            if(ObjectUtils.isNotEmpty(mallSchoolAccept)){
                r = mallCountMethodService.zhuankegetAcceptRateForReport(mallSchoolAccept.getAcceptLowest(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
            }else{
                r.put("acceptRate", 0);
                r.put("rateType", -2);
            }
        }else{

            // 本科
            mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(s.getSchoolId(), bo.getBatchId(), subjectType);
            if(ObjectUtils.isNotEmpty(mallSchoolAccept)){
                r = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
            }else {
                r.put("acceptRate", 0);
                r.put("rateType", -2);
            }

//            boolean flag = false;
//            // 选科：0-文科，1-理科
//            if (subjectType.equals("0") && cultureScore >= 331 && majorScore >= 193) {
//                flag = true;
//            }else if (subjectType.equals("1") && cultureScore >= 328 && majorScore >= 193){
//                flag = true;
//            }

            // 本科
//            mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(s.getSchoolId(), bo.getBatchId(), subjectType);
//            if(flag && ObjectUtils.isNotEmpty(mallSchoolAccept)){
//                r = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);
//            }else {
//                r.put("acceptRate", 0);
//                r.put("rateType", -2);
//            }
        }


        if (!r.isEmpty() ){
            s.setAcceptRate(new BigDecimal(r.get("acceptRate").toString()));
            s.setShowAcceptRate(s.getAcceptRate() + "%");
            s.setRateType((Integer)r.get("rateType"));
            //0-可冒险,1-搏一搏,2-较稳妥,3-可保底
            switch (s.getRateType()) {
                case 0:
                    //0-可冒险
                    rateTypeData.setA(rateTypeData.getA()+1);
                    break;
                case 1:
                    //1-搏一搏
                    rateTypeData.setB(rateTypeData.getB()+1);
                    break;
                case 2:
                    //2-较稳妥
                    rateTypeData.setC(rateTypeData.getC()+1);
                    break;
                case 3:
                    //3-可保底
                    rateTypeData.setD(rateTypeData.getD()+1);
                    break;
            }
            //全部
            rateTypeData.setAll(rateTypeData.getA()+rateTypeData.getB()+rateTypeData.getC()+rateTypeData.getD());
        }
    }


}
