package com.ruoyi.biemo.business.controller;

import com.alibaba.fastjson.JSONObject;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
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.domain.vo.TrainingScoreVo;
import com.ruoyi.system.domain.vo.TrainingTotalScoreVo;
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.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/makesoft/trainingScore")
public class TrainingScoreController {
    @Autowired
    ISysTrainingScoreService trainingScoreService;
    @Autowired
    SysTrainingScoreMapper trainingScoreMapper;
    @Autowired
    SysGradeWeightMapper gradeWeightMapper;
    @Autowired
    SysUserMapper sysUserMapper;


    @PostMapping("/addScore")
    private void addScore(@RequestBody JSONObject jsonObject) {
        String controlsName = jsonObject.getString("controlsName");
        Long userId = jsonObject.getLong("userId");
        //检查状态是否提交且变更的值是否有数据 如果返回值为false 则执行更新操作
        SysTrainingScore sysTrainingScore = trainingScoreService.checkStatusAndControlsName(userId, controlsName);
        if (sysTrainingScore != null) {
            //更新userid的进度和分数
            sysTrainingScore.calculateDataScore();
            trainingScoreService.updateByPrimaryKeySelective(sysTrainingScore);
        }
    }

    //查询实训进度
    @PostMapping("/selectScore")
    private List selectScore(@RequestBody JSONObject jsonObject) {
        Long userId = jsonObject.getLong("userId");
        SysTrainingScore sysTrainingScore = trainingScoreService.selectByUserId(userId);
        TrainingScoreVo trainingScoreVo = new TrainingScoreVo(sysTrainingScore);
        List<Map> list = trainingScoreVo.ReturnTrainingScore(trainingScoreVo);
        return list;
    }

    //查询实训成绩
    @PostMapping("/selectTotalScore")
    private List selectTotalScore(@RequestBody JSONObject jsonObject) {
        Long userId = jsonObject.getLong("userId");
        SysTrainingScore sysTrainingScore = trainingScoreService.selectByUserId(userId);
        TrainingTotalScoreVo totalScoreVo = new TrainingTotalScoreVo(sysTrainingScore);
        totalScoreVo.setTotalscore(sysTrainingScore.getTotalscore());
        totalScoreVo.setTrainingReportScore(sysTrainingScore.getTrainingReportScore());
        List<Map> list = totalScoreVo.ReturnTrainingTotalScore(totalScoreVo);
        return list;
    }

    //重新实训
    @PostMapping("/restartTraining")
    private String restartTraining(@RequestBody JSONObject jsonObject) {
        Long userId = jsonObject.getLong("userId");
        trainingScoreService.deleteByUserId(userId);
        trainingScoreService.insertByUserId(userId);
        return "重新实训成功";
    }

    //一键审批
    @PostMapping("/approvalAll")
    private String approvalAll() {
        List<SysTrainingScore> trainingScoreList = trainingScoreService.selectAllReportContent();
        if (trainingScoreList.isEmpty()) {
            return "没有可审批的数据";
        }
        for (int i = 0; i < trainingScoreList.size(); i++) {
            SysTrainingScore sysTrainingScore = trainingScoreList.get(i);
            if (sysTrainingScore.getReportContent()==null || "".equals(sysTrainingScore.getReportContent())){
                continue;
            }
            String reportContent = sysTrainingScore.getReportContent();
            int wordCount = reportContent.replace(" ", "").length(); // 获取文本的字数

            int score;
            if (wordCount <= 50) {
                score = 40;
            } else if (wordCount <= 350) {
                int extraWords = wordCount - 50; // 超出50字的额外字数
                int extraScore = extraWords / 10 * 2; // 计算额外的得分
                score = 40 + extraScore;
            } else {
                score = 100; // 超过350字直接满分
            }
            SysTrainingScore trainingScore = new SysTrainingScore();
            trainingScore.setId(sysTrainingScore.getId());
            trainingScore.setTrainingReportScore(score);
            trainingScoreService.updateByPrimaryKeySelective(trainingScore);
        }
        return "审批完毕";
    }

    //学生端实训报告上传
    @PostMapping("/uploadReport")
    private AjaxResult uploadReport(@RequestParam("file") @RequestPart(name = "file") MultipartFile file,
                                    @RequestParam Long id,
                                    @RequestParam String fileName) {
        return trainingScoreService.uploadReport(file, fileName, id);
    }

    //学生端实训报告提交
    @PostMapping("/submitReport")
    public AjaxResult submitReport(@RequestBody JSONObject jsonObject) {
        Long userId = jsonObject.getLong("userId");
        String content = jsonObject.getString("content");
        return trainingScoreService.submitReport(content, userId);
    }

    //学生端实验报告回显
    @GetMapping("/getSubmitAndSaveReport")
    public String getSubmitAndSaveReport(@RequestParam Long userId) {
        SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
        trainingScoreExample.createCriteria().andUseridEqualTo(userId);
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExampleWithBLOBs(trainingScoreExample);
        if (!sysTrainingScores.isEmpty()) {
            SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
            return sysTrainingScore.getReportContent();
        }
        return null;
    }

    //    老师端文件下载
    @GetMapping("/downloadReport")
    public AjaxResult downloadReport(@RequestParam Long id, HttpServletResponse response) {
        return trainingScoreService.downloadReport(response, id);
    }

    // 老师端获取文件ID用于下载
    @GetMapping("/getReportIdByUserId")
    public AjaxResult getReportIdByUserId(@RequestParam Long userId) {
        SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
        trainingScoreExample.createCriteria().andUseridEqualTo(userId);
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
        if (!sysTrainingScores.isEmpty()) {
            return AjaxResult.success(sysTrainingScores.get(0));
        }
        return AjaxResult.error(404, "未查询到文件");
    }

    //    老师端按班级导出
    @GetMapping("/exportByClass")
    public void exportByClass(HttpServletResponse response, @RequestParam String className) {
        // 根据班级名称查询对应的用户列表
        List<SysUser> userList = sysUserMapper.selectClassStuNumberNameByClass(className);
        SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
        List<ReportDto> reportDtoList = new ArrayList<>();
        if (!userList.isEmpty()) {
            for (SysTrainingScore sysTrainingScore : sysTrainingScores) {
                for (SysUser sysUser : userList) {
                    if (sysTrainingScore.getUserid().equals(sysUser.getUserId())) {
                        ReportDto reportDto = new ReportDto();
                        reportDto.setFileName(sysTrainingScore.getReportFilename());
                        reportDto.setTrainingReportScore(sysTrainingScore.getTrainingReportScore() == null ? 0.0 :
                                sysTrainingScore.getTrainingReportScore().doubleValue());
                        reportDto.setTrainingOperationScore(sysTrainingScore.getTrainingOperationScore() == null ? 0.0 :
                                sysTrainingScore.getTrainingOperationScore().doubleValue());
                        reportDto.setScoreTotal(sysTrainingScore.getTotalscore());
                        reportDto.setName(sysUser.getUserName());
                        reportDto.setStuClass(sysUser.getStuClass());
                        reportDto.setStuNumber(sysUser.getStudentNumber());
                        reportDtoList.add(reportDto);
                    }
                }
            }
        }
        // 创建Excel工具类实例，指定Excel中需要导出的字段与对应的实体类属性
        ExcelUtil<ReportDto> util = new ExcelUtil<>(ReportDto.class);
        // 导出Excel文件
        util.exportExcel(response, reportDtoList, "班级数据");
    }


    //   老师端报告提交页面查询
    @GetMapping("/teacherGetReport")
    public PageInfo<ReportDto> getReport(@RequestParam Integer index, @RequestParam Integer size,
                                         @RequestParam(required = false) Double operatorWeight,
                                         @RequestParam(required = false) Double reportWeight,
                                         @RequestParam(required = false) String keyWord,
                                         @RequestParam(required = false) String stuClass) {
        return trainingScoreService.teacherGetReport(index, size, reportWeight, operatorWeight, keyWord, stuClass);
    }


    //   老师端下拉查询班级
    @GetMapping("/selectClass")
    public List<String> selectClass() {
        return trainingScoreService.selectClass();
    }


    //   老师端报告评分
    @PostMapping("/reportGrade")
    public void reportGrade(@RequestBody JSONObject jsonObject) {
        Integer reportScore = jsonObject.getInteger("reportScore");
        Long userId = jsonObject.getLong("userId");
        SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
        trainingScoreExample.createCriteria().andUseridEqualTo(userId);
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
        if (!sysTrainingScores.isEmpty()) {
            SysTrainingScore sysTrainingScore = sysTrainingScores.get(0);
            sysTrainingScore.setTrainingReportScore(reportScore);
            trainingScoreMapper.updateByPrimaryKeySelective(sysTrainingScore);
        }
    }


    //   老师端保存修改权重
    @PutMapping("/saveOrUpdateWeight")
    public void saveWeight(@RequestBody JSONObject jsonObject) {
        Double reportWeight = jsonObject.getDouble("reportWeight");
        Double operatorWeight = jsonObject.getDouble("operatorWeight");
        SysGradeWeight sysGradeWeight = gradeWeightMapper.selectByPrimaryKey(1L);
        sysGradeWeight.setReportWeight(reportWeight);
        sysGradeWeight.setOperatorWeight(operatorWeight);
        gradeWeightMapper.updateByPrimaryKeySelective(sysGradeWeight);
    }

    //    老师端回显权重
    @GetMapping("/getWeight")
    public SysGradeWeight getWeight() {
        return gradeWeightMapper.selectByPrimaryKey(1L);
    }

    // 老师端右侧成绩(为经过权重计算)
    @GetMapping("/getReportScore")
    public Map<Long, Integer> getWeightReport() {
        SysTrainingScoreExample trainingScoreExample = new SysTrainingScoreExample();
        List<SysTrainingScore> sysTrainingScores = trainingScoreMapper.selectByExample(trainingScoreExample);
        Map<Long, Integer> resultScores = new HashMap<>();
        if (!sysTrainingScores.isEmpty()) {
            for (SysTrainingScore sysTrainingScore : sysTrainingScores) {
                if (sysTrainingScore.getTrainingReportScore() != null) {
                    Integer trainingReportScore = sysTrainingScore.getTrainingReportScore();
                    Long userid = sysTrainingScore.getUserid();
                    resultScores.put(userid, trainingReportScore);
                }
            }
            return resultScores;
        }
        return null;
    }

}