package com.srs.comprehensive.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.srs.common.exception.ServiceException;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.listFunc;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Vo.CphClasstwoVo;
import com.srs.comprehensive.domain.Vo.CphScoreVo;
import com.srs.comprehensive.domain.Vo.SrsSportTestStudent;
import com.srs.comprehensive.domain.Vo.StuIdNo;
import com.srs.comprehensive.mapper.CphClasstwoMapper;
import com.srs.comprehensive.mapper.SrsAddRecordMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.comprehensive.mapper.SumClassTwoMapper;
import com.srs.comprehensive.service.ICphAuditDetailsService;
import com.srs.comprehensive.service.ICphClasstwoService;
import com.srs.comprehensive.service.ICphRulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 第二课堂Service业务层处理
 * 
 * @author zhy
 * @date 2023-07-03
 */
@Service
public class CphClasstwoServiceImpl implements ICphClasstwoService
{
    @Autowired
    private CphClasstwoMapper cphClasstwoMapper;
    @Autowired
    private SrsStudentMapper SrsStudentMapper;
    @Autowired
    private ICphRulesService _rulesService;
    @Autowired
    private ICphAuditDetailsService _auditService;
    //第二课堂中间表
    @Autowired
    private SumClassTwoMapper sumClassTwoMapper;
    //加分记录
    @Autowired
    private SrsAddRecordMapper srsAddRecordMapper;

    /**
     * 查询第二课堂
     * 
     * @param id 第二课堂主键
     * @return 第二课堂
     */
    @Override
    public CphClasstwo selectCphClasstwoById(Long id)
    {
        return cphClasstwoMapper.selectCphClasstwoById(id);
    }

    /**
     * 查询第二课堂列表
     *
     * @param cphClasstwo 第二课堂 连表查询
     * @return 第二课堂集合
     */
    @Override
    public List<CphClasstwo> selectCphClasstwoListJoin(CphClasstwo cphClasstwo) {


        List<CphClasstwo> cphClasstwos = cphClasstwoMapper.selectCphClasstwoListJoin(cphClasstwo);
//        for (CphClasstwo classtwo : cphClasstwos) {
//            SrsStudent srsStudent = SrsStudentMapper.selectSrsStudentByStuId(classtwo.getToAdd());
//            classtwo.setStudent(srsStudent);
//        }


        return cphClasstwos;
    }

    /**
     * 查询第二课堂列表
     * 
     * @param cphClasstwo 第二课堂
     * @return 第二课堂
     */
    @Override
    public List<CphClasstwo> selectCphClasstwoList(CphClasstwo cphClasstwo)
    {
        return cphClasstwoMapper.selectCphClasstwoList(cphClasstwo);
    }

    /**
     * 新增第二课堂
     * 
     * @param cphClasstwo 第二课堂
     * @return 结果
     */
    @Override
    public int insertCphClasstwo(CphClasstwo cphClasstwo)
    {
        cphClasstwo.setSubmitter(getUserId());
        cphClasstwo.setCreateBy(getUsername());
        cphClasstwo.setCreateTime(DateUtils.getNowDate());
        int res =  cphClasstwoMapper.insertCphClasstwo(cphClasstwo);
        long id = cphClasstwo.getId();
        CphRules rule = _rulesService.selectCphRulesByRuleId(cphClasstwo.getRuleId());

        /**
         *提交时同时添加到CphAuditDetails
         * @author zhy
         **/
        CphAuditDetails temp = new CphAuditDetails();
        temp.setProjectId(id);
        temp.setSubmitterId(getUserId());
        temp.setSubmitterId(getUserId());
        temp.setSubmitterName(getUsername());
        temp.setProjectName(rule.getRuleName());
        temp.setProjectTypeId(rule.getParentId());
        temp.setStatusCode( 1L );
        _auditService.insertCphAuditDetails(temp);

        return res;
    }

    /**
     * 修改第二课堂
     * 
     * @param cphClasstwo 第二课堂
     * @return 结果
     */
    @Override
    public int updateCphClasstwo(CphClasstwo cphClasstwo)
    {
        cphClasstwo.setUpdateTime(DateUtils.getNowDate());
        return cphClasstwoMapper.updateCphClasstwo(cphClasstwo);
    }

    /**
     * 批量删除第二课堂
     * 
     * @param ids 需要删除的第二课堂主键
     * @return 结果
     */
    @Override
    public int deleteCphClasstwoByIds(Long[] ids)
    {
        return cphClasstwoMapper.deleteCphClasstwoByIds(ids);
    }

    /**
     * 删除第二课堂信息
     * 
     * @param id 第二课堂主键
     * @return 结果
     */
    @Override
    public int deleteCphClasstwoById(Long id)
    {
        return cphClasstwoMapper.deleteCphClasstwoById(id);
    }
    /**
     * 中间表导入第二课堂
     */
    @Override
    public List<String> addSumClassTwo() {
        List<SumClassTwo> sumClassTwos = sumClassTwoMapper.selectSumClassTwoAll();//查询中间表
        // List<SumSportTest> sumSportTests = sumSportTestMapper.selectSumSportTestAll();
        List<String> strings = new ArrayList<>();
        if (sumClassTwos.size()==0){
            strings.add("没有要处理的数据");
            return strings;
        }
        CphClasstwo cphClasstwo = new CphClasstwo();
        //SrsSportTest srsSportTest = new SrsSportTest();
        try {
            for (SumClassTwo s: sumClassTwos) {
                SrsStudent srsStudent = SrsStudentMapper.selectSrsStudentByStuNo(s.getStuNo());//查询是否有对应的学生
                if (srsStudent==null){
                    strings.add(s.getStuNo());
                    continue;
                }
                cphClasstwo.setToAdd(srsStudent.getStuId());
                cphClasstwo.setClasstwoScore(s.getTotalScore());
                cphClasstwo.setStuYearId((long) s.getStuYearId());
                int i = cphClasstwoMapper.insertCphClasstwo(cphClasstwo);//添加到第二课堂
                //更新课程学习中间表读取记录
                if (i>0){
                    s.setChmodStatus("2");
                    s.setReadTime(DateUtils.getNowDate());
                    sumClassTwoMapper.updateSum(s);//更新中间表读写状态
                }
            }

        }catch (Exception e){
            strings.add("导入中断");
            return strings;
        }
        return strings;

    }

    //导入第二课堂
    @Transactional(rollbackFor = Exception.class)
    public boolean addSumClassAll(List<CphClasstwoVo> cphClasstwoVo){
        try{


            Long stuYearId = cphClasstwoVo.get(0).getStuYearId();
            List<String> allExportStuNo = new ArrayList<>();
            for (CphClasstwoVo i : cphClasstwoVo) {
                if (i.getStuNo() != null) {
                    allExportStuNo.add(i.getStuNo());
                }
            }
            List<CphScoreVo> temp1 = cphClasstwoMapper.listAllSportInfo(stuYearId);
            List<String> isExistStuNo = new ArrayList<>(); //已存在的学号
            for (CphScoreVo i : temp1) {
                if (i.getStuNo() != null) {
                    isExistStuNo.add(i.getStuNo());
                }
            }

            List<String> needInsertStuNo = listFunc.subList(allExportStuNo,isExistStuNo); //需要添加的学号
                 List<String> needUpdateStuNo = new ArrayList<>();
                Set<CphClasstwoVo> needUpdateList = new HashSet<>();
                if(needInsertStuNo.size() != allExportStuNo.size()){
                     needUpdateStuNo= listFunc.intersectList(allExportStuNo,isExistStuNo);
                    List<String> finalNeedUpdateStuNo = needUpdateStuNo;
                    needUpdateList = cphClasstwoVo.stream()
                            .filter(s -> finalNeedUpdateStuNo.contains(s.getStuNo())).collect(Collectors.toSet());//需要修改的学号
                }

            Set<CphClasstwoVo> needInsertList =cphClasstwoVo.stream()
                    .filter(s -> needInsertStuNo.contains(s.getStuNo())).collect(Collectors.toSet());



            String[] temp2 =  needInsertStuNo.toArray(new String[needInsertStuNo.size()]);
            String[] temp3 =  needUpdateStuNo.toArray(new String[needUpdateStuNo.size()]);

            List<StuIdNo> insertIds = new ArrayList<>();
            List<StuIdNo> updateIds = new ArrayList<>();

            if(temp2.length != 0){
                insertIds = cphClasstwoMapper.getStuIdByStuNosToInsert(temp2);
            }
            if(temp3.length != 0){
                updateIds = cphClasstwoMapper.getStuIdByStuNosToUpdate(temp3,stuYearId);
            }

            List<CphClasstwo> needInsertQuery = new ArrayList<>();
            List<CphClasstwo> needUpdateQuery = new ArrayList<>();

            for (CphClasstwoVo item:
                    needInsertList) {
                CphClasstwo temp = new CphClasstwo();
                temp.setClasstwoScore(item.getClasstwoScore());
                temp.setStuYearId(item.getStuYearId());
                String stu_no = item.getStuNo();
                StuIdNo nTemp = insertIds.stream()
                        .filter(x-> Objects.equals(x.stuNo, stu_no))
                        .findAny().orElse(null);
                temp.setAuditStatus("6");
                if(nTemp != null){
                    temp.setToAdd(nTemp.stuId);
                }
                temp.setStuNo(item.getStuNo());
                temp.setDelFlag("0");
                temp.setCreateTime(new Date());
                temp.setSubmitter(getUserId());
                temp.setCreateBy(getUsername());
                temp.setDescription("导入");
                needInsertQuery.add(temp);
            }

            for (CphClasstwoVo item:
                    needUpdateList) {
                CphClasstwo temp = new CphClasstwo();
                temp.setClasstwoScore(item.getClasstwoScore());
                temp.setStuYearId(item.getStuYearId());
                String stu_no = item.getStuNo();
                StuIdNo nTemp = updateIds.stream()
                        .filter(x-> Objects.equals(x.stuNo, stu_no))
                        .findAny().orElse(null);
                temp.setAuditStatus("6");
                if(nTemp != null){
                    temp.setId(nTemp.id);
                    temp.setToAdd(nTemp.stuId);
                }
                temp.setDelFlag("0");
                temp.setUpdateTime(new Date());
                temp.setSubmitter(getUserId());
                temp.setUpdateBy(getUsername());
                temp.setDescription("导入");
                needUpdateQuery.add(temp);
            }

        //try {
        if (needInsertQuery.size()!=0) {
            cphClasstwoMapper.insertBatchSomeColumn(needInsertQuery);//添加到第二课堂
        }
        if (needUpdateQuery.size() != 0) {
            for (CphClasstwo ccs:needUpdateQuery){
                cphClasstwoMapper.updateCphClasstwo(ccs);//修改第二课堂
            }
            //cphClasstwoMapper.updateCphClasstwoList(needUpdateQuery);//修改第二课堂
        }
//
//            List<SrsAddRecord> srsAddRecordList = new ArrayList<>();
//            for (CphClasstwoVo cphClasstwosMapList: needInsertList){
//                SrsAddRecord srsAddRecord = new SrsAddRecord();
//                srsAddRecord.setStuNo(cphClasstwosMapList.stuNo);//加分人学号
//                srsAddRecord.setApplicant(getUserId());//提交人id
//                srsAddRecord.setRuleId(3L);//规则类别
//                srsAddRecord.setRecordScore(cphClasstwosMapList.getClasstwoScore());//加分
//                srsAddRecord.setStuYearId(Integer.parseInt(stuYearId.toString()));//学年id
//                srsAddRecord.setStatusCode("6");//审核
//                srsAddRecord.setDelFlag("0");//是否存在
//                srsAddRecord.setStatus("0");//状态
//                srsAddRecord.setCreateTime(DateUtils.getNowDate());
//                srsAddRecord.setCreateBy(getUsername());
//                srsAddRecordList.add(srsAddRecord);//添加
//            }
//
//        List<SrsAddRecord> isExistRecord = srsAddRecordMapper.getIsExistRecord(3L,stuYearId,temp3);
//        List<SrsAddRecord> updateSrsAddRecordList = new ArrayList<>();
//        if(needUpdateList.size() != 0){
//            for (CphClasstwoVo item:needUpdateList) {
//                SrsAddRecord temp = new SrsAddRecord();
//                Long id = isExistRecord.stream()
//                        .filter(x->Objects.equals(x.getStuNo(),item.stuNo)).findAny().get().getId();
//                temp.setId(id);
//                temp.setRecordScore(item.getClasstwoScore());
//                temp.setStuYearId(Integer.parseInt(stuYearId.toString()));
//                temp.setUpdateTime(DateUtils.getNowDate());
//                temp.setUpdateBy(getUsername());
//                updateSrsAddRecordList.add(temp);
//            }
//        }
//
//            if(srsAddRecordList.size() != 0) {
//                srsAddRecordMapper.insertBatchSomeColumn(srsAddRecordList);//添加到加分记录表
//            }
//            if(updateSrsAddRecordList.size() != 0) {
//                for (SrsAddRecord sar:updateSrsAddRecordList) {
//                    srsAddRecordMapper.updateSrsAddRecord(sar);//批量修改
//                }
//                //srsAddRecordMapper.updateSrsAddRecordAll(updateSrsAddRecordList);//批量修改加分记录表
//            }
        }catch (Exception e){
            throw new ServiceException("导入出错 ，请重新导入");
        }
//        }catch (Exception ex){
//            System.out.println(ex.getMessage());
//        }
        return true;
    }
}
