package com.srs.comprehensive.service.impl;

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

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.annotation.Excel;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.BaseEntity;
import com.srs.common.core.domain.entity.SysUser;
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.*;
import com.srs.comprehensive.mapper.SrsAddRecordMapper;
import com.srs.comprehensive.mapper.SrsSportTestMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.comprehensive.mapper.SumSportTestMapper;
import com.srs.comprehensive.service.ICphTestForService;
import com.srs.comprehensive.service.ISrsSportTestService;
import org.apache.poi.ss.formula.functions.Now;
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;
import static org.apache.commons.lang3.SystemUtils.getUserName;

/**
 * 体能测试Service业务层处理
 * 
 * @author srs
 * @date 2023-06-28
 */
@Service
public class SrsSportTestServiceImpl  extends ServiceImpl<SrsSportTestMapper,SrsSportTest> implements ISrsSportTestService
{
    @Autowired
    private SrsSportTestMapper srsSportTestMapper;
    //学生表
    @Autowired
    private SrsStudentMapper srsStudentMapper;
    //加分记录
    @Autowired
    private SrsAddRecordMapper srsAddRecordMapper;
    //体能测试中间表
    @Autowired
    private SumSportTestMapper sumSportTestMapper;

    @Autowired
    private ICphTestForService cphTestForService;


    @Override
    public AjaxResult editStuScore(SrsSportTest param){
        try{
            SrsStudent stu = srsStudentMapper.selectSrsStudentByStuNo(param.getStuNo());
            if(stu == null){
                throw new Exception("没有这个学生");
            }
            SrsSportTest query = new SrsSportTest();
            query.setStuId(stu.getStuId());
            query.setStuYearId(param.getStuYearId());

            List<SrsSportTest> list = srsSportTestMapper.selectSrsSportTestList(query);
            if(list.size() == 0){
                SrsSportTest temp = new SrsSportTest();
                temp.setId(stu.getStuId());
                temp.setStuNo(stu.getStuNo());
                temp.setStuId(stu.getStuId());
                temp.setTestScore(param.getTestScore());
                temp.setStuYearId(param.getStuYearId());
                temp.setDelFlag("0");
                temp.setCreateBy(getUsername());
                temp.setCreateTime(new Date());
                int res = srsSportTestMapper.insertSrsSportTest(temp);
                if(res == 1){
//                    cphTestForService.testMethod(Integer.parseInt(param.getStuYearId().toString()));
                    return AjaxResult.success();
                }else{
                    throw new Exception("添加成绩失败");
                }
            }else{
                SrsSportTest temp = list.get(0);
                temp.setTestScore(param.getTestScore());
                int res = srsSportTestMapper.updateSrsSportTest(temp);
                if(res == 1){
//                    cphTestForService.testMethod(Integer.parseInt(param.getStuYearId().toString()));
                    return AjaxResult.success();
                }else{
                    throw new Exception("修改成绩失败");
                }
            }

        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    /**
     * 查询体能测试
     * 
     * @param id 体能测试主键
     * @return 体能测试
     */
    @Override
    public SrsSportTest selectSrsSportTestById(Long id)
    {
        return srsSportTestMapper.selectSrsSportTestById(id);
    }

    /**
     * 查询体能测试列表
     * 
     * @param srsSportTest 体能测试
     * @return 体能测试
     */
    @Override
    public List<SrsSportTest> selectSrsSportTestList(SrsSportTest srsSportTest)
    {
        return srsSportTestMapper.selectSrsSportTestList(srsSportTest);
    }

    /**
     * 新增体能测试
     * 
     * @param srsSportTest 体能测试
     * @return 结果
     */
    @Override
    public int insertSrsSportTest(SrsSportTest srsSportTest)
    {
        srsSportTest.setCreateTime(DateUtils.getNowDate());
        return srsSportTestMapper.insertSrsSportTest(srsSportTest);
    }

    /**
     * 修改体能测试
     * 
     * @param srsSportTest 体能测试
     * @return 结果
     */
    @Override
    public int updateSrsSportTest(SrsSportTest srsSportTest)
    {
        srsSportTest.setUpdateTime(DateUtils.getNowDate());
        srsSportTest.setUpdateBy(getUsername());
        return srsSportTestMapper.updateSrsSportTest(srsSportTest);
    }

    /**
     * 批量删除体能测试
     * 
     * @param ids 需要删除的体能测试主键
     * @return 结果
     */
    @Override
    public int deleteSrsSportTestByIds(Long[] ids)
    {
        return srsSportTestMapper.deleteSrsSportTestByIds(ids);
    }

    /**
     * 删除体能测试信息
     * 
     * @param id 体能测试主键
     * @return 结果
     */
    @Override
    public int deleteSrsSportTestById(Long id)
    {
        return srsSportTestMapper.deleteSrsSportTestById(id);
    }

    /**
     * 体能测试批量新增
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertSrsSportTestStudent(List<SrsSportTestStudent> insertSrsSportTestStudentS) {
        try {
            Long stuYearId = insertSrsSportTestStudentS.get(0).getStuYearId();
            List<CphScoreVo> temp1 = srsSportTestMapper.listAllSportInfo(stuYearId);
            List<String> isExistStuNo = new ArrayList<>(); //已存在的学号
            List<String> allExportStuNo = new ArrayList<>(); //所有待导入的学号
            for (CphScoreVo i : temp1) {
                isExistStuNo.add(i.getStuNo());
            }

            for (SrsSportTestStudent i : insertSrsSportTestStudentS) {
                allExportStuNo.add(i.getStuNo());
            }

            List<String> needInsertStuNo = listFunc.subList(allExportStuNo, isExistStuNo); //需要添加的学号
            List<String> needUpdateStuNo = listFunc.intersectList(allExportStuNo, isExistStuNo); //需要修改的学号

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

            Set<SrsSportTestStudent> needUpdateList = insertSrsSportTestStudentS.stream()
                    .filter(s -> needUpdateStuNo.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 = srsSportTestMapper.getStuIdByStuNosToInsert(temp2);
            }
            if (temp3.length != 0) {
                updateIds = srsSportTestMapper.getStuIdByStuNosToUpdate(temp3, stuYearId);
            }

            List<SrsSportTest> needInsertQuery = new ArrayList<>();
            List<SrsSportTest> needUpdateQuery = new ArrayList<>();
            BigDecimal oneHundred = new BigDecimal(100);

            for (SrsSportTestStudent item :
                    needInsertList) {
                SrsSportTest temp = new SrsSportTest();
                BigDecimal score = item.getTestScore();
                if(score.compareTo(oneHundred) == 1){
                    temp.setTestScore(oneHundred);
                }else{
                    temp.setTestScore(item.getTestScore());
                }
                temp.setStuYearId(item.getStuYearId());
                String stu_no = item.getStuNo();
                StuIdNo nTemp = insertIds.stream()
                        .filter(x -> Objects.equals(x.stuNo, stu_no))
                        .findAny().orElse(null);
                if (nTemp != null) {
                    temp.setStuId(nTemp.stuId);
                }
                temp.setStuNo(item.getStuNo());
                temp.setDelFlag("0");
                temp.setCreateTime(new Date());
                temp.setCreateBy(getUsername());
                needInsertQuery.add(temp);
            }

            for (SrsSportTestStudent item :
                    needUpdateList) {
                SrsSportTest temp = new SrsSportTest();
                BigDecimal score = item.getTestScore();
                if(score.compareTo(oneHundred) == 1){
                    temp.setTestScore(oneHundred);
                }else{
                    temp.setTestScore(item.getTestScore());
                }
                temp.setStuYearId(item.getStuYearId());
                String stu_no = item.getStuNo();
                StuIdNo nTemp = updateIds.stream()
                        .filter(x -> Objects.equals(x.stuNo, stu_no))
                        .findAny().orElse(null);
                if (nTemp != null) {
                    temp.setId(nTemp.id);
                    temp.setStuId(nTemp.stuId);
                }
                temp.setDelFlag("0");
                temp.setUpdateTime(new Date());
                temp.setUpdateBy(getUsername());
                needUpdateQuery.add(temp);
            }

            if (needInsertQuery.size() != 0) {
                srsSportTestMapper.insertBatchSomeColumn(needInsertQuery);//添加到体能测试
            }
            //修改体能测试
            if (needUpdateQuery.size() != 0) {
                this.updateBatchById(needUpdateQuery);
//                //单条
//                for (SrsSportTest srsSportTest:needUpdateQuery){
//
//                    srsSportTestMapper.updateSrsSportTest(srsSportTest);
//                }
                //切片批量
//                int userListSize=needUpdateQuery.size();
//                int sum=userListSize/1000;
//                int sums=userListSize%1000;
//                if (sums!=0){
//                    sum++;
//                }
//                List<List<SrsSportTest>> listList=new ArrayList<>();
//                int sumIm=0;
//                for (int i=0;i<sum;i++){
//                    List<SrsSportTest> objects = new ArrayList<>();
//                    int listSum=1000;
//                    if (sums!=0&&i==sum-1){
//                        listSum=sums;
//                    }
//                    for (int j=0;j<listSum;j++){
//                        objects.add(needUpdateQuery.get(sumIm));
//                        sumIm++;
//                    }
//                    listList.add(objects);
//                }
//                for (List<SrsSportTest> userList1:listList){
//                    srsSportTestMapper.updateSrsSportTestAll(userList1);
//                }

                //srsSportTestMapper.updateSrsSportTestAll(needUpdateQuery);//  修改体能测试
            }

        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
        return 1;
    }

    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);
        }
    }

    /**
     * 中间表添加数据到 体能测试
     * @Description 添加体能测试
     * @return
     */
    public List<String> addSrsSportTest(){
        List<SumSportTest> sumSportTests = sumSportTestMapper.selectSumSportTestAll();
        List<String> strings = new ArrayList<>();
        if (sumSportTests.size()==0){
            strings.add("没有要处理的数据");
            return strings;
        }
        SrsSportTest srsSportTest = new SrsSportTest();
        try {
            for (SumSportTest s: sumSportTests) {
                SrsStudent srsStudent = srsStudentMapper.selectSrsStudentByStuNo(s.getStuNo());
                if (srsStudent==null){
                    strings.add(s.getStuNo());
                    continue;
                }
                srsSportTest.setStuId(srsStudent.getStuId());
                srsSportTest.setTestScore(s.getTestScore());
                srsSportTest.setStuYearId((long) s.getStuYearId());
                srsSportTestMapper.insertSrsSportTest(srsSportTest);
                //
                s.setChmodStatus("2");
                s.setReadTime(DateUtils.getNowDate());
                sumSportTestMapper.updateSum(s);

            }

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