package com.ruoyi.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.TrainingScoreConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.SysGradeWeight;
import com.ruoyi.system.domain.SysTrainingScore;
import com.ruoyi.system.domain.SysTrainingScoreExample;
import com.ruoyi.system.domain.vo.ReportDto;
import com.ruoyi.system.mapper.SysGradeWeightMapper;
import com.ruoyi.system.mapper.SysTrainingScoreMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysTrainingScoreService;
import com.ruoyi.system.util.IFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class SysTrainingScoreServiceImpl implements ISysTrainingScoreService {
    @Autowired
    SysTrainingScoreMapper trainingScoreMapper;
    @Autowired
    private IFileUtil fileUtil;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysGradeWeightMapper gradeWeightMapper;

    @Override
    public void deleteByUserId(Long userId) {
        SysTrainingScoreExample example = new SysTrainingScoreExample();
        SysTrainingScoreExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userId);
        trainingScoreMapper.deleteByExample(example);
    }

    @Override
    public void insertByUserId(Long userId) {
        SysTrainingScore sysTrainingScore = new SysTrainingScore();
        sysTrainingScore.setId(String.valueOf(UUID.randomUUID()));
        sysTrainingScore.setUserid(userId);
        sysTrainingScore.setStatus(0);
        trainingScoreMapper.insert(sysTrainingScore);
    }

    @Override
    public SysTrainingScore selectByUserId(Long userId) {
        SysTrainingScoreExample example = new SysTrainingScoreExample();
        SysTrainingScoreExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userId);
        List<SysTrainingScore> trainingScores = trainingScoreMapper.selectByExample(example);
        return trainingScores.get(0);
    }


    @Override
    public SysTrainingScore checkStatusAndControlsName(Long userId, String controlsName) {
        SysTrainingScoreExample example = new SysTrainingScoreExample();
        SysTrainingScoreExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userId);
        List<SysTrainingScore> trainingScores = trainingScoreMapper.selectByExample(example);
        SysTrainingScore sysTrainingScore = trainingScores.get(0);
        if (sysTrainingScore.getStatus() == 1) {
            return null;
        } else {
            if (sysTrainingScore.get(controlsName) == null || ("").equals(sysTrainingScore.get(controlsName)) || "null".equals(sysTrainingScore.get(controlsName))) {
                Map<String, Integer> trainingScoreConstantsMap = TrainingScoreConstants.getTrainingScoreConstantsMap();
                Integer score = trainingScoreConstantsMap.get(controlsName);
                SysTrainingScore trainingScore = new SysTrainingScore();
                trainingScore.setId(sysTrainingScore.getId());
                trainingScore.set(controlsName, String.valueOf(score));
                if (controlsName.equals("dataCollectionStepDescription")) {
                    trainingScore.set("dataCollectionToolbarButton", "2");
                    sysTrainingScore.set("dataCollectionToolbarButton", "2");
                }
                trainingScoreMapper.updateByPrimaryKeySelective(trainingScore);
                sysTrainingScore.set(controlsName, String.valueOf(score));
                return sysTrainingScore;
            }
            return null;
        }
    }


    public void updateByPrimaryKeySelective(SysTrainingScore trainingScore) {
        trainingScoreMapper.updateByPrimaryKeySelective(trainingScore);
    }


//    @Override
//    public PageInfo<ReportDto> teacherGetReport(Integer index, Integer size, Double reportWeight, Double operatorWeight, String keyWord, String stuClass) {
//        PageHelper.startPage(index, size);
//        List<ReportDto> reportDtoList = new ArrayList<>();
//        if (stuClass != null || keyWord != null) {
//            List<SysUser> users = sysUserMapper.selectByNameStuNum(stuClass, keyWord);
//            for (SysUser user : users) {
//                SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
//                trainingScoreExample.createCriteria().andUseridEqualTo(user.getUserId());
//                List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
//                if (!sysTrainingScores.isEmpty()) {
//                    SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
//                    ReportDto reportDto = createReportDto(sysTrainingScore, user, reportWeight, operatorWeight);
//                    reportDtoList.add(reportDto);
//                }
//            }
//            return new PageInfo<>(reportDtoList);
//        }
//        List<SysUser> userList = sysUserMapper.selectClassStuNumberName();
//        for (SysUser sysUser : userList) {
//            SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
//            trainingScoreExample.createCriteria().andUseridEqualTo(sysUser.getUserId());
//            List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
//            if (!sysTrainingScores.isEmpty()) {
//                SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
//                ReportDto reportDto = createReportDto(sysTrainingScore, sysUser, reportWeight, operatorWeight);
//                reportDtoList.add(reportDto);
//            }
//        }
//        return new PageInfo<>(reportDtoList);
//    }

    @Override
    public PageInfo<ReportDto> teacherGetReport(Integer index, Integer size, Double reportWeight, Double operatorWeight, String keyWord, String stuClass) {
        PageHelper.startPage(index, size);
        List<ReportDto> reportDtoList = new ArrayList<>();
        if (stuClass != null || keyWord != null) {
            List<SysUser> users = sysUserMapper.selectByNameStuNum(stuClass, keyWord);
            for (SysUser user : users) {
                SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
                trainingScoreExample.createCriteria().andUseridEqualTo(user.getUserId());
                List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
                if (!sysTrainingScores.isEmpty()) {
                    SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
                    // 检查是否已经存在分数
                    if (sysTrainingScore.getTotalscore() != null &&
                            sysTrainingScore.getTrainingReportScore() != null &&
                            sysTrainingScore.getTrainingOperationScore() != null) {
                        // 使用数据库中的分数创建ReportDto
                        ReportDto reportDto = new ReportDto(
                                user.getStuClass(),
                                user.getStudentNumber(),
                                user.getUserName(),
                                sysTrainingScore.getTrainingReportScore().doubleValue(),
                                sysTrainingScore.getTrainingOperationScore().doubleValue(),
                                sysTrainingScore.getTotalscore(),
                                sysTrainingScore.getReportFilename()
                        );
                        reportDto.setUserId(user.getUserId());
                        reportDtoList.add(reportDto);
                    } else {
                        // 进行计算分数的逻辑，调用createReportDto方法
                        ReportDto reportDto = createReportDto(sysTrainingScore, user, reportWeight, operatorWeight);
                        reportDtoList.add(reportDto);
                    }
                }
            }
            return new PageInfo<>(reportDtoList);
        }
        List<SysUser> userList = sysUserMapper.selectClassStuNumberName();
        for (SysUser sysUser : userList) {
            SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
            trainingScoreExample.createCriteria().andUseridEqualTo(sysUser.getUserId());
            List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
            if (!sysTrainingScores.isEmpty()) {
                SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
                if (sysTrainingScore.getTotalscore() != null &&
                        sysTrainingScore.getTrainingReportScore() != null &&
                        sysTrainingScore.getTrainingOperationScore() != null) {
                    // 使用数据库中的分数创建ReportDto
                    ReportDto reportDto = new ReportDto(
                            sysUser.getStuClass(),
                            sysUser.getStudentNumber(),
                            sysUser.getUserName(),
                            sysTrainingScore.getTrainingReportScore().doubleValue(),
                            sysTrainingScore.getTrainingOperationScore().doubleValue(),
                            sysTrainingScore.getTotalscore(),
                            sysTrainingScore.getReportFilename()
                    );
                    reportDto.setUserId(sysUser.getUserId());
                    reportDtoList.add(reportDto);
                } else {
                    // 进行计算分数的逻辑，调用createReportDto方法
                    ReportDto reportDto = createReportDto(sysTrainingScore, sysUser, reportWeight, operatorWeight);
                    reportDtoList.add(reportDto);
                }
            }
        }
        return new PageInfo<>(reportDtoList);
    }

    @Override
    public List<SysTrainingScore> selectAllReportContent() {
        List<SysTrainingScore> trainingScores = trainingScoreMapper.selectAllReportContent();
        return trainingScores;
    }


    //    算分
    private ReportDto createReportDto(SysTrainingScore sysTrainingScore, SysUser user, Double reportWeight, Double operatorWeight) {
        ReportDto reportDto = new ReportDto();
        reportDto.setFileName(sysTrainingScore.getReportFilename());
        Integer reportScore = sysTrainingScore.getTrainingReportScore();   // 报告成绩
        Integer trainingOperationScore = sysTrainingScore.getTrainingOperationScore();  // 操作成绩
        reportDto.setName(user.getUserName());
        reportDto.setStuClass(user.getStuClass());
        reportDto.setStuNumber(user.getStudentNumber());
        reportDto.setUserId(user.getUserId());
        if (reportScore != null && trainingOperationScore != null) {
            SysGradeWeight sysGradeWeight = gradeWeightMapper.selectByPrimaryKey(1L);
            Double oldReportWeight = sysGradeWeight.getReportWeight();
            Double oldOperatorWeight = sysGradeWeight.getOperatorWeight();
            if (reportWeight != null) {
                sysGradeWeight.setReportWeight(reportWeight);
            } else if (oldReportWeight != null) {
                reportWeight = oldReportWeight;
            } else {
                reportWeight = 0.1; // 设置默认权重
            }

            if (operatorWeight != null) {
                sysGradeWeight.setOperatorWeight(operatorWeight);
            } else if (oldOperatorWeight != null) {
                operatorWeight = oldOperatorWeight;
            } else {
                operatorWeight = 0.9; // 设置默认权重
            }
            Double resultReportScore = reportScore * reportWeight;  //报告成绩 加权重后
            Double resultOperationScore = trainingOperationScore * operatorWeight;  //操作成绩 加权重后
            Double totalScore = resultReportScore + resultOperationScore;   //总成绩

            reportDto.setTrainingReportScore(resultReportScore);
            reportDto.setTrainingOperationScore(resultOperationScore);
            reportDto.setScoreTotal(totalScore);
            sysTrainingScore.setTotalscore(totalScore);
            sysTrainingScore.setTrainingReportScore(resultReportScore.intValue());
            sysTrainingScore.setTrainingOperationScore(resultOperationScore.intValue());
            trainingScoreMapper.updateByPrimaryKeySelective(sysTrainingScore);
            gradeWeightMapper.updateByPrimaryKeySelective(sysGradeWeight);
            return reportDto;
        }    //当两个成绩有一个时，也需要查询返回已有的 (不能算权重) 只有一个时不计算权重 否则查询一次就会算一次哦
        else if (reportScore != null) { // 当只有报告成绩可用时
            reportDto.setTrainingReportScore(reportScore.doubleValue());
            trainingScoreMapper.updateByPrimaryKeySelective(sysTrainingScore);
            return reportDto;
        } else if (trainingOperationScore != null) { // 当只有操作成绩可用时
            reportDto.setTrainingOperationScore(trainingOperationScore.doubleValue());
            trainingScoreMapper.updateByPrimaryKeySelective(sysTrainingScore);
            return reportDto;
        } else {
            return reportDto;
        }
    }

    //上传
    @Override
    public AjaxResult uploadReport(MultipartFile file, String fileName, Long id) {
        String filePath = fileUtil.upload(file);
        SysTrainingScoreExample sysTrainingScoreExample = new SysTrainingScoreExample();
        sysTrainingScoreExample.createCriteria().andUseridEqualTo(id);
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(sysTrainingScoreExample);
        if (!sysTrainingScores.isEmpty()) {
            SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
            if (sysTrainingScore != null && sysTrainingScore.getReportContent() != null && !sysTrainingScore.getReportContent().isEmpty()) {
                return AjaxResult.error("报告已提交，不允许上传和修改");
            }
            if (sysTrainingScore != null && StringUtils.hasText(sysTrainingScore.getReportUploadPath())) {
                fileUtil.remove(sysTrainingScore.getReportUploadPath());
                sysTrainingScore.setReportUploadPath(filePath);
                sysTrainingScore.setReportFilename(fileName);
                trainingScoreMapper.updateByExample(sysTrainingScore, sysTrainingScoreExample);
                return AjaxResult.success("上传成功");
            } else {
                if (sysTrainingScore != null) {
                    sysTrainingScore.setReportUploadPath(filePath);
                    sysTrainingScore.setReportFilename(fileName);
                }
                trainingScoreMapper.updateByPrimaryKeySelective(sysTrainingScore);
                return AjaxResult.success("上传成功");
            }
        }
        return null;
    }


    //提交
    @Override
    public AjaxResult submitReport(String content, Long userId) {
        SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
        trainingScoreExample.createCriteria().andUseridEqualTo(userId);
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
        if (!sysTrainingScores.isEmpty()) {
            SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
            if (sysTrainingScore.getReportUploadPath() == null) {
                return AjaxResult.error("请先上传再提交");
            }
            sysTrainingScore.setReportContent(content);
            trainingScoreMapper.updateByPrimaryKeySelective(sysTrainingScore);
        }
        return AjaxResult.success("提交成功");
    }


    @Override
    public List<String> selectClass() {
        return sysUserMapper.selectClass();
    }

    @Override
    public AjaxResult downloadReport(HttpServletResponse response, Long id) {
        SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
        trainingScoreExample.createCriteria().andUseridEqualTo(id);
        // 根据id获取文件路径信息
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
        if (sysTrainingScores.isEmpty()) {
            return AjaxResult.error(404, "报告不存在");
        }
        SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
        String filePath = sysTrainingScore.getReportUploadPath();
        String fileName = sysTrainingScore.getReportFilename();

        try {
            // 下载文件
            fileUtil.download(response, fileName, filePath);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(400, "下载失败");
        }
        return AjaxResult.success("下载成功");
    }
}
