package com.srs.comprehensive.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.exception.ServiceException;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Dto.CphProRankingDto;
import com.srs.comprehensive.domain.Vo.CphProRankingVo;
import com.srs.comprehensive.mapper.SrsClassMapper;
import com.srs.comprehensive.mapper.SrsStuYearMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.mapper.CphProRankingMapper;
import com.srs.comprehensive.service.ICphProRankingService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 平均学分绩总排名Service业务层处理
 *
 * @author srs
 * @date 2024-02-19
 */
@Service
public class CphProRankingServiceImpl extends ServiceImpl<CphProRankingMapper, CphProRanking> implements ICphProRankingService {
    @Autowired
    private CphProRankingMapper cphProRankingMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;
    @Autowired
    public SrsClassMapper srsClassMapper;
    @Autowired
    public SysUserMapper sysUserMapper;
    @Autowired
    public SrsStudentMapper srsStudentMapper;
    @Autowired
    public SrsStuYearMapper srsStuYearMapper;

    @Override
    public AjaxResult doImport(List<CphProRanking> param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {

            List<CphProRanking> needUpdateList = new ArrayList<>();
            List<CphProRanking> needInsertList = new ArrayList<>();
            List<String> stuNos = new ArrayList<>();
            param.forEach(x -> {
                stuNos.add(x.getStuNo());
            });
            QueryWrapper<CphProRanking> cphProRankingQueryWrapper = new QueryWrapper<>();
            cphProRankingQueryWrapper.in("stu_no", stuNos)
                    .eq("stu_year_id",param.get(0).getStuYearId());

            List<CphProRanking> isExistList = cphProRankingMapper.selectList(cphProRankingQueryWrapper);
            List<String> isExistStuNos = new ArrayList<>();
            if (isExistList.size() != 0) {
                isExistList.forEach(
                        x -> {
                            String stuNo = x.getStuNo();
                            isExistStuNos.add(stuNo);
                            CphProRanking find = param.stream().filter(y -> Objects.equals(y.getStuNo(), stuNo)).findAny().orElse(null);
                            if (find != null) {
                                CphProRanking needUpdateTemp = new CphProRanking();
                                needUpdateTemp.setAvgCredit(find.getAvgCredit());
                                needUpdateTemp.setId(x.getId());
                                needUpdateTemp.setRanking(find.getRanking());
                                needUpdateTemp.setStuNo(find.getStuNo());
                                needUpdateTemp.setStuYearId(find.getStuYearId());
                                needUpdateTemp.setTotalCredit(find.getTotalCredit());
                                needUpdateTemp.setCourseCredit(find.getCourseCredit());
                                needUpdateTemp.setCourseNum(find.getCourseNum());
                                needUpdateTemp.setAvgScore(find.getAvgScore());
                                needUpdateTemp.setNopass(find.getNopass());
                                needUpdateTemp.setTotalScore(find.getTotalScore());
                                needUpdateList.add(needUpdateTemp);
                            }
                        }
                );
            }

            if (isExistList.size() == 0) {
                needInsertList = param;
            } else {
                needInsertList = param.stream().filter(x -> !isExistStuNos.contains(x.getStuNo())).collect(Collectors.toList());
            }

            if (needUpdateList.size() != 0) {
                boolean res =this.updateBatchById(needUpdateList);
                if(!res){
                    throw new Exception("批量更新数据失败");
                }
            }

            if (needInsertList.size() != 0) {
                boolean res = this.saveBatch(needInsertList);
                if(!res){
                    throw new Exception("批量插入数据失败");
                }
            }

            transactionManager.commit(status);
            return AjaxResult.success("操作成功");
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }

    /**
     * 查询平均学分绩总排名
     *
     * @param id 平均学分绩总排名主键
     * @return 平均学分绩总排名
     */
    @Override
    public CphProRanking selectCphProRankingById(Long id) {
        return cphProRankingMapper.selectCphProRankingById(id);
    }

    /**
     * 查询平均学分绩总排名列表
     *
     * @param cphProRanking 平均学分绩总排名
     * @return 平均学分绩总排名
     */
    @Override
    public List<CphProRanking> selectCphProRankingList(CphProRanking cphProRanking) {
        return cphProRankingMapper.selectCphProRankingList(cphProRanking);
    }

    /**
     * 新增平均学分绩总排名
     *
     * @param cphProRanking 平均学分绩总排名
     * @return 结果
     */
    @Override
    public int insertCphProRanking(CphProRanking cphProRanking) {
        return cphProRankingMapper.insertCphProRanking(cphProRanking);
    }

    /**
     * 修改平均学分绩总排名
     *
     * @param cphProRanking 平均学分绩总排名
     * @return 结果
     */
    @Override
    public int updateCphProRanking(CphProRanking cphProRanking) {
        return cphProRankingMapper.updateCphProRanking(cphProRanking);
    }

    /**
     * 批量删除平均学分绩总排名
     *
     * @param ids 需要删除的平均学分绩总排名主键
     * @return 结果
     */
    @Override
    public int deleteCphProRankingByIds(Long[] ids) {
        return cphProRankingMapper.deleteCphProRankingByIds(ids);
    }

    /**
     * 删除平均学分绩总排名信息
     *
     * @param id 平均学分绩总排名主键
     * @return 结果
     */
    @Override
    public int deleteCphProRankingById(Long id) {
        return cphProRankingMapper.deleteCphProRankingById(id);
    }

    //    导入科学文化素质
    @Override
    public String importUser(List<CphProRankingDto> rankListDto, long operName) {
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<CphProRanking> cphProRankings = new ArrayList<>();
        int totalcount = rankListDto.size();
        int successcount = 0;
        int failcount = 0;
        Date nowdate = new java.util.Date();

        for (CphProRankingDto cphDto : rankListDto) {
            try {
                SrsStudent user = srsStudentMapper.selectSrsStudentByStuNo(cphDto.getStuNo());
                QueryWrapper<SrsClass> classQueryWrapper = new QueryWrapper<>();
                classQueryWrapper.eq("class_id", user.getClassId());
                SrsClass srsClass = srsClassMapper.selectOne(classQueryWrapper);
                QueryWrapper<CphProRanking> rankingQueryWrapper = new QueryWrapper<>();
                rankingQueryWrapper.eq("stu_no", cphDto.getStuNo()).eq("stu_year_id", cphDto.getStuYearId());
                CphProRanking existingRanking = cphProRankingMapper.selectOne(rankingQueryWrapper);

                if (user == null) {
                    failureMsg.append("学号:" + cphDto.getStuNo() + "不存在请检查" + "<br>");
                    failcount++;
                } else if (srsClass == null) {
                    failureMsg.append("学号:" + cphDto.getStuNo() + "的班级" + cphDto.getClassName() + "不存在请检查" + "<br>");
                    failcount++;
                } else if (existingRanking != null) {
                    failureMsg.append("学号:" + cphDto.getStuNo() + "在该学年已存在数据" + "<br>");
                    failcount++;
                } else {
                    CphProRanking ranking = new CphProRanking();
                    ranking.setStuNo(cphDto.getStuNo());
                    ranking.setClassId(srsClass.getClassId());
                    ranking.setClassCode(srsClass.getClassCode());
                    ranking.setStuYearId(cphDto.getStuYearId());
                    ranking.setCourseCredit(cphDto.getCourseCredit());
                    ranking.setTotalCredit(cphDto.getTotalCredit());
                    ranking.setTotalScore(cphDto.getTotalScore());
                    ranking.setCourseNum(cphDto.getCourseNum());
                    ranking.setRanking(cphDto.getRanking());
                    ranking.setAvgCredit(cphDto.getAvgCredit());
                    ranking.setAvgScore(cphDto.getAvgScore());
                    ranking.setNopass(cphDto.getNopass());
                    ranking.setCreateBy(operName);
                    ranking.setCreateDate(nowdate);
                    ranking.setStatus(0L);

                    cphProRankings.add(ranking);
                    successcount++;
                }
            } catch (Exception e) {
                String msg = "<br/>" + "学号 " + cphDto.getStuNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        int sums=0;
        try {
            if (!cphProRankings.isEmpty()) {
                // 批量插入操作
                sums= cphProRankingMapper.batchInsertCphProRanking(cphProRankings);
            }

            if (failcount > 0) {
                failureMsg.insert(0, "本次导入共" + totalcount + "条，很抱歉，导入失败！共 " + failcount + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            } else {
                successMsg.insert(0, "本次导入共" + totalcount + "条，恭喜您，数据已导入成功！共 " + successcount + " 条导入成功"+sums);
            }
        } catch (Exception e) {
            failureMsg.insert(0, "批量插入数据时发生错误：" + e.getMessage());
            log.error("批量插入数据时发生错误", e);
            throw new ServiceException(failureMsg.toString());
        }

        return successMsg.toString();

    }
//导入模板
    @Override
    public List<CphProRankingVo> getRankinginfo(CphProRanking cphProRanking) {
        List<CphProRanking> rankingList=cphProRankingMapper.selectCphProRankingList(cphProRanking);
        List<CphProRankingVo> rankingVoList=new ArrayList<>();
        for (CphProRanking ranking : rankingList) {
            SrsClass srsClass=srsClassMapper.selectSrsClassByClassCode(ranking.getClassCode());
            SrsStudent student=srsStudentMapper.selectSrsStudentByStuNo(ranking.getStuNo());
            SrsStuYear stuYear=srsStuYearMapper.selectSrsStuYearById(ranking.getStuYearId());
            CphProRankingVo rank=new CphProRankingVo();
            rank.setStuNo(ranking.getStuNo());
            rank.setXsxm(student.getName());
            rank.setClassName(srsClass.getClassName());
            rank.setCourseCredit(ranking.getCourseCredit());
            rank.setTotalCredit(ranking.getTotalCredit());
            rank.setTotalScore(ranking.getTotalScore());
            rank.setCourseNum(ranking.getCourseNum());
            rank.setAvgScore(ranking.getAvgScore());
            rank.setAvgCredit(ranking.getAvgCredit());
            rank.setRanking(ranking.getRanking());
            rank.setNopass(ranking.getNopass());
            if (stuYear!=null){
                rank.setStuYearName(stuYear.getStuYearName());
            }
            else {
                rank.setStuYearName("未知");
            }
            rankingVoList.add(rank);
        }
        return rankingVoList;
    }

    @Override
    public List<CphProRank> getRankList(CphProRank cphProRanking) {
        return  cphProRankingMapper.getRankList(cphProRanking);
    }
}
