package com.ruoyi.framework.web.service;

import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.dto.SchoolGradeClassesDto;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BoolValues;
import com.ruoyi.common.enums.NewgaokaoType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mxjb.domain.MxjbSelectedGroup;
import com.ruoyi.mxjb.service.IMxjbSelectedGroupService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.voluntary.domain.*;
import com.ruoyi.voluntary.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Service
public class UserCommonService {
    private static final Logger log = LoggerFactory.getLogger(UserCommonService.class);

    @Autowired
    private IBusiScoreLockService scoreLockService;
    @Autowired
    private IBusiCardsService cardsService;

    @Autowired
    private IBusiSchoolsService schoolsService;
    @Autowired
    private IBusiGradeService gradeService;
    @Autowired
    private IBusiClassesService classesService;
    @Autowired
    private ISysLocationsService locationsService;
    @Autowired
    private IMxjbSelectedGroupService groupService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 高考年度是下一年
     * @return
     */
    public List<Integer> listGaokaoYears(){
        List<Integer> yearList = Lists.newArrayList();
        Integer curYear = Calendar.getInstance().get(Calendar.YEAR);
        String yearJudgement = configService.selectConfigByKey("year.judgement");
        try {
            if (Calendar.getInstance().getTime().before(new SimpleDateFormat("yyyy-MM-dd").parse(curYear + "-" + (StringUtils.isNotBlank(yearJudgement) ? yearJudgement : "08-01")))) {
                curYear--;
            }
        }catch (Exception e){
            if (Calendar.getInstance().get(Calendar.MONTH) < 8) {
                curYear--;
            }
        }
        for (int i = curYear + 1; i < curYear + 4 ; i++) {
            yearList.add(i);
        }
        return yearList;
    }

    public BusiGrade getGradeByYear(Integer gaoKaoYear) {
        if (null == gaoKaoYear) {
            return null;
        }
        BusiGrade grade = new BusiGrade();
        grade.setYear(gaoKaoYear - 3L);
        List<BusiGrade> busiGradeList = gradeService.selectBusiGradeList(grade);
        return CollectionUtils.isNotEmpty(busiGradeList) ? busiGradeList.get(0) : null;
    }

    public SysUser getUserBasicInfo(SysUser user){
//        if(AccessFromType.isFrontAccess(user.getUserType())){
            //前端用户才处理学校班级等信息
            BusiSchools userSchool = null;
            BusiGrade userGrade = null;
            BusiClasses userClass = null;
            String provinceName=user.getProvinceName();
            if(null != user.getSchoolId() && user.getSchoolId() > 0) {
                userSchool = schoolsService.selectBusiSchoolsById(user.getSchoolId());
                userGrade = gradeService.selectBusiGradeById(user.getGradeId());
                userClass = classesService.selectBusiClassesByClassId(user.getClassId());
                if(StringUtils.isNotNull(userSchool)){
                    //获取学校、班级、年级信息
                    if(StringUtils.isBlank(provinceName)){
                        provinceName = locationsService.getNameByLocationId(userSchool.getPro());
                    }
                    user.setProvinceName(provinceName);
                    user.setAreaName(locationsService.getNameByLocationId(userSchool.getArea()));
                    user.setCityName(locationsService.getNameByLocationId(userSchool.getCity()));
                    user.setSchoolName(userSchool.getName());
                }
            } else if (StringUtils.isNotBlank(user.getCustomSchoolName())) {
                user.setSchoolId(-1L);
                userSchool = new BusiSchools();
                userSchool.setId(-1L);
                userSchool.setName(user.getCustomSchoolName());
                userGrade = null != user.getGradeId() ? gradeService.selectBusiGradeById(user.getGradeId()) : getGradeByYear(user.getGaokaoYear());
                userClass = new BusiClasses();
                userClass.setName(user.getCustomClassName());
                user.setSchoolId(userSchool.getId());
                user.setSchoolName(userSchool.getName());
            }
            if(StringUtils.isNotNull(user.getCardId())){
                BusiCards card = cardsService.selectBusiCardsByCardId(user.getCardId());
                if (null == user.getGaokaoYear()) {
                    user.setGaokaoYear(card.getEndYear());
                }
                if(StringUtils.isNotNull(card)){
                    user.setOutDate(card.getOutDate());
                }
            }
            //处理学生所在省份的高考类型
            user.setNewgaokaoType(NewgaokaoType.getNewgaokaoType(StringUtils.isBlank(user.getProvinceName())?provinceName:user.getProvinceName()));
            //学校信息
            SchoolGradeClassesDto busiSchool = new SchoolGradeClassesDto();
            if(StringUtils.isNotNull(userSchool)){
                busiSchool.setSchoolId(userSchool.getId());
                busiSchool.setSchoolName(userSchool.getName());
            }
            if(StringUtils.isNotNull(userGrade) ){
                busiSchool.setGradeId(userGrade.getId());
                busiSchool.setGradeName(userGrade.getName());
            }
            if(StringUtils.isNotNull(userClass)){
                busiSchool.setClassId(userClass.getClassId());
                busiSchool.setClassName(userClass.getName());
                user.setCustomClassName(userClass.getName());
            }
            user.setSchool(busiSchool);
            //处理mode
            if(StringUtils.isNotNull(user.getGroupId())){
                MxjbSelectedGroup group= groupService.selectMxjbSelectedGroupById(user.getGroupId());
                user.setMode(StringUtils.isBlank(group.getCourse1())?group.getCourse0():(group.getCourse0()+","+group.getCourse1()));
            }
            //处理模拟志愿个数
        /**
            String voluntaryCount= configService.selectConfigByKey("voluntary.num");
            if(StringUtils.isNotEmpty(voluntaryCount)){
                try {
                    JSONArray array = JSONArray.parseArray(voluntaryCount);
                    array.stream().forEach(item->{
                        JSONObject jsonObject=(JSONObject) item;
                        if(jsonObject.getString("location").trim().contains(user.getProvinceName().trim())){
                            user.setVoluntaryParam(jsonObject);
                            return;
                        }
                    });
                }catch (Exception e){
                    log.error("解析志愿个数配置失败, {}",e.toString());
                }
            }**/

//        }



//        BusiScoreLock scoreLock =scoreLockService.selectBusiScoreLockByProvinceName(user.getProvinceName());
//        Integer scoreLockVal = 1;
//        if(StringUtils.isNull(scoreLock)){
//            //默认锁定
//            scoreLockVal = BoolValues.yes.getValue();
//        }else {
//            if(BoolValues.isTrue(scoreLock.getIsValid())){
//                //生效，当前时间是否在范围内
//                if(DateUtils.inIntervalDate(scoreLock.getStartDate(),scoreLock.getEndDate())){
//                    scoreLockVal = BoolValues.yes.getValue();
//                }else {
//                    scoreLockVal = BoolValues.no.getValue();
//                }
//            }else {
//                scoreLockVal = BoolValues.no.getValue();
//            }
//        }
//        user.setScoreLock(scoreLockVal);

        return user;
    }

    /**
     * 用户所在省份当前是否在锁定成绩范围内（时间及省份）
     * @param user
     * @return
     */
    public Boolean isInIntervalDate(SysUser user){
        BusiScoreLock scoreLock =scoreLockService.selectBusiScoreLockByProvinceName(user.getProvinceName());
        Boolean scoreLockVal = false;
        if(StringUtils.isNotNull(scoreLock)){
            if(BoolValues.isTrue(scoreLock.getIsValid())){
                //生效，当前时间是否在范围内
                if(DateUtils.inIntervalDate(scoreLock.getStartDate(),scoreLock.getEndDate())){
                    scoreLockVal = true;
                }else {
                    scoreLockVal = false;
                }
            }else {
                scoreLockVal = false;
            }
        }
        return scoreLockVal;
    }
}
