package com.ruoyi.web.service;

import com.google.common.collect.Lists;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mxjb.domain.MxjbSelectedRound;
import com.ruoyi.mxjb.mapper.MxjbSelectedRoundMapper;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AdminSelectService {
    private final MxjbSelectedRoundMapper mxjbSelectedRoundMapper;
    private final ISysConfigService sysConfigService;

    public AdminSelectService(MxjbSelectedRoundMapper mxjbSelectedRoundMapper, ISysConfigService sysConfigService) {
        this.mxjbSelectedRoundMapper = mxjbSelectedRoundMapper;
        this.sysConfigService = sysConfigService;
    }

    public Integer getSelectCourseRound(){
        //取年份
        List<Integer> yearList = this.listYears();
        //处理当前学校开启的最新选科roundId ,year为返回数据的最新值
        Integer roundId = 0;
        for (Integer year : yearList) {
            List<MxjbSelectedRound> roundList = this.getSchoolRounds(SecurityUtils.getLoginUser().getSchoolId(), year);
            for (MxjbSelectedRound round : roundList) {
                if (round.getAllowSelect()) {
                    //TODO allowSelect表达的为选科全生命周期，但是此处需要的是当前round是否已经结束选科了
                    roundId = round.getRoundId();
                    break;
                }
            }
        }

        return roundId;
    }

    public List<Integer> listYears(){
        List<Integer> yearList = Lists.newArrayList();
        Integer curYear = Calendar.getInstance().get(Calendar.YEAR);
        Integer curMonth = Calendar.getInstance().get(Calendar.MONTH);
        String yearJudgement = sysConfigService.selectConfigByKey("year.judgement");
        Integer yearMonth = 7;//默认7月
        try {
            if(StringUtils.isNotBlank(yearJudgement)){
                yearMonth = Integer.parseInt(yearJudgement.split("-")[0]);
            }
        }catch (Exception e){
            yearMonth=7;
        }
        if (curMonth < yearMonth) {
            curYear--;
        }
        for (int i = curYear; i > curYear - 3 ; i--) {
            yearList.add(i);
        }
        return yearList;
    }

    public List<MxjbSelectedRound> getSchoolRounds(Long schoolId, Integer year) {
        MxjbSelectedRound round = new MxjbSelectedRound();
        round.setSchoolId(schoolId);
        round.setYear(year);
        List<MxjbSelectedRound> roundList = mxjbSelectedRoundMapper.selectMxjbSelectedRoundList(round);
        Date now = new Date();
        roundList.forEach(t -> {
            t.setAllowSelect("1".equals(t.getState()) && now.after(t.getBeginTime()) && now.before(DateUtils.addDays(t.getEndTime(), 1)));
        });
        return roundList;
    }
}
