package com.ruoyi.mall.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CountDownLatch;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.MallAcceptRateSetting;
import com.ruoyi.mall.domain.MallMemberUser;
import com.ruoyi.mall.domain.Vo.MajorItemVo;
import com.ruoyi.mall.domain.Vo.ReportIntelligenceVo;
import com.ruoyi.mall.mapper.MallAcceptRateSettingMapper;
import com.ruoyi.mall.mapper.MallSchoolTagMapper;
import com.ruoyi.mall.service.IMallCountMethodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.mapper.ReportIntelligenceMapper;
import com.ruoyi.mall.domain.ReportIntelligence;
import com.ruoyi.mall.service.IReportIntelligenceService;

import javax.annotation.Resource;

/**
 * 志愿报告条目Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-28
 */
@Service
public class ReportIntelligenceServiceImpl implements IReportIntelligenceService
{
    @Resource
    private ReportIntelligenceMapper reportIntelligenceMapper;
    @Resource
    private MallSchoolTagMapper mallSchoolTagMapper;
    @Resource
    private MallAcceptRateSettingMapper mallAcceptRateSettingMapper;
    @Resource
    private IMallCountMethodService mallCountMethodService;

    /**
     * 查询志愿报告条目
     *
     * @param itemId 志愿报告条目主键
     * @return 志愿报告条目
     */
    @Override
    public ReportIntelligence selectReportIntelligenceByItemId(Long itemId)
    {
        return reportIntelligenceMapper.selectReportIntelligenceByItemId(itemId);
    }

    /**
     * 查询志愿报告条目列表
     *
     * @param reportIntelligence 志愿报告条目
     * @return 志愿报告条目
     */
    @Override
    public List<ReportIntelligence> selectReportIntelligenceList(ReportIntelligence reportIntelligence)
    {
        return reportIntelligenceMapper.selectReportIntelligenceList(reportIntelligence);
    }

    /**
     * 查询志愿条目展示列表
     * 用于 xcx 报告 志愿详情列表
     */
    @Override
    public List<ReportIntelligenceVo> selectReportItemVoList(ReportIntelligence reportIntelligence, MallMemberUser user) {
        //目标报告 条目列表
        List<ReportIntelligenceVo> vos = reportIntelligenceMapper.selectReportItemVoList(reportIntelligence);
        // 遍历 填充数据
        if (!vos.isEmpty()){
            CountDownLatch countDownLatch = new CountDownLatch(vos.size());
            try {
                for (ReportIntelligenceVo vo : vos) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            computAcceptRate(vo,user);
                            countDownLatch.countDown();
                        }
                    }).start();

                }

                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return vos;
    }

    @Async
    public void computAcceptRate(ReportIntelligenceVo vo,MallMemberUser user){
        //填充学校标签
        if (StringUtils.isNotBlank(vo.getTags())) {
            List<String> list = mallSchoolTagMapper.selectTagByTagId(vo.getTags());
            vo.setTagList(list);
        }
        Map<String, Object> result = new HashMap<>();
        //计算录取率
        if (vo.getBatchId() == 4L){
            // 专科
            if (vo.getAcceptLowest() != null){
                result = mallCountMethodService.zhuankegetAcceptRateForReport(BigDecimal.valueOf(vo.getAcceptLowest()), vo.getAcceptRuleId(),  user.getCultureScore(),user.getMajorScore());

            }else{
                result.put("acceptRate", BigDecimal.ZERO);
                result.put("rateType", -2);
            }
        }else{
            // 本科
            if (vo.getReference() != null){
                result = mallCountMethodService.getAcceptRateForReport(vo.getReference(), vo.getAcceptRuleId(),  user.getCultureScore(),user.getMajorScore());

            }else{
                result.put("acceptRate", BigDecimal.ZERO);
                result.put("rateType", -2);
            }
        }

        if (!result.isEmpty() && new BigDecimal(result.get("acceptRate").toString()).compareTo(BigDecimal.ZERO) > 0 ){
            vo.setAcceptRate(new BigDecimal(result.get("acceptRate").toString()));
            vo.setShowAcceptRate(vo.getAcceptRate() + "%");
            vo.setRateType((Integer)result.get("rateType"));
        }else{
            vo.setAcceptRate(new BigDecimal("0"));
            vo.setShowAcceptRate("0");
            vo.setRateType(-2);
        }
        // 计算已填报人数
        ReportIntelligence en = BeanUtil.toBean(vo,ReportIntelligence.class);
        en.setUserId(user.getId());
        en.setSubjectType(user.getSubjectType());
        List<MajorItemVo> reportNum = reportIntelligenceMapper.reportNum(en);
        //计算录取率 再 count 录取率比用户大的 人数
        if(null != vo.getAcceptRuleId()){
            int num = 0;
            for (MajorItemVo majorItemVo : reportNum) {
                compareAcceptRate(majorItemVo,num,vo,user);

            }
            vo.setReportNum(num);
        }
        else{
            vo.setReportNum(reportNum.size());
        }

    }
    @Async
    public void compareAcceptRate(MajorItemVo majorItemVo,int num,ReportIntelligenceVo vo,MallMemberUser user){
        if(majorItemVo.getCultureScore() > user.getCultureScore() && majorItemVo.getMajorScore() > user.getMajorScore()){
            num+=1;
        }
        else{
            // 专业录取率
            Map<String, Object> acceptRate =  new HashMap<>();
            if (null != vo.getReference()){
                 acceptRate = mallCountMethodService.getAcceptRateForReport(vo.getReference(),vo.getAcceptRuleId(), majorItemVo.getCultureScore(),majorItemVo.getMajorScore());

            }else{
                acceptRate.put("acceptRate", 0);
                acceptRate.put("rateType", -2);
            }
             if (!acceptRate.isEmpty() && new BigDecimal(acceptRate.get("acceptRate").toString()).compareTo(BigDecimal.ZERO) > 0 ){
                majorItemVo.setAcceptRate(new BigDecimal(acceptRate.get("acceptRate").toString()));
                //if 当前报名用户的录取率 小于等于 历史报名用户
                if(vo.getAcceptRate().compareTo(majorItemVo.getAcceptRate())<1){
                    num+=1;
                }
            }
        }
    }

    /**
     * 新增志愿报告条目
     *
     * @param reportIntelligence 志愿报告条目
     * @return 结果
     */
    @Override
    public int insertReportIntelligence(ReportIntelligence reportIntelligence)
    {
        reportIntelligence.setCreateTime(DateUtils.getNowDate());
        return reportIntelligenceMapper.insertReportIntelligence(reportIntelligence);
    }

    @Override
    public int insertBatch(List<ReportIntelligenceVo> reportIntelligence) {
        return reportIntelligenceMapper.insertBatch(reportIntelligence);
    }

    /**
     * 修改志愿报告条目
     *
     * @param reportIntelligence 志愿报告条目
     * @return 结果
     */
    @Override
    public int updateReportIntelligence(ReportIntelligence reportIntelligence)
    {
        reportIntelligence.setUpdateTime(DateUtils.getNowDate());
        return reportIntelligenceMapper.updateReportIntelligence(reportIntelligence);
    }

    /** 批量更新志愿条目sort by itemId
     *
     * @param update
     * @return
     */
    @Override
    public int updateItemsSortByItemIds(List<ReportIntelligence> update) {
        return reportIntelligenceMapper.updateItemsSortByItemIds(update);
    }

    /**
     * 批量删除志愿报告条目
     *
     * @param itemIds 需要删除的志愿报告条目主键
     * @return 结果
     */
    @Override
    public int deleteReportIntelligenceByItemIds(Long[] itemIds)
    {
        return reportIntelligenceMapper.deleteReportIntelligenceByItemIds(itemIds);
    }

    /**
     * 删除志愿报告条目信息
     *
     * @param itemId 志愿报告条目主键
     * @return 结果
     */
    @Override
    public int deleteReportIntelligenceByItemId(Long itemId)
    {
        return reportIntelligenceMapper.deleteReportIntelligenceByItemId(itemId);
    }
}
