package com.srs.comprehensive.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.utils.DateUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Vo.SreCourseScoreStudent;
import com.srs.comprehensive.domain.Vo.SrsCeScoreStudent;
import com.srs.comprehensive.domain.Vo.SrsCeScoreStudentStuYear;
import com.srs.comprehensive.mapper.*;
import com.srs.comprehensive.service.ICphTestForService;
import com.srs.comprehensive.service.ISrsCeScoreService;
import com.srs.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import static com.srs.common.utils.SecurityUtils.getUsername;

/**
 * 综合评价Service业务层处理
 * 
 * @author srs
 * @date 2023-06-28
 */
@Service
public class SrsCeScoreServiceImpl implements ISrsCeScoreService
{
    @Autowired
    private SrsCeScoreMapper srsCeScoreMapper;

    @Autowired
    private SrsStudentMapper srsStudentMapper;
    @Autowired
    private SrsAddRecordMapper srsAddRecordMapper;
    @Autowired
    private ICphTestForService cphTestForService;

    @Autowired
    private SysUserMapper sysUserMapper;

    //辅导员信息
    @Autowired
    private CphTeacherMapper cphTeacherMapper;

    @Autowired
    private SrsClassMapper srsClassMapper;

    /**
     * 查询综合评价
     * 
     * @param id 综合评价主键
     * @return 综合评价
     */
    @Override
    public SrsCeScore selectSrsCeScoreById(Long id)
    {
        return srsCeScoreMapper.selectSrsCeScoreById(id);
    }

    /**
     * 查询综合评价列表
     * 
     * @param srsCeScore 综合评价
     * @return 综合评价
     */
    @Override
    public List<SrsCeScore> selectSrsCeScoreList(SrsCeScore srsCeScore)
    {
        return srsCeScoreMapper.selectSrsCeScoreList(srsCeScore);
    }

    /**
     * 新增综合评价
     * 
     * @param srsCeScore 综合评价
     * @return 结果
     */
    @Override
    public int insertSrsCeScore(SrsCeScore srsCeScore)
    {
        srsCeScore.setCreateTime(DateUtils.getNowDate());
        return srsCeScoreMapper.insertSrsCeScore(srsCeScore);
    }

    /**
     * 修改综合评价
     * 
     * @param srsCeScore 综合评价
     * @return 结果
     */
    @Override
    public int updateSrsCeScore(SrsCeScore srsCeScore)
    {
        srsCeScore.setUpdateTime(DateUtils.getNowDate());
        return srsCeScoreMapper.updateSrsCeScore(srsCeScore);
    }

    /**
     * 批量删除综合评价
     * 
     * @param ids 需要删除的综合评价主键
     * @return 结果
     */
    @Override
    public int deleteSrsCeScoreByIds(Long[] ids)
    {
        return srsCeScoreMapper.deleteSrsCeScoreByIds(ids);
    }

    /**
     * 删除综合评价信息
     * 
     * @param id 综合评价主键
     * @return 结果
     */
    @Override
    public int deleteSrsCeScoreById(Long id)
    {
        return srsCeScoreMapper.deleteSrsCeScoreById(id);
    }

    /**
     *综合评价连表查询
     * @return 结果
     */
    @Override
    public List<SrsCeScoreStudentStuYear> SrsCeScoreStudentStuYear(SrsCeScore srsCeScore) {
        srsCeScore.setDelFlag("0");
        return srsCeScoreMapper.SrsCeScoreStudentStuYear(srsCeScore);
    }

    /**
     * 综合评价成绩导入
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertSrsCeScoreStudent(List<SrsCeScoreStudent> srsCeScoreStudentsS) {
        List<SrsCeScoreStudent> srsCeScoreStudents = srsCeScoreStudentsS.stream()
                .map(student -> {
                    student.setStuNo(student.getStuNo().trim());
                    return student;
                })
                .collect(Collectors.toList());//清空前后空格
        int number=0;
        StringBuilder error= new StringBuilder();
        //查询辅导员
        CphTeacher cphTeacher = cphTeacherMapper.searchTeacherByTno(getUsername());
        SysUser sysUser = sysUserMapper.selectUserByUserName(getUsername());
        if (!Objects.equals(sysUser.getUserName(), "admin")) {
            List<SrsStudent> srsStudentList = new ArrayList<>();//辅导员所带的学生
            //查询班级
            SrsClass srsClass = new SrsClass();
            srsClass.setTeacherId(cphTeacher.getTeacherId());
            List<SrsClass> srsClasses = srsClassMapper.selectSrsClassListTeacherId(srsClass);//班级
            //查询辅导员所带的班级学生
            for (SrsClass scs : srsClasses) {
                SrsStudent srsStudent = new SrsStudent();
                srsStudent.setClassId(scs.getClassId());
//                srsStudent.setStatus("01");
                //根据班级id查询学生
                List<SrsStudent> srsStudentList1 = srsStudentMapper.selectSrsStudentList(srsStudent);
                srsStudentList.addAll(srsStudentList1);
            }
            for (SrsCeScoreStudent scss : srsCeScoreStudents) {
                if (scss.getCeScore().compareTo(new BigDecimal(100))>0){
                    scss.setCeScore(new BigDecimal(100));
                }
                int i = 0;
                for (SrsStudent ssd : srsStudentList) {
                    if (Objects.equals(scss.getStuNo(), ssd.getStuNo())) {
                        i = 1;
                        break;
                    }
                }
                if (i == 0) {
                    error.append(scss.getStuNo()).append(",");
                }
            }
            if (!error.toString().equals("")) {
                throw new RuntimeException("表中的学号：" + error + "不是所带的学生，请删除后再尝试导入！");
            }
        }
        //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//标记为回滚状态
        for (SrsCeScoreStudent i:srsCeScoreStudents){
            //综合评价成绩
            SrsCeScore srsCeScore1 = new SrsCeScore();//综合评价
            SrsStudent srsStudent = srsStudentMapper.selectSrsStudentByStuNo(i.getStuNo());//查询学生信息
            srsCeScore1.setStuId(srsStudent.getStuId());//学生id
            srsCeScore1.setStuYearId(i.getStuYearId());//学年id
            List<SrsCeScore> srsCeScores = srsCeScoreMapper.selectSrsCeScoreListS(srsCeScore1);//查询综合评价表重复
            srsCeScore1.setCeScore(i.getCeScore());
            srsCeScore1.setStuNo(i.getStuNo());
            if (srsCeScores.size()==0){//判断综合评价表有没有重复的值
                srsCeScore1.setCreateBy(getUsername());
                srsCeScore1.setCreateTime(DateUtils.getNowDate());
                srsCeScoreMapper.insertSrsCeScore(srsCeScore1);//没有则添加
                //ifSrsAdd(srsAddRecord,srsAddRecords);
                number++;
                continue;
            }
            srsCeScore1.setUpdateBy(getUsername());
            srsCeScore1.setUpdateTime(DateUtils.getNowDate());
            srsCeScore1.setId(srsCeScores.get(0).getId());
            srsCeScoreMapper.updateSrsCeScore(srsCeScore1);//有则修改
            //ifSrsAdd(srsAddRecord,srsAddRecords);
            number++;
        }
        TransactionAspectSupport.currentTransactionStatus().flush();//手动提交事务
        //cphTotalScoreMapper.testFor(id);
        cphTestForService.testMethod(Math.toIntExact(srsCeScoreStudents.get(0).getStuYearId()));
        return number;
    }
    private void ifSrsAdd(SrsAddRecord srsAddRecord, List<SrsAddRecord> srsAddRecords){
        if (srsAddRecords.size()==0){
            //添加
            srsAddRecord.setCreateBy(getUsername());
            srsAddRecord.setCreateTime(DateUtils.getNowDate());
            srsAddRecordMapper.insertSrsAddRecord(srsAddRecord);
        }else {
            //修改加分记录表
            srsAddRecord.setUpdateBy(getUsername());
            srsAddRecord.setUpdateTime(DateUtils.getNowDate());
            srsAddRecord.setId(srsAddRecords.get(0).getId());
            srsAddRecordMapper.updateSrsAddRecord(srsAddRecord);
        }
    }

}
