package com.ruoyi.mall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.Vo.SchoolContrast;
import com.ruoyi.mall.mapper.BusinessTutorialMapper;
import com.ruoyi.mall.mapper.ContrastSchoolMapper;
import com.ruoyi.mall.mapper.MallAcceptRateSettingMapper;
import com.ruoyi.mall.mapper.MallSchoolAcceptMapper;
import com.ruoyi.mall.service.ContrastSchoolService;
import com.ruoyi.mall.service.IMallMemberUserService;
import com.ruoyi.system.service.ISysDictTypeService;
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.stream.Collectors;

@Service
public class ContrastSchoolServiceImpl implements ContrastSchoolService {
    @Resource
    private ContrastSchoolMapper contrastSchoolMapper;
    @Resource
    private ISysDictTypeService dictTypeService;
    @Resource
    private MallAcceptRateSettingMapper mallAcceptRateSettingMapper;
    @Resource
    private MallCountMethodServiceImpl mallCountMethodService;
    @Resource
    private IMallMemberUserService mallMemberUserService;
    @Resource
    private MallSchoolAcceptMapper mallSchoolAcceptMapper;

    /**
     *
     * @param schoolIds
     * @param batchId
     * @param memberId
     * @return
     */
    @Override
    public List<SchoolContrast> getSchoolContrastList(Long[] schoolIds, Long batchId ,Long memberId) {
        List<SchoolContrast> result = new ArrayList<>();
        MallMemberUser mallMemberUser = mallMemberUserService.selectMallMemberUserById(memberId);
        Integer cultureScore = mallMemberUser.getCultureScore();
        Integer majorScore = mallMemberUser.getMajorScore();
        String subjectType = mallMemberUser.getSubjectType();

        //查询学校最低学费 by schoolIds batchId
        List<MallAcceptPlan> schoolPriceList = contrastSchoolMapper.getSchoolPrice(schoolIds, batchId);
        //学校相关信息
        List<MallSchool> schoolList = contrastSchoolMapper.getSchoolList(schoolIds);
        //学校三年最低分
        List<MallSchoolAccept> mallSchoolAccepts = contrastSchoolMapper.getlAcceptLowest(schoolIds, batchId);
        //学校介绍 宿舍 食堂 图书馆 学风
        List<MallSchoolIntroduce> introduceList = contrastSchoolMapper.getIntroduceList(schoolIds);



        for (Long schoolId : schoolIds) {
            fillContrastInfo(result,schoolId,subjectType,batchId ,cultureScore,majorScore,schoolPriceList,schoolList,mallSchoolAccepts,introduceList);
        }

        return result;
    }
    @Async
    public void fillContrastInfo(List<SchoolContrast> result,Long schoolId,String subjectType, Long batchId ,Integer cultureScore,Integer majorScore,List<MallAcceptPlan> schoolPriceList,List<MallSchool> schoolList,List<MallSchoolAccept> mallSchoolAccepts,List<MallSchoolIntroduce> introduceList){
        SchoolContrast contrast = new SchoolContrast();
        contrast.setSchoolId(schoolId);
        // 学校录取率
        //fillAcceptRate(contrast,subjectType, batchId ,cultureScore,majorScore,schoolId);
        //查存 低学费
        if(null != schoolPriceList && schoolPriceList.size()>0) {
            Optional<MallAcceptPlan> first = schoolPriceList.stream().filter(o -> o.getSchoolId().longValue() == schoolId.longValue()).findFirst();
            if (first.isPresent()) {
                if(null != first.get().getSchoolPrice()) {
                    BigDecimal schoolPrice = first.get().getSchoolPrice();
                    contrast.setSchoolPrice(schoolPrice);
                }
            }
        }
        //查存 学校信息 学校名schoolName 男maleRatio女比率femaleRatio 城市cityName 保研率postgraduateRatio 转专业率changeMajorRatio
        fillSchoolInfo(contrast,schoolList,schoolId);
        //查存 学校三年最低分
        if(null != mallSchoolAccepts && mallSchoolAccepts.size()>0){
            Optional<MallSchoolAccept> schoolAccept = mallSchoolAccepts.stream().filter(o -> o.getSchoolId().longValue() == schoolId.longValue()).findFirst();
            //最低分
            if(schoolAccept.isPresent() && null != schoolAccept.get().getAcceptLowest()) {
                BigDecimal acceptLowest = schoolAccept.get().getAcceptLowest();
                contrast.setAcceptLowest(acceptLowest);
            }
        }
        //查存 学校介绍
        fillIntroduce(contrast,introduceList,schoolId);
        result.add(contrast);
    }
    @Async
    public void fillAcceptRate(SchoolContrast contrast,String subjectType, Long batchId ,Integer cultureScore,Integer majorScore,Long schoolId){

        if(null != cultureScore && null != majorScore){
            Map<String, Object> acceptRateMap = new HashMap<>();
            MallSchoolAccept mallSchoolAccept = mallSchoolAcceptMapper.selectMinReferenceBySchoolId(schoolId, batchId, subjectType);
            if (ObjectUtils.isNotEmpty(mallSchoolAccept)){
                 acceptRateMap = mallCountMethodService.getAcceptRateForReport(mallSchoolAccept.getReference(),  mallSchoolAccept.getAcceptRuleId(), cultureScore, majorScore);

            }else{
                acceptRateMap.put("acceptRate", 0);
                acceptRateMap.put("rateType", -2);
            }

            if (!acceptRateMap.isEmpty() && new BigDecimal(acceptRateMap.get("acceptRate").toString()).compareTo(BigDecimal.ZERO) > 0 ){
                BigDecimal acceptRate = new BigDecimal(acceptRateMap.get("acceptRate").toString());
                BigDecimal showAcceptRate = acceptRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP) ;
                //划分等级 schoolVO.setRateType((Integer)acceptRateMap.get("rateType"));
                if(null != showAcceptRate){
                    //划分等级
                    //contrast_level
                    //计算高中低
                    List<SysDictData> contrastLevel = getDictData("contrast_level");
                    String level = computelevel(contrastLevel, showAcceptRate)+"等";
                    contrast.setLevel(level);
                }
            }
        }
    }
    @Async
    public void fillSchoolInfo(SchoolContrast contrast,List<MallSchool> schoolList,Long schoolId){
        if(null != schoolList && schoolList.size()>0) {
            Optional<MallSchool> school = schoolList.stream().filter(o -> o.getSchoolId().longValue() == schoolId.longValue()).findFirst();
            if (school.isPresent()) {
                //学校名schoolName
                if(null != school.get().getSchoolName()) {
                    String schoolName = school.get().getSchoolName();
                    contrast.setSchoolName(schoolName);
                }
                //男maleRatio女比率femaleRatio
                if(null != school.get().getMaleRatio() && null != school.get().getFemaleRatio()) {
                    BigDecimal maleRatiob = school.get().getMaleRatio();
                    BigDecimal femaleRatiob = school.get().getFemaleRatio();
                    String femaleRatio = "男 " + maleRatiob.toString() + "% 女 " + femaleRatiob.toString() + "%";
                    contrast.setFemaleRatio(femaleRatio);
                }
                //城市cityName
                if(null != school.get().getCityName()) {
                    String cityName = school.get().getCityName();
                    contrast.setCityName(cityName);
                }
                //保研率postgraduateRatio
                if(null != school.get().getPostgraduateRatio()) {
                    BigDecimal postgraduateRatio = school.get().getPostgraduateRatio();
                    contrast.setPostgraduateRatio(postgraduateRatio);
                    //计算高中低
                    List<SysDictData> postgraduateRatio1 = getDictData("postgraduate_ratio");
                    String postgraduateLevel = computelevel(postgraduateRatio1, postgraduateRatio);
                    contrast.setPostgraduateLevel(postgraduateLevel);
                }
                //转专业率
                if(null != school.get().getChangeMajorRatio()) {
                    String changeMajorRatio = school.get().getChangeMajorRatio();
                    contrast.setChangeMajorRatio(changeMajorRatio);
                    //计算高中低
//                        List<SysDictData> changeMajorRatio1 = getDictData("change_major_ratio");
//                        String changeMajorLevel = computelevel(changeMajorRatio1, changeMajorRatio);
//                        contrast.setChangeMajorLevel(changeMajorLevel);
                }
                String excellent = null;
                //硕士点
                if(null != school.get().getMastersDegree()) {
                    Integer mastersDegree = school.get().getMastersDegree();
                    excellent = "硕士点 " + mastersDegree.toString() + "个,";
                }
                //博士点
                if(null != school.get().getDoctorate()) {
                    Integer doctorate = school.get().getDoctorate();
                    excellent = excellent + "博士点 "  + doctorate.toString() + "个,";
                }
                //优势专业
                if(null != school.get().getAce()) {
                    String ace = school.get().getAce();
                    excellent = excellent + ace;
                }
                contrast.setExcellent(excellent);
                //学校综合排名
                if(null != school.get().getRanking()){
                    String ranking = school.get().getRanking();
                    contrast.setRanking(ranking);
                }
                // 学科评估
                if (null != school.get().getContentOne()){
                    contrast.setContentOne(school.get().getContentOne());
                }
                // 专业评估
                if (null != school.get().getContentTwo()){
                    contrast.setContentTwo(school.get().getContentTwo());
                }
            }
        }
    }
    @Async
    public void fillIntroduce(SchoolContrast contrast,List<MallSchoolIntroduce> introduceList,Long schoolId){
        if(null != introduceList && introduceList.size()>0){
            //宿舍
            Optional<MallSchoolIntroduce> dorm = introduceList.stream().filter(o -> o.getSchoolId().longValue() == schoolId.longValue() && o.getIntroduceClassId().longValue() == 1L).findFirst();
            if(dorm.isPresent() && null != dorm.get().getContent()){
                contrast.setContentDorm(dorm.get().getContent());
            }
            //食堂
            Optional<MallSchoolIntroduce> eatery = introduceList.stream().filter(o -> o.getSchoolId().longValue() == schoolId.longValue() && o.getIntroduceClassId().longValue() == 4L).findFirst();
            if(eatery.isPresent() && null != eatery.get().getContent()){
                contrast.setContentEatery(eatery.get().getContent());
            }
            //图书馆
            Optional<MallSchoolIntroduce> library = introduceList.stream().filter(o -> o.getSchoolId().longValue() == schoolId.longValue() && o.getIntroduceClassId().longValue() == 5L).findFirst();
            if(library.isPresent() && null != library.get().getContent()){
                contrast.setContentLibrary(library.get().getContent());
            }
            //学风
            Optional<MallSchoolIntroduce> study = introduceList.stream().filter(o -> o.getSchoolId().longValue() == schoolId.longValue() && o.getIntroduceClassId().longValue() == 3L).findFirst();
            if(study.isPresent() && null != study.get().getContent()){
                contrast.setContentStudy(study.get().getContent());
            }
        }
    }
    /**查询字典值*/
    private List<SysDictData> getDictData(String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return data;
    }

    /** 计算 高中低*/
    private String computelevel(List<SysDictData> dictDataList,BigDecimal tag){
        //高
        SysDictData highDictData = dictDataList.get(0);
        String highValue = highDictData.getDictValue();
        //低
        SysDictData lowDictData = dictDataList.get(1);
        String lowValue = lowDictData.getDictValue();
        if(StringUtils.isNotBlank(highValue) && StringUtils.isNotBlank(lowValue)) {
            BigDecimal high = BigDecimal.valueOf(Long.valueOf(highValue));
            BigDecimal low = BigDecimal.valueOf(Long.valueOf(lowValue));
            if(null != tag && tag.compareTo(high) > -1){//a.b a>=b //高
                return "高";
            } else if (null != tag && tag.compareTo(low) > -1) {//中
                return "中";
            }else{//低
                return "低";
            }
        }else{
            return "-";
        }
    }
}
