package com.ruoyi.web.controller.front;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.syzy.domain.BBusiWishScoreGroups;
import com.ruoyi.syzy.service.IBBusiWishScoreGroupsService;
import com.ruoyi.web.service.CommService;
import com.ruoyi.web.service.ScoreRankService;
import com.ruoyi.web.service.ZyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = "模拟志愿-一分一段")
@RequestMapping("front/syzy/yfyd")
public class FrontSyzyYfydController extends BaseController {
    @Autowired
    private IBBusiWishScoreGroupsService scoreGroupsService;
    @Autowired
    private ScoreRankService scoreRankService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ZyService zyService;
    @Autowired
    private CommService commService;

    @GetMapping("locations")
    @ApiOperation("01.地域")
    public TableDataInfo locations() {
        List<String> list = scoreGroupsService.locations();
        CommonUtils.sortByChina(list);
        return getDataTable(list);
    }

    @GetMapping("years")
    @ApiOperation("02.录取年份")
    public TableDataInfo years(@ApiParam("地域") @RequestParam String location) {
        //此处显示使用时不限制status
        List<Integer> list = scoreGroupsService.yearsNoStatus(location);
        return getDataTable(list);
    }

    @GetMapping("modes")
    @ApiOperation("03.科类")
    public TableDataInfo modes(@ApiParam("地域") @RequestParam String location, @ApiParam("录取年份") @RequestParam String year) {
        //此处显示使用时不限制status
        List<Map> list = scoreGroupsService.modesNoStatus(location, year).stream().map(t -> {
            Map d = new HashMap();
            d.put("mode", t.getMode());
            d.put("modeName", t.getModeName());
            return d;
        }).collect(Collectors.toList());
        return getDataTable(list);
    }

    @GetMapping("list")
    @ApiOperation("04.一分一段列表")
    public TableDataInfo list(@ApiParam("地域") @RequestParam String location, @ApiParam("录取年份") @RequestParam(required = false) Integer year,
        @ApiParam("科类") @RequestParam String mode, @ApiParam("分数或位次") Integer scoreRank,@ApiParam("type 1分数，2位次") Integer type,
        @ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
        @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
        BBusiWishScoreGroups query = new BBusiWishScoreGroups();
        query.setLocation(location).setYear(year).setMode(mode).setScoreRank(scoreRank).setType(type);
        startPage();
        List<BBusiWishScoreGroups> list = scoreGroupsService.selectBBusiWishScoreGroupsList(query);
        return getDataTable(list);
    }

    @GetMapping("getRankByScore")
    @ApiOperation("05.根据分数找位次")
    public AjaxResult getDataByRankOrScore(@ApiParam("地域") String location, @ApiParam("录取年份")  Integer year,
                              @ApiParam("分数或位次") @RequestParam Integer scoreRank) {
        if(StringUtils.isBlank(location)){
            location= SecurityUtils.getLoginUser().getUser().getLocation();
        }
        if(null==year){
            year = scoreGroupsService.years(location).stream().filter(e -> e != null).max(Comparator.naturalOrder()).orElse(0);
        }

        Map cond = Maps.newHashMap();
        cond.put("score", scoreRank);
        cond.put("location", location);
        cond.put("year", year);
        cond.put("mode", SecurityUtils.getLoginUser().getUser().getExamMajor()); // 物理/历史 或 文科/理课
        List<BBusiWishScoreGroups> groupList = scoreGroupsService.selectBusiWishScoreGroupsByScore(cond);
        if (CollectionUtils.isEmpty(groupList)) {
            return AjaxResult.success(new BBusiWishScoreGroups());
        }
        return AjaxResult.success(groupList.get(0));
    }


    @GetMapping("getEquivalentScore")
    @ApiOperation("06.根据分数找历史等效位次")
    public AjaxResult getEquivalentScore(@ApiParam("地域") String location, @ApiParam("录入年度")  Integer year,
                                         @ApiParam("分数") @RequestParam Integer score) {
        if (StringUtils.isBlank(location)) {
            location = commService.getLocation(location);
        }
        String mode = String.valueOf(SecurityUtils.getLoginUser().getUser().getExamMajor());
        // 1. 初始当前年度, 文理类型
        List<Integer> list = scoreGroupsService.yearsNoStatus(location);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.error("无有效一分一段数据");
        }
        Integer currYear = zyService.getYear();
        String forceLocation = configService.selectConfigByKey("voluntary.force.locations");
        Integer submitYear = currYear;
        if (null != forceLocation && forceLocation.contains(location)) {
            submitYear = submitYear - 1;
        }
        if (null == year) {
            year = list.get(0);
        }

        // Map cond = Maps.newHashMap();
        // ZyService.appendMode(cond, location, mode);
        // List<String> modes = cond.containsKey("modes") ? (List) cond.get("modes") : Lists.newArrayList((String) cond.get("mode"));

        AjaxResult ajax = AjaxResult.success();

        BBusiWishScoreGroups base = scoreRankService.getScoreGroups(location, year, mode, score);
        ajax.put("match", base);
        ajax.put("scores", getHistoryEqList(base, mode, currYear, year, submitYear, score, location));
        return ajax;
    }

    private List<Map> getHistoryEqList(BBusiWishScoreGroups base, String mode, Integer maxYear, Integer userYear, Integer submitYear, Integer score, String location) {
        List<Map> historyEqList = Lists.newArrayList();
        if(null == base) {
            return historyEqList;
        }
        BBusiWishScoreGroups currScoreRange = scoreRankService.getScoreRangeByScore(location, maxYear, mode, userYear, score);
        if (null == currScoreRange) {
            return historyEqList;
        }
        Integer minYear = submitYear - 2; // 专业线最近3年 + 计划年, 计划是新年度时共4年
        for (int i = submitYear; i >= minYear; i--) {
            Map tmp = new HashMap();
            tmp.put("year" , i);
            BBusiWishScoreGroups eqScoreRange = scoreRankService.getScoreRangeByBatch(location, maxYear, currScoreRange.getMode(), i, currScoreRange.getType());
            Integer eqRank = scoreRankService.getEqRank(currScoreRange, eqScoreRange, location, maxYear, userYear, score, null, i);
            if (null == eqRank) {
                tmp.put("seat", 0);
                tmp.put("score", 0);
            } else {
                tmp.put("seat" , eqRank);
                Integer lastEqScore = scoreRankService.getScore(location, i, eqScoreRange.getMode(), eqRank);
                tmp.put("score" , lastEqScore);
            }
            historyEqList.add(tmp);
        }
        return historyEqList;
    }
}
