package com.ruoyi.web.controller.front;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResult2;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.content.VistorContextHolder;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.syzy.domain.*;
import com.ruoyi.syzy.dto.UniversitiesCondDTO;
import com.ruoyi.syzy.dto.UniversityDetailDTO;
import com.ruoyi.syzy.service.*;
import com.ruoyi.util.ConstantUtil;
import com.ruoyi.web.domain.Constant;
import com.ruoyi.web.service.CommService;
import com.ruoyi.web.service.VoluntaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@Api(tags = "前端-三库-院校库")
@RequestMapping("front/university")
public class FrontUniversitiesController extends BaseController {

    @Autowired
    private IBBusiWishUniversitiesImageService universitiesImageService;
    @Autowired
    private IBBusiWishUniversitiesEnrollBrochureService universitiesEnrollBrochureService;
    @Autowired
    private IBBusiWishUniversitiesService universitiesService;
    @Autowired
    private IBBusiWishUniversitiesRankingService universitiesRankingService;
    @Autowired
    public ISysDictTypeService dictTypeService;
    @Autowired
    private IBCustomerUniversitiesService customerUniversitiesService;
    @Autowired
    private VoluntaryService voluntaryService;
    @Autowired
    private IBBusiWishUniversitySubmitMarjorsService wishUniversitySubmitMarjorsService;
    @Autowired
    private IBBusiWishUniversitySubmitRecruitPlanService wishUniversitySubmitRecruitPlanService;
    @Autowired
    private CommService commService;

    /**
     * 获取梯次描述
     * @param tierValue 梯次值
     * @return 梯次描述
     */
    private String getTierDesc(String tierValue) {
        return dictTypeService.getDictDataByType("tier_desc", tierValue);
    }

    @GetMapping("filters")
    @ApiOperation("00 院校列表数据筛选项")
    @Anonymous
    public AjaxResult filters() {
        String entranceType = ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title());
        JSONObject data = new JSONObject(true);
        data.put("locations", universitiesService.getLocations(entranceType));
        data.put("natureTypes", universitiesService.getNatureTypeCN(entranceType));//办学性质：公办民办
        data.put("types", universitiesService.getTypes(entranceType));//院校类别
//        data.put("levels", universitiesService.getLevels());
        data.put("features", universitiesService.getFeatures(entranceType));//等级
        data.put("bxTypes", universitiesService.getBxTypes(entranceType));//双高院校
        //竞争力星级
        Map<String,String> map = dictTypeService.selectDictDataByType("university_stars")
                .stream().collect(Collectors.toMap(t -> t.getDictValue(), SysDictData::getDictLabel));
        map.entrySet().stream().sorted(Map.Entry.comparingByKey());
        data.put("stars", map);

        //梯次
        Map<String,String> tierMap = dictTypeService.selectDictDataByType("tier_type")
                .stream().collect(Collectors.toMap(t -> t.getDictValue(), SysDictData::getDictLabel));
        map.entrySet().stream().sorted(Map.Entry.comparingByKey());
        data.put("tiers", tierMap);
        return AjaxResult.success(data);
    }

    @GetMapping("locations")
    @ApiOperation("00 院校列表数据筛选项-地域 回传location")
    @Anonymous
    public AjaxResult locations() {
        return AjaxResult.success(universitiesService.getLocations(ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title())));
    }

    @GetMapping("locations2")
    @Anonymous
    @ApiOperation("00 院校列表数据筛选项-地域 回传location和cityName")
    public AjaxResult locations2() {
//        List<BBusiWishUniversities> list = universitiesService.selectBBusiWishUniversitiesLocations2(ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title()));
        List<BBusiWishUniversities> list = universitiesService.selectBBusiWishUniversitiesLocations3(VistorContextHolder.getLocation());

        // 按location分组，收集每个location下的cityName
        Map<String, Set<String>> locationCityMap = list.stream()
                .filter(item -> StringUtils.isNotBlank(item.getLocation()) && StringUtils.isNotBlank(item.getCityName()))
                .collect(Collectors.groupingBy(
                        BBusiWishUniversities::getLocation,
                        Collectors.mapping(
                                BBusiWishUniversities::getCityName,
                                Collectors.toSet()
                        )
                ));

        // 构建返回数据
        List<Map<String, Object>> result = locationCityMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(entry -> {
                    Map<String, Object> item = Maps.newHashMap();
                    item.put("location", entry.getKey());
                    // 将Set转为List并排序
                    List<String> cityNames = entry.getValue().stream()
                            .sorted()
                            .collect(Collectors.toList());
                    item.put("cityName", cityNames);
                    return item;
                })
                .collect(Collectors.toList());

        return AjaxResult.success(result);
    }

    @GetMapping("natureTypes")
    @ApiOperation("00 院校列表数据筛选项-主管机构类型 回传natureTypeCN")
    @Anonymous
    public AjaxResult natureTypes() {
        return AjaxResult.success(universitiesService.getNatureTypeCN(ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title())));
    }

    @GetMapping("types")
    @ApiOperation("00 院校列表数据筛选项-院校类型 回传type")
    @Anonymous
    public AjaxResult types() {
        return AjaxResult.success(universitiesService.getTypes(ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title())));
    }

    @GetMapping("levels")
    @ApiOperation("00 院校列表数据筛选项-学历层次 回传level")
    public AjaxResult levels() {
        return AjaxResult.success(universitiesService.getLevels(ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title())));
    }

    @GetMapping("features")
    @ApiOperation("00 院校列表数据筛选项-院校类型 回传features")
    @Anonymous
    public AjaxResult features() {
        return AjaxResult.success(universitiesService.getFeatures(ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title())));
    }

    @GetMapping("listNoToken")
    @ApiOperation("01 院校列表")
    public TableDataInfo listNoToken(UniversitiesCondDTO cond, @ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
                                     @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
        return getDataTable(getUniversitiesList(cond,null,  pageNum, pageSize));
    }

    @GetMapping("listByTier")
    @ApiOperation("01 分级院校列表")
    @Anonymous
    public AjaxResult2<List<JSONObject>> listByTier(UniversitiesCondDTO cond) {
        String location = VistorContextHolder.getLocation();
        if(StringUtils.isNotBlank(location)){
            location = location+",全国";
        }
        if(StringUtils.isBlank(cond.getTiers())) {
            cond.setTiers("1,2,3,4,5,6,7,8");
        }
        List<JSONObject> tierList = Lists.newArrayList();
        List<BBusiWishUniversities> arr = getUniversitiesList(cond,location,  -1, 15);
        Collections.sort(arr, new Comparator<BBusiWishUniversities>() {
            @Override
            public int compare(BBusiWishUniversities o1, BBusiWishUniversities o2) {
                int iRet;
                if(null == o1.getTierRank()) {
                    if(null != o2.getTierRank()) {
                        return 1;
                    }
                } else if(null == o2.getTierRank()) {
                    return -1;
                } else if(0 != (iRet = o1.getTierRank().compareTo(o2.getTierRank()))) {
                    return iRet;
                }
                return o1.getCode().compareTo(o2.getCode());
            }
        });
        Map<Integer, List<BBusiWishUniversities>> tierMap = arr.stream().filter(t -> null != t.getTier())
                .collect(Collectors.groupingBy(BBusiWishUniversities::getTier, Collectors.toList()));
        List<SysDictData> tierTypeList = dictTypeService.selectDictDataByType("tier_type");
        Set<String> tierSet = Sets.newHashSet(Arrays.asList(cond.getTiers().split(",")));
        for(SysDictData dd : tierTypeList) {
            if(!tierSet.contains(dd.getDictValue())) {
                continue;
            }
            List<BBusiWishUniversities> uList = tierMap.get(NumberUtils.toInt(dd.getDictValue()));
            JSONObject tierUniversities = new JSONObject();
            tierUniversities.put("typeName", dd.getDictLabel());
            tierUniversities.put("typeValue", dd.getDictValue());
            tierUniversities.put("desc", getTierDesc(dd.getDictValue()));
            tierUniversities.put("list", uList.size() > 10 ? uList.subList(0, 10) : uList);
            tierList.add(tierUniversities);
        }
        return AjaxResult2.success(tierList);
    }

    @GetMapping("list")
    @ApiOperation("01 院校列表")
    public TableDataInfo list(UniversitiesCondDTO cond, @ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
                              @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
        String location = VistorContextHolder.getLocation();
        if(StringUtils.isNotBlank(location)){
            location = location+",全国";
        }
        return getDataTable(getUniversitiesList(cond,location,  pageNum, pageSize));
    }

    public List<BBusiWishUniversities> getUniversitiesList(UniversitiesCondDTO cond,String location, Integer pageNum,Integer pageSize){
        if (StringUtils.isNumber(cond.getName())) {
            cond.setCode(cond.getName());
            cond.setName(null);
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        cond.setEnrollLocation(user.getLocation());
        List<BBusiWishUniversities> arr;
        Integer planYear = voluntaryService.getPlanYear(user);

        if (null != pageNum && pageNum >= 0) {
            startPage();
        }
        if(Constant.EXAM_TYPE_ZG.equals(user.getExamType().title())) {
            //职高对口
            arr = universitiesService.selectMajorWishUniversitiesListSimpleByMap2(cond.toCondMap(planYear, user.getExamType().title(), user.getExamMajor(), user.getLocation(),cond.getTiers(),cond.getCityName())); // TODO MF
        } else {
            arr = universitiesService.selectMajorWishUniversitiesListSimpleByMap(cond.toCondMap(planYear, Constant.EXAM_TYPE_PG, null, user.getLocation(),cond.getTiers(),cond.getCityName()));
        }
        //处理院校星级竞争力
        arr.stream().forEach(t -> {
            if(StringUtils.isNotEmpty(t.getStar())){
                t.setStar(dictTypeService.getDictDataByType("university_stars",t.getStar()));
            }
        });
        return arr;
    }

    @GetMapping("detail")
    @ApiOperation("02 院校详情")
    public AjaxResult detail(@ApiParam("学校code") @RequestParam String code) {
        commService.requireVip();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        UniversityDetailDTO data = universitiesService.detail(code, voluntaryService.getPlanYear(sysUser));
        if(StringUtils.isNotEmpty(data.getBaseInfo().getStar())){
            data.getBaseInfo().setStar(dictTypeService.getDictDataByType("university_stars",data.getBaseInfo().getStar()));
        }
        Long universityId = data.getBaseInfo().getId();
        BCustomerUniversities cond = new BCustomerUniversities();
        cond.setUniversityId(universityId);
        cond.setCustomerCode(sysUser.getCode());
        cond.setStatus(1L);
        List<BCustomerUniversities> list = customerUniversitiesService.selectBCustomerUniversitiesList(cond);
        data.getBaseInfo().setCollected(CollectionUtils.isNotEmpty(list));
        this.saveUniversitiesClicks(code);

        if(Constant.EXAM_TYPE_ZG.equals(sysUser.getExamType().title())) {
            Integer examMajor = sysUser.getExamMajor();

            BBusiWishUniversitySubmitRecruitPlan planCond = new BBusiWishUniversitySubmitRecruitPlan();
            planCond.setUniversityId(universityId);
            planCond.setLocation(sysUser.getLocation());
            planCond.setLiberalScience(examMajor);
            List<UniversityDetailDTO.WishPlan> planList = wishUniversitySubmitRecruitPlanService.selectBBusiWishUniversitySubmitRecruitPlanList(planCond).stream().map(t -> new UniversityDetailDTO.WishPlan(t)).collect(Collectors.toList());
            data.setPlanHistories(planList);

            BBusiWishUniversitySubmitMarjors submitCond = new BBusiWishUniversitySubmitMarjors();
            submitCond.setUniversityId(universityId);
            submitCond.setLocation(sysUser.getLocation());
            submitCond.setLiberalScience(examMajor);
            List<UniversityDetailDTO.WishSubmit> submitList = wishUniversitySubmitMarjorsService.selectBBusiWishUniversitySubmitMarjorsList(submitCond).stream().map(t -> new UniversityDetailDTO.WishSubmit(t)).collect(Collectors.toList());
            data.setEnrollHistories(submitList);
        } else if(Constant.EXAM_TYPE_PG.equals(sysUser.getExamType().title()) || Constant.EXAM_TYPE_ZZ.equals(sysUser.getExamType().title())) {
            Pair<List<UniversityDetailDTO.WishPlan>, List<UniversityDetailDTO.WishSubmit>> pair = voluntaryService.getUniversityHistory(universityId, sysUser.getLocation(), sysUser.getExamType().title());
            data.setPlanHistories(pair.getLeft());
            data.setEnrollHistories(pair.getRight());
        }
        return AjaxResult.success(data);
    }

    /**
     * 新接口：20260110
     * @param code
     * @param title
     * @return
     */
    @GetMapping("getUniversityBaseInfo")
    @ApiOperation("112 院校基础信息")
    public AjaxResult getUniversityDetail(@ApiParam("学校code") @RequestParam String code) {
//        long startTime = System.currentTimeMillis();
//        long currentTime = startTime;

        commService.requireVip();
//        log.info("Step 0 - 获取VIP完成, 耗时: {} ms", System.currentTimeMillis() - currentTime);

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
//        log.info("Step 1 - 获取用户信息完成, 耗时: {} ms", System.currentTimeMillis() - currentTime);
//        currentTime = System.currentTimeMillis();

        UniversityDetailDTO data = universitiesService.detail(code, voluntaryService.getPlanYear(sysUser));
//        log.info("Step 2 - 获取院校详情完成, 耗时: {} ms", System.currentTimeMillis() - currentTime);
//        currentTime = System.currentTimeMillis();

        if(StringUtils.isNotEmpty(data.getBaseInfo().getStar())){
            data.getBaseInfo().setStar(dictTypeService.getDictDataByType("university_stars",data.getBaseInfo().getStar()));
        }
//        log.info("Step 3 - 处理院校星级完成, 耗时: {} ms", System.currentTimeMillis() - currentTime);
//        currentTime = System.currentTimeMillis();

        Long universityId = data.getBaseInfo().getId();
        BCustomerUniversities cond = new BCustomerUniversities();
        cond.setUniversityId(universityId);
        cond.setCustomerCode(sysUser.getCode());
        cond.setStatus(1L);
        List<BCustomerUniversities> list = customerUniversitiesService.selectBCustomerUniversitiesList(cond);
//        log.info("Step 4 - 查询收藏状态完成, 耗时: {} ms", System.currentTimeMillis() - currentTime);
//        currentTime = System.currentTimeMillis();

        data.getBaseInfo().setCollected(CollectionUtils.isNotEmpty(list));
        this.saveUniversitiesClicks(code);
//        log.info("Step 5 - 更新点击量和设置收藏状态完成, 耗时: {} ms", System.currentTimeMillis() - currentTime);

//        log.info("总耗时: {} ms", System.currentTimeMillis() - startTime);

        return AjaxResult.success(data);
    }

    /**
     * 新接口：20260110
     * @param code
     * @param title
     * @return
     */
    @GetMapping("getUniversityPlanEnroll")
    @ApiOperation("113 院校计划与录取分数")
    public AjaxResult getUniversityPlanEnroll(@ApiParam("学校code") @RequestParam String code) {
        commService.requireVip();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        UniversityDetailDTO data = new UniversityDetailDTO();
        Long universityId = Long.parseLong(code);

        if(Constant.EXAM_TYPE_ZG.equals(sysUser.getExamType().title())) {
            Integer examMajor = sysUser.getExamMajor();

            BBusiWishUniversitySubmitRecruitPlan planCond = new BBusiWishUniversitySubmitRecruitPlan();
            planCond.setUniversityId(universityId);
            planCond.setLocation(sysUser.getLocation());
            planCond.setLiberalScience(examMajor);
            List<UniversityDetailDTO.WishPlan> planList = wishUniversitySubmitRecruitPlanService.selectBBusiWishUniversitySubmitRecruitPlanList(planCond).stream().map(t -> new UniversityDetailDTO.WishPlan(t)).collect(Collectors.toList());
            data.setPlanHistories(planList);

            BBusiWishUniversitySubmitMarjors submitCond = new BBusiWishUniversitySubmitMarjors();
            submitCond.setUniversityId(universityId);
            submitCond.setLocation(sysUser.getLocation());
            submitCond.setLiberalScience(examMajor);
            List<UniversityDetailDTO.WishSubmit> submitList = wishUniversitySubmitMarjorsService.selectBBusiWishUniversitySubmitMarjorsList(submitCond).stream().map(t -> new UniversityDetailDTO.WishSubmit(t)).collect(Collectors.toList());
            data.setEnrollHistories(submitList);
        } else if(Constant.EXAM_TYPE_PG.equals(sysUser.getExamType().title()) || Constant.EXAM_TYPE_ZZ.equals(sysUser.getExamType().title())) {
            Pair<List<UniversityDetailDTO.WishPlan>, List<UniversityDetailDTO.WishSubmit>> pair = voluntaryService.getUniversityHistory(universityId, sysUser.getLocation(), sysUser.getExamType().title());
            data.setPlanHistories(pair.getLeft());
            data.setEnrollHistories(pair.getRight());
        }
        return AjaxResult.success(data);
    }

    @GetMapping("getUniversitiesEnrollBrochure")
    @ApiOperation("03 招生简章")
    public TableDataInfo getUniversitiesEnrollBrochure(@ApiParam("学校code") @RequestParam String code,
                                                       @ApiParam("学校code")  String title) {
        BBusiWishUniversitiesEnrollBrochure query = new BBusiWishUniversitiesEnrollBrochure();
        query.setCollegeCode(code);
        query.setTitle(title);
//        startPage();
        List<BBusiWishUniversitiesEnrollBrochure> list = universitiesEnrollBrochureService.selectBBusiWishUniversitiesEnrollBrochureList(query);
        return getDataTable(list);
    }

    @GetMapping("getUniversitiesEnrollBrochureDetail")
    @ApiOperation("03-2 招生简章详情")
    public AjaxResult getUniversitiesEnrollBrochure(@ApiParam("简章id") @RequestParam Long id) {
        return AjaxResult.success(universitiesEnrollBrochureService.selectBBusiWishUniversitiesEnrollBrochureById(id));
    }

    @PostMapping("saveUniversitiesEnrollBrochureHits")
    @ApiOperation("04-2 保存招生简章热度/点击")
    public AjaxResult saveUniversitiesEnrollBrochureHits(@ApiParam("ID") @RequestParam Long id){
        BBusiWishUniversitiesEnrollBrochure result = universitiesEnrollBrochureService.selectBBusiWishUniversitiesEnrollBrochureById(id);
        result.setHits(null==result.getHits()?1:(result.getHits()+1));
        universitiesEnrollBrochureService.updateBBusiWishUniversitiesEnrollBrochure(result);
        return AjaxResult.success("保存成功");
    }

    //    @PostMapping("saveUniversitiesHits")
//    @ApiOperation("04 保存院校热度/点击")
    public AjaxResult saveUniversitiesClicks(@ApiParam("学校code") @RequestParam String code) {
        BBusiWishUniversities result  = universitiesService.selectBBusiWishUniversitiesByCode(code);
        if(null==result){
            return AjaxResult.error("学校[ "+code+" ]不存在");
        }
        BBusiWishUniversities update = new BBusiWishUniversities();
        update.setId(result.getId());
        update.setHits(null==result.getHits()?1:(result.getHits()+1));
        universitiesService.updateBBusiWishUniversities(update);
        return AjaxResult.success();
    }

    @GetMapping("getUniversitiesHitsTopCount")
    @ApiOperation("05 获取院校热度/点击 Top count")
    public AjaxResult getUniversitiesHits(Integer count) {
        BBusiWishUniversities exam = new BBusiWishUniversities();
        exam.getParams().put("orderBy", "hits desc");
        exam.getParams().put("limit", null==count?8:count);
        List<BBusiWishUniversities> arr = universitiesService.selectBBusiWishUniversitiesListSimple(exam);
        return AjaxResult.success(arr);
    }

    @GetMapping("getUniversitiesStyle")
    @ApiOperation("06 获取院校风采")
    public AjaxResult getUniversitiesStyle(@ApiParam("学校code") @RequestParam String code) {
        BBusiWishUniversitiesImage query = new BBusiWishUniversitiesImage();
        query.setCollegeCode(code);
//        query.getParams().put("orderBy", "collegeCode,sort");
        List<BBusiWishUniversitiesImage> list = universitiesImageService.selectBBusiWishUniversitiesImageList(query);
        return AjaxResult.success(list);
    }

    @GetMapping("getUniversitiesRankingFilter")
    @ApiOperation("07-1 获取院校排名筛选条件")
    public AjaxResult getUniversitiesRankingFilter(String type) {
        JSONObject result = new JSONObject();
        result.put("types",universitiesRankingService.selectBBusiWishUniversitiesRankingTypes());
        result.put("years",universitiesRankingService.selectBBusiWishUniversitiesRankingYears(type));
        return AjaxResult.success(result);
    }

    @GetMapping("getUniversitiesRankingFilterYears")
    @ApiOperation("07-1-1 获取院校排名筛选条件年份")
    public AjaxResult getUniversitiesRankingFilterYears(String type) {
        JSONObject result = new JSONObject();
        result.put("years",universitiesRankingService.selectBBusiWishUniversitiesRankingYears(type));
        return AjaxResult.success(result);
    }

    @GetMapping("getUniversitiesRanking")
    @ApiOperation("07-2 获取院校排名")
    public TableDataInfo getUniversitiesRanking(@ApiParam("排名类型") @RequestParam String type,
                                                @ApiParam("年份") @RequestParam Integer year,@ApiParam("学校名称")  String collegeName) {

        return getUniversitiesRankingList(type, year, collegeName);
    }

    @GetMapping("getUniversitiesRankingNoToken")
    @ApiOperation("07-2 获取院校排名")
    public TableDataInfo getUniversitiesRankingNoToken(@ApiParam("排名类型") @RequestParam String type,
                                                       @ApiParam("年份") @RequestParam Integer year,@ApiParam("学校名称")  String collegeName) {

        return getUniversitiesRankingList(type, year, collegeName);
    }

    private TableDataInfo getUniversitiesRankingList(String type,Integer year,String collegeName){
        BBusiWishUniversitiesRanking query = new BBusiWishUniversitiesRanking();
        query.setType(type);
        query.setYear(year);
        if(StringUtils.isNotBlank(collegeName)){
            query.setCollegeName(collegeName);
        }
//        query.getParams().put("orderBy", " ranking");
        startPage();
        //取到学校数据
        List<BBusiWishUniversitiesRanking> list = universitiesRankingService.selectBBusiWishUniversitiesRankingList(query);
        return getDataTable(list);
    }

    @GetMapping("getUniversitiesRankingByTypes")
    @ApiOperation("07-3 获取院校排名->APP使用")
    public TableDataInfo getUniversitiesRankingByTypes(@ApiParam("排名类型") @RequestParam String type) {
        Integer year = universitiesRankingService.selectUniversitiesRankingMaxYearByType(type);
        if(null==year){
            return getDataTable(new ArrayList<>());
        }

        BBusiWishUniversitiesRanking query = new BBusiWishUniversitiesRanking();
        query.setType(type);
        query.setYear(year);

        //取到最新一年的学校排名数据
        startPage();
        List<BBusiWishUniversitiesRanking> list = universitiesRankingService.selectBBusiWishUniversitiesRankingList(query);

        List<String> collegeCodes = list.stream().map(t->t.getCollegeCode()).collect(Collectors.toList());
        query = new BBusiWishUniversitiesRanking();
        query.setType(type);
        query.setCollegeCodes(collegeCodes);
        query.getParams().put("maxYear", year-1);
        query.getParams().put("minYear", year-2);
        //取最近两年对应学校的数据
        List<BBusiWishUniversitiesRanking>  historyList = universitiesRankingService.selectBBusiWishUniversitiesRankingList(query);
        Map<String,Integer> yearCodeRankingMap = historyList.stream().collect(Collectors.toMap(e -> (e.getYear()+e.getCollegeCode()),e -> e.getRanking()));
//        Map<String, BBusiWishUniversitiesRanking> importMap = historyList.stream().collect(Collectors.toMap(BBusiWishUniversitiesRanking::getCollegeCode, Function.identity()));
        //填充过去2年数据
        for (BBusiWishUniversitiesRanking ll : list) {
            //去年
            String key = (ll.getYear() - 1) + ll.getCollegeCode();
            if (yearCodeRankingMap.containsKey(key)) {
                ll.setLastRanking1(yearCodeRankingMap.get(key));
            }
            //前年
            key = (ll.getYear() - 2) + ll.getCollegeCode();
            if (yearCodeRankingMap.containsKey(key)) {
                ll.setLastRanking2(yearCodeRankingMap.get(key));
            }
        }

        return getDataTable(list);
    }

}
