package com.srs.comprehensive.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.spi.CharsetProvider;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Dto.*;
import com.srs.comprehensive.domain.Vo.*;
import com.srs.comprehensive.mapper.*;
import com.srs.comprehensive.service.ICphGoodAuditService;
import com.srs.comprehensive.service.ICphOwnGoodTypeService;
import com.srs.comprehensive.service.ISrsStuYearService;
import com.srs.comprehensive.util.BeanCopyUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.service.ICphGoodApplyService;
import org.springframework.transaction.annotation.Transactional;

import javax.websocket.OnError;

import static com.srs.common.utils.DateUtils.getNowDate;
import static com.srs.common.utils.SecurityUtils.getLoginUser;
import static com.srs.common.utils.SecurityUtils.getUsername;

/**
 * 评优申请Service业务层处理
 *
 * @author srs
 * @date 2023-09-12
 */
@Service
public class CphGoodApplyServiceImpl extends ServiceImpl<CphGoodApplyMapper, CphGoodApply> implements ICphGoodApplyService {
    @Autowired
    private CphGoodApplyMapper cphGoodApplyMapper;

    @Autowired
    private CphGoodAuditMapper _cphGoodAuditMapper;
    @Autowired
    private CphCardersStudentMapper cphCardersStudentMapper;
    @Autowired
    private CphCardersMapper cphCardersMapper;
    @Autowired
    private SrsCqScoreMapper srsCqScoreMapper;
    @Autowired
    private CphOwnGoodTypeMapper cphOwnGoodTypeMapper;
    @Autowired
    private SrsStudentMapper srsStudentMapper;

    @Autowired
    private CphStuScoreMiddleDtoMapper cphStuScoreMiddleDtoMapper;

    @Autowired
    private CphGoodCancelLogMapper _logMapper;

    @Autowired
    private ICphGoodAuditService goodAuditService;

    @Autowired
    private ICphOwnGoodTypeService ownGoodTypeService;

    @Autowired
    private ISrsStuYearService stuYearService;

    @Autowired
    public CphScienceScoreMapper _scienceScoreMapper;

    @Autowired
    public SrsStuYearMapper _yearMapper;


    @Override
    public List<CphGoodAuditFdyVo> listFdyAudit(CphSearch param) {
        return cphGoodApplyMapper.listFdyAudit(param);
    }

    @Override
    public List<CphGoodApplyVo> importXyjxj(CphSearch param) {
        return cphGoodApplyMapper.importXyjxj(param);
    }

    @Override
    public List<String> countJwcUnDo(){
        return cphGoodApplyMapper.countJwcUnDo();
    }

    @Override
    public List<String> countXwUnDo(Long id){
        return cphGoodApplyMapper.countXwUnDo(id);
    }

    @Override
    public List<String> countFdyUnDo(String tNo){
        return cphGoodApplyMapper.countFdyUnDo(tNo);
    }

    @Override
    public List<String> countStuUnDo(String stuNo){
        return cphGoodApplyMapper.countStuUnDo(stuNo);
    }

    @Override
    public List<String> countSjUnDo(Long id){
        return cphGoodApplyMapper.countSjUnDo(id);
    }
    @Override
    public List<CphBiyeApplyVo> countBiyeYearDept(){
        return cphGoodApplyMapper.countBiyeYearDept();
    }



    @Override
    public List<CphGoodApplyVo> importShxs(CphSearch param) {
        return cphGoodApplyMapper.importShxs(param);
    }

    @Override
    public List<CphGoodApplyVo> importYxbg(CphSearch param) {
        return cphGoodApplyMapper.importYxbg(param);
    }


    @Override
    public List<CphGoodAuditFdyVo> listXwAudit(CphSearch param) {
        return cphGoodApplyMapper.listXwAudit(param);
    }


    @Override
    public List<CphGoodTypeCode> listXyjxjCanType() {
        return cphGoodApplyMapper.listXyjxjCanType();
    }

    @Override
    public List<CphTerm> listTermByYear(Long id) {
        return cphGoodApplyMapper.listTermByYear(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelOwnApply(CphCancel param) {
        try {
            if (param.reason == null || param.reason.equals("")) {
                throw new Exception("请填写原因");
            }

            Long id = param.id;
            String stuNo = getUsername();
            CphGoodApply f = cphGoodApplyMapper.selectCphGoodApplyById(id);
            if (!Objects.equals(f.getApplyStatus(), "1")) {
                throw new Exception("你想要做什么?");
            }
            if (!Objects.equals(f.getStuNo(), stuNo)) {
                throw new Exception("你是谁?");
            }

            int res1 = cphGoodApplyMapper.deleteCphGoodApplyById(id);
            if (res1 != 1) {
                throw new Exception("删除申请记录失败，刷新试试");
            }

            int res2 = _cphGoodAuditMapper.deleteCphGoodAuditByApplyId(id);

            if (res2 == 0) {
                throw new Exception("删除审核记录失败，刷新试试");
            }

            CphGoodCancelLog log = new CphGoodCancelLog();
            log.setReason(param.reason);
            log.setIp(getLoginUser().getIpaddr());
            log.setStuNo(f.getStuNo());
            log.setTypeCode(f.getTypeCode());
            log.setCreateBy(getUsername());
            log.setCreateTime(getNowDate());
            int res3 = _logMapper.insertCphGoodCancelLog(log);
            if (res3 == 0) {
                throw new Exception("插入取消记录失败，请联系管理员。");
            }

            return AjaxResult.success("已取消申请");
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public CphGoodApplyVo lookDetail(Long id) {
        return cphGoodApplyMapper.lookDetail(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult reApply(CphApplyXyjxj param) {
        try {
            String stuNo = getUsername();
            Long applyId = param.applyId;
            CphGoodApply needUpdate = cphGoodApplyMapper.selectCphGoodApplyById(applyId);
            if (needUpdate == null) {
                throw new Exception("需要更新的申请项为空，请联系管理员");
            }
            if (!Objects.equals(needUpdate.getApplyStatus(), "10")) {
                throw new Exception("这不是驳回的项");
            }
            needUpdate.setApplyStatus("14");
            int res1 = cphGoodApplyMapper.updateCphGoodApply(needUpdate);
            if (res1 == 1) {
                CphGoodApply cga = new CphGoodApply();
                cga.setStuNo(stuNo);
                cga.setZzmm(param.zzmm);
                cga.setBornTime(param.bornTime);

                cga.setClasstwoSure(param.classtwoSure);
                cga.setYouthPercent(param.youthPercent);

                cga.setTypeCode(param.typeCode);
                cga.setClassPost(param.classPost);
                cga.setBankCard(param.bankCard);
                cga.setBankAddr(param.bankAddr);
                cga.setGoodHis(param.goodHis);
                cga.setMainHis(param.mainHis);
                cga.setMaterial(param.material);
                cga.setApplyStatus("1");
                cga.setApplyTime(getNowDate());

                cga.setStatus("0");
                cga.setDelFlag("0");
                cga.setCreateBy(getUsername());
                cga.setCreateTime(getNowDate());

                int res2 = cphGoodApplyMapper.insertCphGoodApply(cga);

                if (res2 != 0) {
                    Long apply_id = cga.getId();

                    CphGoodAudit cphGoodAudit = new CphGoodAudit();
                    cphGoodAudit.setApplyId(apply_id);
                    cphGoodAudit.setStatus("0");
                    cphGoodAudit.setDelFlag("0");
                    cphGoodAudit.setCreateBy(getUsername());
                    cphGoodAudit.setCreateTime(getNowDate());

                    int res3 = _cphGoodAuditMapper.insertCphGoodAudit(cphGoodAudit);

                    if (res3 != 0) {
                        return AjaxResult.success("申请成功");
                    } else {
                        throw new Exception("添加审核记录失败,请联系管理员");
                    }

                } else {
                    throw new Exception("添加申请记录失败,请联系管理员");
                }

            } else {
                throw new Exception("更新原有状态失败");
            }
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult applyXyjxj(CphApplyXyjxj param) {
        try {
            String stuNo = getUsername();

            CphOwnGoodType toGetOnlyCode = cphOwnGoodTypeMapper.selectByCode(param.typeCode);
            String onlyCode = toGetOnlyCode.getOnlyCode();

            Long stuYearId = toGetOnlyCode.getStuYearId();

            SrsStuYear year = _yearMapper.selectSrsStuYearById(stuYearId);

            String xndm = year.xndm;

            QueryWrapper<CphScienceScore> scoreQuery = new QueryWrapper<>();
            scoreQuery.eq("stu_no", stuNo)
                    .eq("stu_year", xndm);
            List<CphScienceScore> scoreList = _scienceScoreMapper.selectList(scoreQuery);

            boolean hasUnPass = false;
            for (CphScienceScore score : scoreList) {
                if (score.getIsPass() == 0) {
                    hasUnPass = true;
                    break;
                }
            }
            if (hasUnPass) {
                throw new Exception("您当前学年有课程成绩未通过");
            }


            List<CphGoodApply> isApply = cphGoodApplyMapper.selectByOnlyCodeStuNo(onlyCode, stuNo);
            if (isApply.size() > 0) {
                return AjaxResult.error("您已经提交过一项了");
            }

            CphGoodApply cga = new CphGoodApply();
            cga.setStuNo(stuNo);
            cga.setZzmm(param.zzmm);
            cga.setBornTime(param.bornTime);
            cga.setTypeCode(param.typeCode);
            cga.setClassPost(param.classPost);
            cga.setBankCard(param.bankCard);
            cga.setBankAddr(param.bankAddr);
            cga.setGoodHis(param.goodHis);
            cga.setMainHis(param.mainHis);
            cga.setMaterial(param.material);
            cga.setApplyStatus("1");
            cga.setApplyTime(getNowDate());

            cga.setStatus("0");
            cga.setDelFlag("0");
            cga.setCreateBy(getUsername());
            cga.setCreateTime(getNowDate());

            int res1 = cphGoodApplyMapper.insertCphGoodApply(cga);

            if (res1 != 0) {
                Long apply_id = cga.getId();

                CphGoodAudit cphGoodAudit = new CphGoodAudit();
                cphGoodAudit.setApplyId(apply_id);
                cphGoodAudit.setStatus("0");
                cphGoodAudit.setDelFlag("0");
                cphGoodAudit.setCreateBy(getUsername());
                cphGoodAudit.setCreateTime(getNowDate());

                int res2 = _cphGoodAuditMapper.insertCphGoodAudit(cphGoodAudit);

                if (res2 != 0) {
                    return AjaxResult.success("申请成功");
                } else {
                    throw new Exception("添加审核记录失败,请联系管理员");
                }

            } else {
                throw new Exception("添加申请记录失败,请联系管理员");
            }
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public List<CphGoodApplyVo> listOwnXyjxjApply(String stuNo) {
        return cphGoodApplyMapper.listOwnXyjxjApply(stuNo);
    }

    @Override
    public List<CphClassRankScore> listOwnScoreClassRank(String stuNo) {
        return cphGoodApplyMapper.listOwnScoreClassRank(stuNo);
    }

    /**
     * 获取某学生指定学年的班级排名,是由前端查询的学年标签对应的学年
     * @param stuNo
     * @param tag
     * @return
     */
    @Override
    public List<CphClassRankScore> listOwnScoreClassRankByTag(String stuNo,String tag) {
        return cphGoodApplyMapper.listOwnScoreClassRankByTag(stuNo,tag);
    }

    @Override
    public CphClassRankScore getOwnRankByCode(CphSearch param) {
        return cphGoodApplyMapper.getOwnRankByCode(param);
    }


    //查询我的学年课程成绩
    @Override
    public List<CphCourseNameScore> listOwnYearCourseScore(String stuNo) {
        List<CphCourseNameScore> cphCourseNameScores = cphGoodApplyMapper.listOwnYearCourseScore(stuNo);
        for (CphCourseNameScore ccns : cphCourseNameScores) {
            if (Objects.equals(ccns.getFzlx(), "2")) {
                double num;
                try {
                    num = Double.parseDouble(ccns.getCourseScore());
                } catch (Exception e) {
                    continue;
                }
                if (num >= 90.00) {
                    ccns.setCourseScore("优秀");
                } else if (num >= 80.00) {
                    ccns.setCourseScore("良好");
                } else if (num >= 70.00) {
                    ccns.setCourseScore("中等");
                } else if (num >= 60.00) {
                    ccns.setCourseScore("及格");
                } else if (num < 60.00) {
                    ccns.setCourseScore("不及格");
                }
            }
        }
        return cphCourseNameScores;
    }

    @Override
    public List<CphCoursePassCount> countOwnPass(String stuNo) {
        return cphGoodApplyMapper.countOwnPass(stuNo);
    }

    @Override
    public List<CphIamSitCount> countOwnIam(String stuNo) {
        return cphGoodApplyMapper.countOwnIam(stuNo);
    }

    @Override
    public CphCoursePassCount getOwnPassCountByCode(String stuNo, String code) {
        return cphGoodApplyMapper.getOwnPassCountByCode(stuNo, code);
    }

    @Override
    public CphIamSitCount getOwnIamCountByCode(String stuNo, String code) {
        return cphGoodApplyMapper.getOwnIamCountByCode(stuNo, code);
    }


    /**
     * 查询评优申请
     *
     * @param id 评优申请主键
     * @return 评优申请
     */
    @Override
    public CphGoodApply selectCphGoodApplyById(Long id) {
        return cphGoodApplyMapper.selectCphGoodApplyById(id);
    }

    /**
     * 查询评优申请列表
     *
     * @param cphGoodApply 评优申请
     * @return 评优申请
     */
    @Override
    public List<CphGoodApply> selectCphGoodApplyList(CphGoodApply cphGoodApply) {
        return cphGoodApplyMapper.selectCphGoodApplyList(cphGoodApply);
    }

    /**
     * 新增评优申请
     *
     * @param cphGoodApply 评优申请
     * @return 结果
     */
    @Override
    public int insertCphGoodApply(CphGoodApply cphGoodApply) {
        cphGoodApply.setCreateTime(DateUtils.getNowDate());
        return cphGoodApplyMapper.insertCphGoodApply(cphGoodApply);
    }

    /**
     * 修改评优申请
     *
     * @param cphGoodApply 评优申请
     * @return 结果
     */
    @Override
    public int updateCphGoodApply(CphGoodApply cphGoodApply) {
        cphGoodApply.setUpdateTime(DateUtils.getNowDate());
        return cphGoodApplyMapper.updateCphGoodApply(cphGoodApply);
    }

    /**
     * 批量删除评优申请
     *
     * @param ids 需要删除的评优申请主键
     * @return 结果
     */
    @Override
    public int deleteCphGoodApplyByIds(Long[] ids) {
        return cphGoodApplyMapper.deleteCphGoodApplyByIds(ids);
    }

    /**
     * 删除评优申请信息
     *
     * @param id 评优申请主键
     * @return 结果
     */
    @Override
    public int deleteCphGoodApplyById(Long id) {
        return cphGoodApplyMapper.deleteCphGoodApplyById(id);
    }

    /**
     * 申请优秀干部
     *
     * @param cphApplyYxgb
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public AjaxResult applyYxgb(CphApplyYxgb cphApplyYxgb) {
        QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
        yearQuery.eq("status",1)
                .orderByDesc("id")
                .last("limit 1");
        SrsStuYear year = _yearMapper.selectOne(yearQuery);
        if(year == null){
            throw new RuntimeException("学年未开启");
        }

        QueryWrapper<CphOwnGoodType> typeQuery = new QueryWrapper<>();
        typeQuery.like("type_code","YXXSGB")
                .eq("stu_year_id",year.getId())
                .last("limit 1");
        CphOwnGoodType type = cphOwnGoodTypeMapper.selectOne(typeQuery);
        if(type==null){
            throw new RuntimeException("暂未开放申请优秀学生干部");
        }
        String typeCode = type.getTypeCode();


        String stuNo = getUsername();
        CphGoodApply check = null;
        check = lambdaQuery()
                .eq(CphGoodApply::getStuNo, stuNo)
                .eq(CphGoodApply::getTypeCode, typeCode)
                .eq(CphGoodApply::getApplyStatus, "1")
                .one();
        if (check != null) return AjaxResult.error("无法重复提交申请");
        check = lambdaQuery()
                .eq(CphGoodApply::getStuNo, stuNo)
                .eq(CphGoodApply::getTypeCode, typeCode)
                .eq(CphGoodApply::getApplyStatus, "10")
                .one();
        if (check != null) return AjaxResult.error("您有已被驳回的申请，请重新提交");
        //查找该学生个人信息
//        CphCardersStudent cphCardersStudent = new LambdaQueryChainWrapper<>(cphCardersStudentMapper)
//                .eq(CphCardersStudent::getStuNo, stuNo)
//                .one();
        QueryWrapper<ViewStuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        ViewStuInfo srsStudent = viewStuInfoMapper.selectOne(queryWrapper);

        CphSearch cphSearch = new CphSearch();
        cphSearch.setMajorId(srsStudent.getMajorId());
        cphSearch.setStuYearId(year.getId());
        //查询该学生所在专业的综合成绩情况
        List<CphTotalScoreInfo> cphTotalScoreInfoList = srsCqScoreMapper.listCphScore(cphSearch);
        CphTotalScoreInfo cphTotalScoreInfo = null;
        //查找该学生的综合成绩
        for (CphTotalScoreInfo info : cphTotalScoreInfoList) {
            if (info.stuNo.equals(stuNo)) {
                cphTotalScoreInfo = info;
                break;
            }
        }
        if (cphTotalScoreInfo == null) return AjaxResult.error("您的学号不存在，请联系管理员");
        //判断该学生体能素质成绩是否达到良好及以上
        if (cphTotalScoreInfo.sportScore.compareTo(new BigDecimal(80)) < 0) {
            return AjaxResult.error("您的体能素质没有达到良好或更高，无法申请优秀班干部");
        }
        //判断该学生第二课堂成绩是否达到优秀
//        if (cphTotalScoreInfo.classtwoScore.compareTo(new BigDecimal(90)) < 0) {
//            return AjaxResult.error("您的第二课堂成绩没有达到优秀，无法申请优秀班干部");
//        }
        //判断该学生综合成绩是否在专业前50%
        if (new BigDecimal(cphTotalScoreInfo.majorRank).divide(new BigDecimal(cphTotalScoreInfoList.size()), 1, RoundingMode.UP).compareTo(new BigDecimal("0.5")) > 0) {
            return AjaxResult.error("您的综合素质成绩专业排名没有达到前50%，无法申请优秀班干部");
        }
        // 各科平均成绩75分以上含70分
        List<CphStuScoreMiddleDto> cphStuScoreMiddleDtos = new LambdaQueryChainWrapper<>(cphStuScoreMiddleDtoMapper)
                .eq(CphStuScoreMiddleDto::getStuNo, stuNo)
                .eq(CphStuScoreMiddleDto::getXndm, year.xndm)
                .list();
        BigDecimal Grade = new BigDecimal(0);
        for (CphStuScoreMiddleDto cphStuScoreMiddleDto : cphStuScoreMiddleDtos) {
            if(cphStuScoreMiddleDto.getCj().equals("不及格")){
                throw new RuntimeException("有不及格成绩，无法申请");
            }
            if(cphStuScoreMiddleDto.getCj().equals("及格")){
                BigDecimal bigDecimal = new BigDecimal("60.00");
                Grade = Grade.add(bigDecimal);
            }else{
                BigDecimal bigDecimal = new BigDecimal(cphStuScoreMiddleDto.getCj());
                Grade = Grade.add(bigDecimal);
            }
        }
        if (Grade.divide(new BigDecimal(cphStuScoreMiddleDtos.size()), 2, RoundingMode.HALF_UP)
                .compareTo(new BigDecimal(70)) < 0) {
            return AjaxResult.error("学生各科平均成绩需要达到70分以上");
        }

        // 平均学分绩班级前40%
        //班级人数
        CphSearch cphSearch2 = new CphSearch();
        cphSearch2.setStuYearId(year.getId());
        List<Integer> classIdInfo = srsCqScoreMapper.cphTotalScoreClassIdInfo(stuNo);//班级id
        cphSearch2.setClassId(Long.valueOf(classIdInfo.get(0).toString()));
        List<CphTotalScoreInfo> cphTotalScoreInfos1 = srsCqScoreMapper.classData(cphSearch2);
        List<CphClassRankScore> cphClassRankScores = cphGoodApplyMapper.listOwnScoreClassRank(stuNo);
        BigDecimal size = new BigDecimal(cphTotalScoreInfos1.size());
        BigDecimal multiplier = new BigDecimal("0.45");
        BigDecimal v = size.multiply(multiplier);//计算排名前30%
        for (CphClassRankScore ccrs : cphClassRankScores) {
            BigDecimal bigDecimal = new BigDecimal(ccrs.stuClassRank);
            if (v.compareTo(bigDecimal) < 0) {
                throw new RuntimeException("平均学分绩排名没有达到45%");
            }
        }


//        CphCarders cphCarders = cphCardersMapper.selectById(cphCardersStudent.getCarderId());
        CphGoodApply cphGoodApply = new CphGoodApply();
        cphGoodApply.setStuNo(stuNo);
        cphGoodApply.setZzmm(cphApplyYxgb.getZzmm());
        cphGoodApply.setBornTime(cphApplyYxgb.getBornTime());
        cphGoodApply.setTypeCode(typeCode);
        cphGoodApply.setClassPost(cphApplyYxgb.getClassPost());
        cphGoodApply.setGoodHis(cphApplyYxgb.getGoodHis());
        cphGoodApply.setMainHis(cphApplyYxgb.getMainHis());
        cphGoodApply.setMaterial(cphApplyYxgb.getMaterial());
        cphGoodApply.setYouthPercent(cphApplyYxgb.getYouthPercent());
        cphGoodApply.setApplyStatus("1");
        cphGoodApply.setApplyTime(getNowDate());
        cphGoodApply.setClasstwoSure(cphApplyYxgb.getClasstwoSure());
        cphGoodApply.setStatus("0");
        cphGoodApply.setDelFlag("0");
        cphGoodApply.setCreateBy(getUsername());
        cphGoodApply.setCreateTime(getNowDate());

        int insert = cphGoodApplyMapper.insert(cphGoodApply);
        if (insert != 0) {
            Long apply_id = cphGoodApply.getId();

            CphGoodAudit cphGoodAudit = new CphGoodAudit();
            cphGoodAudit.setApplyId(apply_id);
            cphGoodAudit.setStatus("0");
            cphGoodAudit.setDelFlag("0");
            cphGoodAudit.setCreateBy(getUsername());
            cphGoodAudit.setCreateTime(getNowDate());

            int res2 = _cphGoodAuditMapper.insertCphGoodAudit(cphGoodAudit);

            if (res2 != 0) {
                return AjaxResult.success("申请成功");
            } else {
                throw new RuntimeException("添加审核记录失败,请联系管理员");
            }

        } else {
            throw new RuntimeException("添加申请记录失败,请联系管理员");
        }
    }

    //验证申请三好学生资格
    public boolean verifyApplySHXS() {
        String stuNo = getUsername();//用户
        /*QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
        yearQuery.eq("status", 1)
                .orderByDesc("id")
                .last("limit 1");
        SrsStuYear year = _yearMapper.selectOne(yearQuery);*/
        /*if(year == null){
            throw new RuntimeException("当前未开启学年");
        }*/

        /* 此处使用硬编码，请根据实际情况修改。
        当前功能是获取'评优评先---PYPS'标签对应的学年。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
        ---尽量避免学年标签字典的更改!!!! */
        //使用学年标签筛选学年
        String yearTag = "PYPS";//<---评优评先 学年标签
        List<SrsStuYear> yearList = _yearMapper.selectYearsByTag(yearTag);
        SrsStuYear year = yearList.get(0);
        if(!year.getModuleTags().contains("PYPS")){
            throw new RuntimeException("当前学年未关联到评优评先标签!");
        }
        //类型
        CphOwnGoodType cphOwnGoodType = new LambdaQueryChainWrapper<>(cphOwnGoodTypeMapper)
                .like(CphOwnGoodType::getTypeCode, "SHXS")
                .eq(CphOwnGoodType::getStuYearId,year.getId())
                .one();
        // 各科平均成绩75分以上含75分
        LambdaQueryWrapper<CphStuScoreMiddleDto> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CphStuScoreMiddleDto::getStuNo, stuNo);
        queryWrapper.eq(CphStuScoreMiddleDto::getXndm,year.getXndm());
        List<CphStuScoreMiddleDto> cphStuScoreMiddleDtos = cphStuScoreMiddleDtoMapper
                .selectList(queryWrapper);
        BigDecimal Grade = new BigDecimal(0);
        for (CphStuScoreMiddleDto cphStuScoreMiddleDto : cphStuScoreMiddleDtos) {
            if (cphStuScoreMiddleDto.getCj() == null
                    || Objects.equals(cphStuScoreMiddleDto.getCj(), "null")
                    || Objects.equals(cphStuScoreMiddleDto.getCj(), "")
                    || Objects.equals(cphStuScoreMiddleDto.getCj(), "NULL")) {
                continue;
            }
            if(cphStuScoreMiddleDto.getCj().equals("不及格")){
                throw new RuntimeException("有不及格成绩，无法申请");
            }
            if(cphStuScoreMiddleDto.getCj().equals("及格")){
                BigDecimal bigDecimal = new BigDecimal("60.00");
                Grade = Grade.add(bigDecimal);
            }else{
                BigDecimal bigDecimal = new BigDecimal(cphStuScoreMiddleDto.getCj());
                Grade = Grade.add(bigDecimal);
            }
        }
        if (Grade.divide(new BigDecimal(cphStuScoreMiddleDtos.size()), 2, RoundingMode.HALF_UP)
                .compareTo(new BigDecimal(75)) < 0) {
            throw new RuntimeException("学生各科平均成绩需要达到75分以上");
        }
        // 考察课中等及以上
        List<Map<String,Object>> cphStuScoreMiddleCjList = cphStuScoreMiddleDtoMapper
                .getCphStuScoreMiddleCjListMap(stuNo,year.getXndm());
        for (Map<String,Object> course : cphStuScoreMiddleCjList) {
            BigDecimal bigDecimal = new BigDecimal(course.get("cj").toString());
            if (bigDecimal.compareTo(new BigDecimal("70.00")) < 0) {
                if(course.get("course_name")!= null){
                    throw new RuntimeException("考查课"+course.get("course_name").toString()+"没有达到中等及以上");
                }else{
                    throw new RuntimeException("考查课没有达到中等及以上");
                }
            }
        }

        // 平均学分绩班级前30%
        //班级人数
        CphSearch cphSearch2 = new CphSearch();
        if (cphOwnGoodType != null) {
            cphSearch2.setStuYearId(cphOwnGoodType.getStuYearId());
        } else {
            throw new RuntimeException("没有该类型");
        }

        List<Integer> classIdInfo = srsCqScoreMapper.cphTotalScoreClassIdInfo(stuNo);//班级id
        cphSearch2.setClassId(Long.valueOf(classIdInfo.get(0).toString()));
        List<CphTotalScoreInfo> cphTotalScoreInfos1 = srsCqScoreMapper.classData(cphSearch2);
        //根据标签 PYPS 对应的学年获取班级排名
        List<CphClassRankScore> cphClassRankScores = cphGoodApplyMapper.listOwnScoreClassRankByTag(stuNo,yearTag);
        BigDecimal size = new BigDecimal(cphTotalScoreInfos1.size());
        BigDecimal multiplier = new BigDecimal("0.3");
        BigDecimal v = size.multiply(multiplier);//计算排名前30%
        for (CphClassRankScore ccrs : cphClassRankScores) {
            BigDecimal bigDecimal = new BigDecimal(ccrs.stuClassRank);
            if (v.compareTo(bigDecimal) < 0) {
                throw new RuntimeException("平均学分绩排名没有达到30%");
            }
        }

        // 学年综合素质测评班级排名前30%
        for (CphClassRankScore ccrs : cphClassRankScores) {
            BigDecimal bigDecimal = new BigDecimal(ccrs.cphClassRank);
            if (v.compareTo(bigDecimal) < 0) {
                throw new RuntimeException("学生学年综合素质测评班级排名需要达到前30%");
            }
        }

        // 体能考核成绩为良好及以上
        CphSearch cphSearch = new CphSearch();
        cphSearch.setStuYearId(cphOwnGoodType.getStuYearId());
        cphSearch.setStuNo(stuNo);
        //查询该学生所在专业的综合成绩情况
        List<CphTotalScoreInfo> cphTotalScoreInfoList = srsCqScoreMapper.listCphScore(cphSearch);//体能成绩
        //判断该学生体能素质成绩是否达到良好及以上
        if (cphTotalScoreInfoList.get(0).sportScore.compareTo(new BigDecimal(80)) < 0) {
            throw new RuntimeException("体能成绩没有达到良好及以上，无法申请");
        }

        return true;
    }

    //申请三好学生，遍历所有班级的所有校区，将其中符合申请条件的校区分配给该班级
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean applySHXS(CphApplySHXS cphApplySHXS) {
        /*QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
        yearQuery.eq("status","1")
                .last("limit 1");
        SrsStuYear year = _yearMapper.selectOne(yearQuery);
        if(year == null){
            throw new RuntimeException("当前未开启学年");
        }*/

        /* 此处使用硬编码，请根据实际情况修改。
        当前功能是获取'评优评先---PYPS'标签对应的学年。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
        ---尽量避免学年标签字典的更改!!!! */
        //使用学年标签筛选学年
        String yearTag = "PYPS";//<---评优评先 学年标签
        List<SrsStuYear> yearList = _yearMapper.selectYearsByTag(yearTag);
        SrsStuYear year = yearList.get(0);
        if(!year.getModuleTags().contains("PYPS")){
            throw new RuntimeException("当前学年未关联到评优评先标签!");
        }

        QueryWrapper<CphOwnGoodType> typeQuery = new QueryWrapper<>();
        typeQuery.eq("stu_year_id",year.getId())
                .like("type_code","SHXS")
                .last("limit 1");
        CphOwnGoodType type = cphOwnGoodTypeMapper.selectOne(typeQuery);
        if(type == null){
                throw new RuntimeException("当前学年未开启奖项申请");
        }

        cphApplySHXS.typeCode = type.getTypeCode();

        String stuNo = getUsername();//用户
        CphGoodApply check = lambdaQuery()
                .eq(CphGoodApply::getStuNo, stuNo)
                .eq(CphGoodApply::getTypeCode, cphApplySHXS.getTypeCode())
                .eq(CphGoodApply::getApplyStatus, "1")
                .one();
        if (check != null) throw new RuntimeException("无法重复提交申请");
        CphGoodApply checks = lambdaQuery()
                .eq(CphGoodApply::getStuNo, stuNo)
                .eq(CphGoodApply::getTypeCode, cphApplySHXS.getTypeCode())
                .eq(CphGoodApply::getApplyStatus, "10")
                .one();
        if (checks != null) throw new RuntimeException("您有已被驳回的申请，请重新提交");
        //类型
        CphOwnGoodType cphOwnGoodType = new LambdaQueryChainWrapper<>(cphOwnGoodTypeMapper)
                .eq(CphOwnGoodType::getTypeCode, type.getTypeCode())
                .one();
        // 各科平均成绩75分以上含75分
        LambdaQueryWrapper<CphStuScoreMiddleDto> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CphStuScoreMiddleDto::getStuNo, stuNo);
        queryWrapper.eq(CphStuScoreMiddleDto::getXndm, year.getXndm());
        List<CphStuScoreMiddleDto> cphStuScoreMiddleDtos = cphStuScoreMiddleDtoMapper
                .selectList(queryWrapper);
        BigDecimal Grade = new BigDecimal(0);
        for (CphStuScoreMiddleDto cphStuScoreMiddleDto : cphStuScoreMiddleDtos) {
            if (cphStuScoreMiddleDto.getCj() == null
                    || Objects.equals(cphStuScoreMiddleDto.getCj(), "null")
                    || Objects.equals(cphStuScoreMiddleDto.getCj(), "")
                    || Objects.equals(cphStuScoreMiddleDto.getCj(), "NULL")) {
                continue;
            }
            if(cphStuScoreMiddleDto.getCj().equals("不及格")){
                throw new RuntimeException("有不及格成绩，无法申请");
            }
            if(cphStuScoreMiddleDto.getCj().equals("及格")){
                BigDecimal bigDecimal = new BigDecimal("60.00");
                Grade = Grade.add(bigDecimal);
            }else{
                BigDecimal bigDecimal = new BigDecimal(cphStuScoreMiddleDto.getCj());
                Grade = Grade.add(bigDecimal);
            }
        }
        if (Grade.divide(new BigDecimal(cphStuScoreMiddleDtos.size()), 2, RoundingMode.HALF_UP)
                .compareTo(new BigDecimal(75)) < 0) {
            throw new RuntimeException("学生各科平均成绩需要达到75分以上");
        }
        // 考察课中等及以上
        List<String> cphStuScoreMiddleCjList = cphStuScoreMiddleDtoMapper
                .getCphStuScoreMiddleCjLists(stuNo,year.getXndm());

        for (String cj : cphStuScoreMiddleCjList) {
            BigDecimal bigDecimal = new BigDecimal(cj);
            if (bigDecimal.compareTo(new BigDecimal("70.00")) < 0) {
                throw new RuntimeException("考查课没有达到中等及以上");
            }
        }
        // 平均学分绩班级前30%
        //班级人数
        CphSearch cphSearch2 = new CphSearch();
        if (cphOwnGoodType != null) {
            cphSearch2.setStuYearId(cphOwnGoodType.getStuYearId());
        } else {
            throw new RuntimeException("没有该类型");
        }
        List<Integer> classIdInfo = srsCqScoreMapper.cphTotalScoreClassIdInfo(stuNo);//班级id
        cphSearch2.setClassId(Long.valueOf(classIdInfo.get(0).toString()));
        List<CphTotalScoreInfo> cphTotalScoreInfos1 = srsCqScoreMapper.classData(cphSearch2);
        //根据学年标签 PYPS 查询排名
        List<CphClassRankScore> cphClassRankScores = cphGoodApplyMapper.listOwnScoreClassRankByTag(stuNo,yearTag);
        BigDecimal size = new BigDecimal(cphTotalScoreInfos1.size());
        BigDecimal multiplier = new BigDecimal("0.3");
        BigDecimal v = size.multiply(multiplier);//计算排名前30%
        for (CphClassRankScore ccrs : cphClassRankScores) {
            BigDecimal bigDecimal = new BigDecimal(ccrs.stuClassRank);
            if (v.compareTo(bigDecimal) < 0) {
                throw new RuntimeException("平均学分绩排名没有达到30%");
            }
        }
        // 学年综合素质测评班级排名前30%
        for (CphClassRankScore ccrs : cphClassRankScores) {
            BigDecimal bigDecimal = new BigDecimal(ccrs.cphClassRank);
            if (v.compareTo(bigDecimal) < 0) {
                throw new RuntimeException("学生学年综合素质测评班级排名需要达到前30%");
            }
        }

        // 体能考核成绩为良好及以上
        CphSearch cphSearch = new CphSearch();
        cphSearch.setStuYearId(cphOwnGoodType.getStuYearId());
        cphSearch.setStuNo(stuNo);
        //查询该学生所在专业的综合成绩情况
        List<CphTotalScoreInfo> cphTotalScoreInfoList = srsCqScoreMapper.listCphScore(cphSearch);//体能成绩
        //判断该学生体能素质成绩是否达到良好及以上
        if (cphTotalScoreInfoList.get(0).sportScore.compareTo(new BigDecimal(80)) < 0) {
            throw new RuntimeException("体能成绩没有达到良好及以上，无法申请");
        }
        // 学年综合素质测评班级排名前30%
//            CphSearch cphSearch1 = new CphSearch();
//            cphSearch1.setStuYearId(cphOwnGoodType.getStuYearId());
//            cphSearch1.setClassId(Long.valueOf(classIdInfo.get(0).toString()));
//            List<CphTotalScoreInfo> cphTotalScoreInfos = srsCqScoreMapper.listCphScore30(cphSearch1);//所有综合素质测评排名前30
//            boolean control = false;
//            for (CphTotalScoreInfo cphGoodApply : cphTotalScoreInfos) {
//                if (Objects.equals(cphGoodApply.stuNo, stuNo)) {
//                    control = false;
//                    break;
//                }
//                control = true;
//            }
//            if (control) {
//                throw new RuntimeException("学生学年综合素质测评班级排名需要达到前30%");
//            }
        try {
            CphGoodApply cphGoodApply = new CphGoodApply();//申请表

            cphGoodApply.setClasstwoSure(cphApplySHXS.getClasstwoSure());
            cphGoodApply.setYouthPercent(cphApplySHXS.getYouthPercent());

            cphGoodApply.setStuNo(stuNo);
            cphGoodApply.setZzmm(cphApplySHXS.getZzmm());
            cphGoodApply.setBornTime(cphApplySHXS.getBornTime());
            cphGoodApply.setTypeCode(type.getTypeCode());
            cphGoodApply.setClassPost(cphApplySHXS.getClassPost());
            cphGoodApply.setGoodHis(cphApplySHXS.getGoodHis());
            cphGoodApply.setMainHis(cphApplySHXS.getMainHis());
            cphGoodApply.setMaterial(cphApplySHXS.getMaterial());
            cphGoodApply.setApplyStatus("1");
            cphGoodApply.setApplyTime(DateUtils.getNowDate());
            cphGoodApply.setStatus("0");
            cphGoodApply.setDelFlag("0");
            cphGoodApply.setCreateBy(stuNo);
            cphGoodApply.setCreateTime(DateUtils.getNowDate());
            int i = cphGoodApplyMapper.insertCphGoodApply(cphGoodApply);
            if (i > 0) {
                CphGoodAudit cphGoodAudit = new CphGoodAudit();//审核表
                cphGoodAudit.setApplyId(cphGoodApply.getId());
                cphGoodAudit.setFdyStatus("1");
                cphGoodAudit.setDeptStatus("1");
                cphGoodAudit.setFinalStatus("1");
                cphGoodAudit.setStatus("0");
                cphGoodAudit.setDelFlag("0");
                cphGoodAudit.setCreateBy(stuNo);
                cphGoodAudit.setCreateTime(getNowDate());
                int i1 = _cphGoodAuditMapper.insertCphGoodAudit(cphGoodAudit);
                if (i1 == 0) {
                    //cphGoodApplyMapper.deleteCphGoodApplyById(cphGoodApply.getId());//没有加进去则删除申请信息
                    throw new RuntimeException("添加审核记录失败,请联系管理员");
                }
            } else {
                throw new RuntimeException("添加申请失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("未知错误，请联系管理员");
        }
        return true;
    }

    //查询我的申请
    public List<Map<String, Object>> getGrades() {
        CphGoodApply cphGoodApply = new CphGoodApply();
        cphGoodApply.setStuNo(getUsername());
        List<Map<String, Object>> grades = cphGoodApplyMapper.getGrades(cphGoodApply);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Map<String, Object> grade : grades) {
            grade.put("applyTime", sdf.format(grade.get("applyTime")));
        }
        return grades;
    }

    @Override
    public AjaxResult getApplyYxgb() {
        String username = getUsername();
        List<ApplyYxgbVo> applyYxgbVos = cphGoodApplyMapper.getMyApply(username);
        return AjaxResult.success(applyYxgbVos);
    }

    @Transactional
    @Override
    public AjaxResult deleteYxgb(List<Long> ids) {
        boolean removeApply = removeBatchByIds(ids);
        boolean removeAudit = new LambdaUpdateChainWrapper<>(_cphGoodAuditMapper)
                .in(CphGoodAudit::getApplyId, ids)
                .remove();
        if (!removeApply || !removeAudit) {
            throw new RuntimeException("删除失败");
        }
        return AjaxResult.success();
    }


    @Autowired
    private ViewStuInfoMapper  viewStuInfoMapper;

    /**
     * 验证优秀干部申请
     * @return
     */
    @Override
    public AjaxResult verifyApplyYXGB() {
        /*QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
        yearQuery.eq("status","1")
                .last("limit 1");
        SrsStuYear year = _yearMapper.selectOne(yearQuery);
        if(year == null){
            throw new RuntimeException("当前未开启学年");
        }*/
        /* 此处使用硬编码，请根据实际情况修改。
        当前功能是获取'评优评先---PYPS'标签对应的学年。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
        ---尽量避免学年标签字典的更改!!!! */
        //使用学年标签筛选学年
        String yearTag = "PYPS";//<---评优评先 学年标签
        List<SrsStuYear> yearList = _yearMapper.selectYearsByTag(yearTag);
        SrsStuYear year = yearList.get(0);
        if(!year.getModuleTags().contains("PYPS")){
            throw new RuntimeException("当前学年未关联到评优评先标签!");
        }


        String stuNo = getUsername();
        //查找该学生个人信息
        CphOwnGoodType cphOwnGoodType = new LambdaQueryChainWrapper<>(cphOwnGoodTypeMapper)
                .eq(CphOwnGoodType::getStuYearId,year.getId())
                .like(CphOwnGoodType::getTypeCode, "YXXSGB")
                .one();
        QueryWrapper<ViewStuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo);
        ViewStuInfo srsStudent = viewStuInfoMapper.selectOne(queryWrapper);
        if (cphOwnGoodType == null) return AjaxResult.error("该学年对应的项目不存在或者未开放，请联系管理员");

        CphSearch cphSearch = new CphSearch();
        cphSearch.setMajorId(srsStudent.getMajorId());
        cphSearch.setStuYearId(cphOwnGoodType.getStuYearId());
        //查询该学生所在专业的综合成绩情况
        List<CphTotalScoreInfo> cphTotalScoreInfoList = srsCqScoreMapper.listCphScore(cphSearch);
        CphTotalScoreInfo cphTotalScoreInfo = null;
        //查找该学生的综合成绩
        for (CphTotalScoreInfo info : cphTotalScoreInfoList) {
            if (info.stuNo.equals(stuNo)) {
                cphTotalScoreInfo = info;
                break;
            }
        }
        if (cphTotalScoreInfo == null) return AjaxResult.error("您的学号不存在，请联系管理员");
        //判断该学生体能素质成绩是否达到80分及以上
        if (cphTotalScoreInfo.sportScore.compareTo(new BigDecimal(80)) < 0) {
            return AjaxResult.error("您的体测分数没有达到80分");
        }
        // 各科平均成绩70分以上含70分
        List<CphStuScoreMiddleDto> cphStuScoreMiddleDtos = new LambdaQueryChainWrapper<>(cphStuScoreMiddleDtoMapper)
                .eq(CphStuScoreMiddleDto::getStuNo, stuNo)
                .list();
        BigDecimal Grade = new BigDecimal(0);
        for (CphStuScoreMiddleDto cphStuScoreMiddleDto : cphStuScoreMiddleDtos) {
            if(cphStuScoreMiddleDto.getCj().equals("不及格")){
                throw new RuntimeException("有不及格成绩，无法申请");
            }
            if(cphStuScoreMiddleDto.getCj().equals("及格")){
                BigDecimal bigDecimal = new BigDecimal("60.00");
                Grade = Grade.add(bigDecimal);
            }else{
                BigDecimal bigDecimal = new BigDecimal(cphStuScoreMiddleDto.getCj());
                Grade = Grade.add(bigDecimal);
            }
        }
        if (Grade.divide(new BigDecimal(cphStuScoreMiddleDtos.size()), 2, RoundingMode.HALF_UP)
                .compareTo(new BigDecimal(70)) < 0) {
            return AjaxResult.error("学生各科平均成绩需要达到70分以上");
        }
        // 平均学分绩班级前40%
        //班级人数
        CphSearch cphSearch2 = new CphSearch();
        cphSearch2.setStuYearId(cphOwnGoodType.getStuYearId());
        List<Integer> classIdInfo = srsCqScoreMapper.cphTotalScoreClassIdInfo(stuNo);//班级id
        cphSearch2.setClassId(Long.valueOf(classIdInfo.get(0).toString()));
        List<CphTotalScoreInfo> cphTotalScoreInfos1 = srsCqScoreMapper.classData(cphSearch2);
        //根据学年标签 PYPS 查询该班级的排名
        List<CphClassRankScore> cphClassRankScores = cphGoodApplyMapper.listOwnScoreClassRankByTag(stuNo,yearTag);
        BigDecimal size = new BigDecimal(cphTotalScoreInfos1.size());
        BigDecimal multiplier = new BigDecimal("0.40");
        BigDecimal v = size.multiply(multiplier);//计算排名前30%
        for (CphClassRankScore ccrs : cphClassRankScores) {
            BigDecimal bigDecimal = new BigDecimal(ccrs.stuClassRank);
            if (v.compareTo(bigDecimal) < 0) {
                throw new RuntimeException("平均学分绩排名没有达到40%");
            }
        }
        // 学年综合素质测评班级排名前50%
        BigDecimal multiplier1 = new BigDecimal("0.50");
        BigDecimal v1 = size.multiply(multiplier1);//计算排名前30%
        for (CphClassRankScore ccrs : cphClassRankScores) {
            BigDecimal bigDecimal = new BigDecimal(ccrs.cphClassRank);
            if (v1.compareTo(bigDecimal) < 0) {
                return AjaxResult.error("学生学年综合素质测评班级排名需要达到前50%");
            }
        }

        return AjaxResult.success("验证成功");
    }

    /**
     * 提交优秀干部申请
     * @param cphApplyYxgb
     * @return
     */
    @Transactional
    @Override
    public AjaxResult reApplyYxgb(CphApplyYxgb cphApplyYxgb) {
        /*QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
        yearQuery.eq("status",1)
                .orderByDesc("id")
                .last("limit 1");
        SrsStuYear year = _yearMapper.selectOne(yearQuery);*/
        /* 此处使用硬编码，请根据实际情况修改。
        当前功能是获取'评优评先---PYPS'标签对应的学年。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
        ---尽量避免学年标签字典的更改!!!! */
        //使用学年标签筛选学年
        String yearTag = "PYPS";//<---评优评先 学年标签
        List<SrsStuYear> yearList = _yearMapper.selectYearsByTag(yearTag);
        SrsStuYear year = yearList.get(0);
        if(!year.getModuleTags().contains("PYPS")){
            throw new RuntimeException("当前学年未关联到评优评先标签!");
        }


        QueryWrapper<CphOwnGoodType> typeQuery = new QueryWrapper<>();
        typeQuery.like("type_code","YXXSGB")
                .eq("stu_year_id",year.getId())
                .last("limit 1");
        CphOwnGoodType type = cphOwnGoodTypeMapper.selectOne(typeQuery);
        if(type==null){
            throw new RuntimeException("暂未开放申请优秀学生干部");
        }
        String typeCode = type.getTypeCode();

        String stuNo = SecurityUtils.getUsername();
        //查询被驳回的申请表
        CphGoodApply apply = getById(cphApplyYxgb.getApplyId());
        if (apply == null) return AjaxResult.error("申请表ID错误");
        if (!apply.getApplyStatus().equals("10") && !apply.getApplyStatus().equals("14"))
            return AjaxResult.error("该申请表没有被驳回");
        //修改被驳回的申请表的状态
        apply.setApplyStatus("14");
        boolean updateApply = updateById(apply);
        if (!updateApply) throw new RuntimeException("修改申请表状态失败");
        //添加新的申请表
        CphGoodApply cphGoodApply = new CphGoodApply();
        cphGoodApply.setStuNo(stuNo);
        cphGoodApply.setZzmm(cphApplyYxgb.getZzmm());
        cphGoodApply.setBornTime(cphApplyYxgb.getBornTime());
        cphGoodApply.setClasstwoSure(cphApplyYxgb.getClasstwoSure());
        cphGoodApply.setTypeCode(typeCode);
        cphGoodApply.setClassPost(apply.getClassPost());
        cphGoodApply.setGoodHis(cphApplyYxgb.getGoodHis());
        cphGoodApply.setMainHis(cphApplyYxgb.getMainHis());
        cphGoodApply.setYouthPercent(cphApplyYxgb.getYouthPercent());
        cphGoodApply.setMaterial(cphApplyYxgb.getMaterial());
        cphGoodApply.setApplyStatus("1");
        cphGoodApply.setApplyTime(getNowDate());
        cphGoodApply.setStatus("0");
        cphGoodApply.setDelFlag("0");
        cphGoodApply.setCreateBy(getUsername());
        cphGoodApply.setCreateTime(getNowDate());
        boolean saveApply = save(cphGoodApply);
        if (!saveApply) throw new RuntimeException("添加申请表失败");
        //添加审核记录
        CphGoodAudit cphGoodAudit = new CphGoodAudit();
        cphGoodAudit.setApplyId(cphGoodApply.getId());
        cphGoodAudit.setStatus("0");
        cphGoodAudit.setDelFlag("0");
        cphGoodAudit.setCreateBy(getUsername());
        cphGoodAudit.setCreateTime(getNowDate());
        int insertAudit = _cphGoodAuditMapper.insert(cphGoodAudit);
        if (insertAudit <= 0) throw new RuntimeException("添加审核记录失败");
        return AjaxResult.success();
    }
}
