wangliang 1 gadu atpakaļ
vecāks
revīzija
c470058981

+ 35 - 2
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/PrintCommonService.java

@@ -1,14 +1,14 @@
 package com.qmth.distributed.print.business.service;
 
-import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.itextpdf.text.DocumentException;
 import com.qmth.distributed.print.business.bean.createPdf.PrintPathVo;
 import com.qmth.distributed.print.business.bean.dto.PdfDto;
 import com.qmth.distributed.print.business.bean.dto.PdfPackageDto;
 import com.qmth.distributed.print.business.bean.dto.PdfSignDto;
+import com.qmth.distributed.print.business.bean.excel.ExcelField;
 import com.qmth.distributed.print.business.bean.params.ExamTaskStudentObjectParam;
-import com.qmth.distributed.print.business.bean.params.SerialNumberParams;
+import com.qmth.distributed.print.business.bean.result.ScoreResult;
 import com.qmth.distributed.print.business.entity.BasicTemplate;
 import com.qmth.distributed.print.business.entity.ExamDetail;
 import com.qmth.distributed.print.business.entity.ExamStudent;
@@ -20,6 +20,7 @@ import com.qmth.teachcloud.common.entity.SysUser;
 import com.qmth.teachcloud.common.enums.ClassifyEnum;
 import com.qmth.teachcloud.common.enums.TaskTypeEnum;
 import com.qmth.teachcloud.common.enums.UploadFileEnum;
+import com.qmth.teachcloud.mark.entity.MarkPaper;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.web.multipart.MultipartFile;
 
@@ -224,6 +225,7 @@ public interface PrintCommonService {
     void checkData(Long schoolId, Long examId, String courseCode, String paperNumber, SysUser user) throws IOException;
 
     void checkDataMakeup(Long schoolId, ExamDetail examDetail, String courseCode, String paperNumber, SysUser user);
+
     /**
      * 根据学生集合创建考生考务数据
      *
@@ -268,4 +270,35 @@ public interface PrintCommonService {
     void saveAttachmentPackagePdf(PdfPackageDto pdfPackageDto, ExamDetail examDetail, List<PdfDto> variablePdfList, Integer printCount, List<File> fileTempList);
 
     String parseAttachmentPath(String attachmentPath, PrintPathVo printPathVo);
+
+    /**
+     * 成绩管理导入excel校验
+     *
+     * @param file
+     * @param examId
+     * @param paperNumber
+     * @return
+     */
+    public MarkPaper scoreImportExcelVaild(MultipartFile file, Long examId, String paperNumber) throws IOException;
+
+    /**
+     * 成绩管理动态生成excel
+     *
+     * @param describe
+     * @param sheetName
+     * @param fileName
+     * @param excelFieldList
+     * @throws IOException
+     */
+    public void scoreDownLoadExaminationTemplate(String describe, String sheetName, String fileName, List<ExcelField> excelFieldList) throws IOException;
+
+    /**
+     * 成绩管理列表
+     *
+     * @param iPage
+     * @param examId
+     * @param courseCode
+     * @return
+     */
+    public IPage<ScoreResult> scoreList(IPage<Map> iPage, Long examId, String courseCode);
 }

+ 16 - 1
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/TCFinalScoreService.java

@@ -1,7 +1,11 @@
 package com.qmth.distributed.print.business.service;
 
-import com.qmth.distributed.print.business.entity.TCFinalScore;
 import com.baomidou.mybatisplus.extension.service.IService;
+import com.qmth.distributed.print.business.entity.TCFinalScore;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.util.Map;
 
 /**
  * <p>
@@ -13,4 +17,15 @@ import com.baomidou.mybatisplus.extension.service.IService;
  */
 public interface TCFinalScoreService extends IService<TCFinalScore> {
 
+    /**
+     * 导入期末成绩excel
+     *
+     * @param file
+     * @param examId
+     * @param courseCode
+     * @param paperNumber
+     * @return
+     * @throws IOException
+     */
+    public Map<String, String> finalScoreExcelImport(MultipartFile file, Long examId, String courseCode, String paperNumber) throws IOException;
 }

+ 4 - 24
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/TCUsualScoreService.java

@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.extension.service.IService;
 import com.qmth.distributed.print.business.bean.excel.ExcelField;
 import com.qmth.distributed.print.business.bean.result.ScoreResult;
 import com.qmth.distributed.print.business.entity.TCUsualScore;
-import com.qmth.teachcloud.mark.entity.MarkPaper;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.IOException;
@@ -23,33 +22,14 @@ import java.util.Map;
 public interface TCUsualScoreService extends IService<TCUsualScore> {
 
     /**
-     * 成绩管理列表
-     *
-     * @param iPage
-     * @param examId
-     * @param courseCode
-     * @return
-     */
-    public IPage<ScoreResult> scoreList(IPage<Map> iPage, Long examId, String courseCode);
-
-    /**
-     * 动态生成excel
-     *
-     * @param describe
-     * @param sheetName
-     * @param fileName
-     * @param excelFieldList
-     * @throws IOException
-     */
-    void downLoadExaminationTemplate(String describe, String sheetName, String fileName, List<ExcelField> excelFieldList) throws IOException;
-
-    /**
-     * 导入excel校验
+     * 导入平时成绩excel
      *
      * @param file
      * @param examId
+     * @param courseCode
      * @param paperNumber
      * @return
+     * @throws IOException
      */
-    public MarkPaper importExcelVaild(MultipartFile file, Long examId, String paperNumber) throws IOException;
+    public Map<String, String> usualScoreExcelImport(MultipartFile file, Long examId, String courseCode, String paperNumber) throws IOException;
 }

+ 152 - 0
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/impl/PrintCommonServiceImpl.java

@@ -15,11 +15,14 @@ import com.qmth.distributed.print.business.bean.createPdf.PrintPathVo;
 import com.qmth.distributed.print.business.bean.dto.PdfDto;
 import com.qmth.distributed.print.business.bean.dto.PdfPackageDto;
 import com.qmth.distributed.print.business.bean.dto.PdfSignDto;
+import com.qmth.distributed.print.business.bean.excel.ExcelField;
 import com.qmth.distributed.print.business.bean.params.ExamTaskStudentObjectParam;
+import com.qmth.distributed.print.business.bean.result.ScoreResult;
 import com.qmth.distributed.print.business.entity.*;
 import com.qmth.distributed.print.business.enums.ExamDetailStatusEnum;
 import com.qmth.distributed.print.business.enums.PrintPlanStatusEnum;
 import com.qmth.distributed.print.business.enums.StudentClazzEnum;
+import com.qmth.distributed.print.business.mapper.TCUsualScoreMapper;
 import com.qmth.distributed.print.business.service.*;
 import com.qmth.distributed.print.business.util.CreatePrintPdfUtil;
 import com.qmth.distributed.print.business.util.PdfUtil;
@@ -35,10 +38,18 @@ import com.qmth.teachcloud.common.enums.*;
 import com.qmth.teachcloud.common.mapper.BasicCourseMapper;
 import com.qmth.teachcloud.common.service.*;
 import com.qmth.teachcloud.common.util.*;
+import com.qmth.teachcloud.mark.entity.MarkPaper;
+import com.qmth.teachcloud.mark.service.MarkPaperService;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.commons.io.FilenameUtils;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.poi.ss.usermodel.FillPatternType;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.HorizontalAlignment;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.xssf.usermodel.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.context.annotation.Lazy;
@@ -48,8 +59,11 @@ import org.springframework.util.FileCopyUtils;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
 import java.io.*;
 import java.math.BigDecimal;
+import java.net.URLEncoder;
 import java.nio.charset.StandardCharsets;
 import java.util.*;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -157,6 +171,12 @@ public class PrintCommonServiceImpl implements PrintCommonService {
     @Resource
     RedisCounterUtil redisCounterUtil;
 
+    @Resource
+    MarkPaperService markPaperService;
+
+    @Resource
+    TCUsualScoreMapper tcUsualScoreMapper;
+
     /**
      * 保存附件
      *
@@ -318,6 +338,138 @@ public class PrintCommonServiceImpl implements PrintCommonService {
         return jsonObject.toJSONString();
     }
 
+    /**
+     * 成绩管理导入excel校验
+     *
+     * @param file
+     * @param examId
+     * @param paperNumber
+     * @return
+     */
+    @Override
+    public MarkPaper scoreImportExcelVaild(MultipartFile file, Long examId, String paperNumber) throws IOException {
+        String reqFileMd5 = ServletUtil.getRequestMd5();
+        String fileMd5 = DigestUtils.md5Hex(file.getBytes());
+        if (!Objects.equals(fileMd5, reqFileMd5)) {
+            throw ExceptionResultEnum.MD5_EQUALS_FALSE.exception();
+        }
+        MarkPaper markPaper = markPaperService.getByExamIdAndPaperNumber(examId, paperNumber);
+        Objects.requireNonNull(markPaper, "未找到科目信息");
+        return markPaper;
+    }
+
+    /**
+     * 成绩管理动态生成excel
+     *
+     * @param describe
+     * @param sheetName
+     * @param fileName
+     * @param excelFieldList
+     * @throws IOException
+     */
+    @Override
+    public void scoreDownLoadExaminationTemplate(String describe, String sheetName, String fileName, List<ExcelField> excelFieldList) throws IOException {
+        HttpServletResponse response = ServletUtil.getResponse();
+        log.debug("导出Excel开始...");
+        XSSFWorkbook wb = new XSSFWorkbook();
+        response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, SystemConstant.CHARSET_NAME) + ExcelUtil.DEFALUT_EXT);
+        response.setContentType(ExcelUtil.DEFALUT_CONTENT_TYPE);
+        XSSFSheet sheet = wb.createSheet(sheetName);
+
+        Font headFont = wb.createFont();
+        headFont.setFontHeightInPoints((short) 12);
+        headFont.setFontName("宋体");
+        headFont.setBold(true);
+
+        Font defaultFont = wb.createFont();
+        defaultFont.setFontHeightInPoints((short) 12);
+        defaultFont.setFontName("宋体");
+
+        Font describeFont = wb.createFont();
+        describeFont.setFontHeightInPoints((short) 12);
+        describeFont.setFontName("宋体");
+        describeFont.setColor(IndexedColors.RED.getIndex());
+
+        int cellCount = excelFieldList.size();
+        // 说明
+        XSSFCellStyle describeStyle = wb.createCellStyle();
+        describeStyle.setAlignment(HorizontalAlignment.LEFT);
+        describeStyle.setFont(describeFont);
+        describe = describe.trim();
+        XSSFRow rowDescribe = sheet.createRow(0);
+        rowDescribe.setHeightInPoints(195); //行高设置成195px
+        for (int i = 0; i < cellCount; i++) {
+            XSSFCell cell = rowDescribe.createCell(i);
+            if (i == 0) {
+                cell.setCellValue(describe);
+                cell.setCellStyle(describeStyle);
+            }
+        }
+        CellRangeAddress region = new CellRangeAddress(0, 0, 0, cellCount - 1);
+        sheet.addMergedRegion(region);
+
+        // 表头行
+        XSSFCellStyle headerStyle = wb.createCellStyle();
+        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+        headerStyle.setAlignment(HorizontalAlignment.CENTER);
+        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
+        headerStyle.setFont(headFont);
+        XSSFRow rowHead = sheet.createRow(1);
+        for (int i = 0; i < excelFieldList.size(); i++) {
+            XSSFCell cell = rowHead.createCell(i);
+            cell.setCellValue(excelFieldList.get(i).getName());
+            cell.setCellStyle(headerStyle);
+            if (excelFieldList.get(i).getComment()) {
+                // 前四个参数是坐标点,后四个参数是编辑和显示批注时的大小.
+                XSSFDrawing p = sheet.createDrawingPatriarch();
+                XSSFComment comment = p.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
+                // 输入批注信息
+                comment.setString(new XSSFRichTextString("必填"));
+                cell.setCellComment(comment);
+            }
+        }
+
+        // 样例行
+        XSSFCellStyle exampleStyle = wb.createCellStyle();
+        exampleStyle.setAlignment(HorizontalAlignment.LEFT);
+        exampleStyle.setFont(defaultFont);
+        XSSFRow rowExample = sheet.createRow(2);
+        for (int i = 0; i < excelFieldList.size(); i++) {
+            XSSFCell cell = rowExample.createCell(i);
+            if (excelFieldList.get(i).getCode().startsWith("score")) {
+                cell.setCellValue(new Random().nextInt(100) + 1);
+            } else if (excelFieldList.get(i).getCode().startsWith("key")) {
+                cell.setCellValue(new Random().nextInt(10) + 1);
+            } else {
+                cell.setCellValue(excelFieldList.get(i).getValue());
+            }
+            cell.setCellStyle(exampleStyle);
+        }
+
+        for (int i = 0; i < cellCount; i++) {
+            sheet.autoSizeColumn(i);
+            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
+        }
+        ServletOutputStream outputStream = response.getOutputStream();
+        wb.write(outputStream);
+        outputStream.flush();
+        outputStream.close();
+        log.debug("导出Excel结束...");
+    }
+
+    /**
+     * 成绩管理列表
+     *
+     * @param iPage
+     * @param examId
+     * @param courseCode
+     * @return
+     */
+    @Override
+    public IPage<ScoreResult> scoreList(IPage<Map> iPage, Long examId, String courseCode) {
+        return tcUsualScoreMapper.scoreList(iPage, examId, courseCode);
+    }
+
     /**
      * 保存html附件
      *

+ 135 - 1
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/impl/TCFinalScoreServiceImpl.java

@@ -1,10 +1,34 @@
 package com.qmth.distributed.print.business.service.impl;
 
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.qmth.boot.api.exception.ApiException;
 import com.qmth.distributed.print.business.entity.TCFinalScore;
 import com.qmth.distributed.print.business.mapper.TCFinalScoreMapper;
+import com.qmth.distributed.print.business.service.PrintCommonService;
 import com.qmth.distributed.print.business.service.TCFinalScoreService;
-import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.qmth.teachcloud.common.contant.SystemConstant;
+import com.qmth.teachcloud.common.entity.SysUser;
+import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
+import com.qmth.teachcloud.common.enums.FieldUniqueEnum;
+import com.qmth.teachcloud.common.util.JacksonUtil;
+import com.qmth.teachcloud.common.util.ResultUtil;
+import com.qmth.teachcloud.common.util.ServletUtil;
+import com.qmth.teachcloud.mark.entity.MarkPaper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.dao.DuplicateKeyException;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.CollectionUtils;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import java.io.IOException;
+import java.util.*;
 
 /**
  * <p>
@@ -16,5 +40,115 @@ import org.springframework.stereotype.Service;
  */
 @Service
 public class TCFinalScoreServiceImpl extends ServiceImpl<TCFinalScoreMapper, TCFinalScore> implements TCFinalScoreService {
+    private final static Logger log = LoggerFactory.getLogger(TCFinalScoreServiceImpl.class);
+
+    @Resource
+    PrintCommonService printCommonService;
+
+    @Resource
+    TCFinalScoreService tcFinalScoreService;
+
+    /**
+     * 导入期末成绩excel
+     *
+     * @param file
+     * @param examId
+     * @param courseCode
+     * @param paperNumber
+     * @return
+     * @throws IOException
+     */
+    @Override
+    @Transactional
+    public Map<String, String> finalScoreExcelImport(MultipartFile file, Long examId, String courseCode, String paperNumber) throws IOException {
+        log.debug("导入Excel开始...");
+        long start = System.currentTimeMillis();
+        MarkPaper markPaper = printCommonService.scoreImportExcelVaild(file, examId, paperNumber);
+
+        Map<String, String> messageMap = new LinkedHashMap<>();
+        try {
+            StringJoiner errorData = new StringJoiner("");
+            StringJoiner successData = new StringJoiner("");
+            List<Map<String, String>> list = EasyExcel.read(file.getInputStream()).headRowNumber(1).sheet(0).doReadSync();
+            log.info("list:{}", JacksonUtil.parseJson(list));
+
+            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
+            List<TCFinalScore> tcFinalScoreList = new ArrayList<>(list.size());
+            Map<String, String> headMap = list.get(0);
+            for (Map.Entry<String, String> entry : headMap.entrySet()) {
+                if (Objects.equals(entry.getKey(), 0) && Objects.nonNull(entry.getValue()) &&
+                        !Objects.equals(entry.getValue().trim(), "学号")) {
+                    throw ExceptionResultEnum.ERROR.exception("excel表头第一行为学号");
+                } else if (Objects.equals(entry.getKey(), 1) && Objects.nonNull(entry.getValue()) &&
+                        !Objects.equals(entry.getValue().trim(), "姓名")) {
+                    throw ExceptionResultEnum.ERROR.exception("excel表头第二行为姓名");
+                } else if (Objects.equals(entry.getKey(), 2) && Objects.nonNull(entry.getValue()) &&
+                        !Objects.equals(entry.getValue().trim(), "成绩")) {
+                    throw ExceptionResultEnum.ERROR.exception("excel表头第三行为成绩");
+                }
+            }
+
+            for (int i = 1; i < list.size(); i++) {
+                Map<String, String> objectMap = list.get(i);
+                boolean error = false;
+                JSONArray jsonArray = new JSONArray();
+                TCFinalScore tcFinalScore = new TCFinalScore(examId, courseCode, markPaper.getCourseName(), paperNumber, sysUser.getId());
+                for (Map.Entry<String, String> entry : objectMap.entrySet()) {
+                    JSONObject jsonObject = new JSONObject();
+                    if (Objects.isNull(entry.getValue()) || Objects.equals(entry.getValue().trim(), "")) {
+                        errorData.add("excel第" + i + "行[").add(headMap.get(entry.getKey()) + "]为空;").add("\r\n");
+                        error = true;
+                    } else {
+                        String head = headMap.get(entry.getKey());
+                        Objects.requireNonNull(head, "表头信息异常");
+                        if (Objects.equals(head.trim(), "学号")) {
+                            tcFinalScore.setStudentCode(entry.getValue());
+                        } else if (Objects.equals(head.trim(), "姓名")) {
+                            tcFinalScore.setName(entry.getValue());
+                        } else if (Objects.equals(head.trim(), "成绩")) {
+                            tcFinalScore.setScore(Double.valueOf(entry.getValue()));
+                        } else {
+                            jsonObject.put("name", headMap.get(entry.getKey()));
+                            jsonObject.put("score", entry.getValue());
+                            jsonArray.add(jsonObject);
+                        }
+                    }
+                }
+                if (jsonArray.size() > 0) {
+                    tcFinalScore.setScoreDetail(jsonArray.toJSONString());
+                }
+                if (!error) {
+                    tcFinalScoreList.add(tcFinalScore);
+                }
+            }
+            if (!CollectionUtils.isEmpty(tcFinalScoreList)) {
+                successData.add("共导入" + tcFinalScoreList.size() + "条数据");
 
+                QueryWrapper<TCFinalScore> tcScoreEndExamQueryWrapper = new QueryWrapper<>();
+                tcScoreEndExamQueryWrapper.lambda().eq(TCFinalScore::getExamId, examId)
+                        .eq(TCFinalScore::getCourseCode, courseCode)
+                        .eq(TCFinalScore::getCourseName, markPaper.getCourseName())
+                        .eq(TCFinalScore::getPaperNumber, paperNumber);
+                tcFinalScoreService.remove(tcScoreEndExamQueryWrapper);
+                tcFinalScoreService.saveBatch(tcFinalScoreList);
+            }
+            messageMap.put("正确信息", successData.length() > 0 ? successData.toString() : "无");
+            messageMap.put("错误信息", errorData.length() > 0 ? errorData.toString() : "无");
+        } catch (Exception e) {
+            log.error(SystemConstant.LOG_ERROR, e);
+            if (e instanceof DuplicateKeyException) {
+                String errorColumn = e.getCause().toString();
+                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
+                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
+            } else if (e instanceof ApiException) {
+                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
+            } else {
+                ResultUtil.error(e.getMessage());
+            }
+        }
+        log.debug("导入Excel结束...");
+        long end = System.currentTimeMillis();
+        log.info("============耗时{}秒============:", (end - start) / 1000);
+        return messageMap;
+    }
 }

+ 101 - 133
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/impl/TCUsualScoreServiceImpl.java

@@ -1,37 +1,34 @@
 package com.qmth.distributed.print.business.service.impl;
 
-import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-import com.qmth.distributed.print.business.bean.excel.ExcelField;
-import com.qmth.distributed.print.business.bean.result.ScoreResult;
+import com.qmth.boot.api.exception.ApiException;
 import com.qmth.distributed.print.business.entity.TCUsualScore;
 import com.qmth.distributed.print.business.mapper.TCUsualScoreMapper;
+import com.qmth.distributed.print.business.service.PrintCommonService;
 import com.qmth.distributed.print.business.service.TCUsualScoreService;
 import com.qmth.teachcloud.common.contant.SystemConstant;
+import com.qmth.teachcloud.common.entity.SysUser;
 import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
-import com.qmth.teachcloud.common.util.ExcelUtil;
+import com.qmth.teachcloud.common.enums.FieldUniqueEnum;
+import com.qmth.teachcloud.common.util.JacksonUtil;
+import com.qmth.teachcloud.common.util.ResultUtil;
 import com.qmth.teachcloud.common.util.ServletUtil;
 import com.qmth.teachcloud.mark.entity.MarkPaper;
-import com.qmth.teachcloud.mark.service.MarkPaperService;
-import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.poi.ss.usermodel.FillPatternType;
-import org.apache.poi.ss.usermodel.Font;
-import org.apache.poi.ss.usermodel.HorizontalAlignment;
-import org.apache.poi.ss.usermodel.IndexedColors;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.xssf.usermodel.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.dao.DuplicateKeyException;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.CollectionUtils;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
-import java.net.URLEncoder;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Random;
+import java.util.*;
 
 /**
  * <p>
@@ -43,139 +40,110 @@ import java.util.Random;
  */
 @Service
 public class TCUsualScoreServiceImpl extends ServiceImpl<TCUsualScoreMapper, TCUsualScore> implements TCUsualScoreService {
+    private final static Logger log = LoggerFactory.getLogger(TCUsualScoreServiceImpl.class);
 
     @Resource
-    MarkPaperService markPaperService;
+    PrintCommonService printCommonService;
+
+    @Resource
+    TCUsualScoreService tcUsualScoreService;
 
     /**
-     * 成绩管理列表
+     * 导入平时成绩excel
      *
-     * @param iPage
+     * @param file
      * @param examId
      * @param courseCode
+     * @param paperNumber
      * @return
-     */
-    @Override
-    public IPage<ScoreResult> scoreList(IPage<Map> iPage, Long examId, String courseCode) {
-        return this.baseMapper.scoreList(iPage, examId, courseCode);
-    }
-
-    /**
-     * 动态生成excel
-     *
-     * @param describe
-     * @param sheetName
-     * @param fileName
-     * @param excelFieldList
      * @throws IOException
      */
     @Override
-    public void downLoadExaminationTemplate(String describe, String sheetName, String fileName, List<ExcelField> excelFieldList) throws IOException {
-        HttpServletResponse response = ServletUtil.getResponse();
-        log.debug("导出Excel开始...");
-        XSSFWorkbook wb = new XSSFWorkbook();
-        response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, SystemConstant.CHARSET_NAME) + ExcelUtil.DEFALUT_EXT);
-        response.setContentType(ExcelUtil.DEFALUT_CONTENT_TYPE);
-        XSSFSheet sheet = wb.createSheet(sheetName);
-
-        Font headFont = wb.createFont();
-        headFont.setFontHeightInPoints((short) 12);
-        headFont.setFontName("宋体");
-        headFont.setBold(true);
+    @Transactional
+    public Map<String, String> usualScoreExcelImport(MultipartFile file, Long examId, String courseCode, String paperNumber) throws IOException {
+        log.debug("导入Excel开始...");
+        long start = System.currentTimeMillis();
+        MarkPaper markPaper = printCommonService.scoreImportExcelVaild(file, examId, paperNumber);
 
-        Font defaultFont = wb.createFont();
-        defaultFont.setFontHeightInPoints((short) 12);
-        defaultFont.setFontName("宋体");
+        Map<String, String> messageMap = new LinkedHashMap<>();
+        try {
+            StringJoiner errorData = new StringJoiner("");
+            StringJoiner successData = new StringJoiner("");
+            List<Map<String, String>> list = EasyExcel.read(file.getInputStream()).headRowNumber(1).sheet(0).doReadSync();
+            log.info("list:{}", JacksonUtil.parseJson(list));
 
-        Font describeFont = wb.createFont();
-        describeFont.setFontHeightInPoints((short) 12);
-        describeFont.setFontName("宋体");
-        describeFont.setColor(IndexedColors.RED.getIndex());
-
-        int cellCount = excelFieldList.size();
-        // 说明
-        XSSFCellStyle describeStyle = wb.createCellStyle();
-        describeStyle.setAlignment(HorizontalAlignment.LEFT);
-        describeStyle.setFont(describeFont);
-        describe = describe.trim();
-        XSSFRow rowDescribe = sheet.createRow(0);
-        rowDescribe.setHeightInPoints(195); //行高设置成195px
-        for (int i = 0; i < cellCount; i++) {
-            XSSFCell cell = rowDescribe.createCell(i);
-            if (i == 0) {
-                cell.setCellValue(describe);
-                cell.setCellStyle(describeStyle);
+            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
+            List<TCUsualScore> tcUsualScoreList = new ArrayList<>(list.size());
+            Map<String, String> headMap = list.get(0);
+            for (Map.Entry<String, String> entry : headMap.entrySet()) {
+                if (Objects.equals(entry.getKey(), 0) && Objects.nonNull(entry.getValue()) &&
+                        !Objects.equals(entry.getValue().trim(), "学号")) {
+                    throw ExceptionResultEnum.ERROR.exception("excel表头第一行为学号");
+                } else if (Objects.equals(entry.getKey(), 1) && Objects.nonNull(entry.getValue()) &&
+                        !Objects.equals(entry.getValue().trim(), "姓名")) {
+                    throw ExceptionResultEnum.ERROR.exception("excel表头第二行为姓名");
+                }
             }
-        }
-        CellRangeAddress region = new CellRangeAddress(0, 0, 0, cellCount - 1);
-        sheet.addMergedRegion(region);
 
-        // 表头行
-        XSSFCellStyle headerStyle = wb.createCellStyle();
-        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
-        headerStyle.setAlignment(HorizontalAlignment.CENTER);
-        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
-        headerStyle.setFont(headFont);
-        XSSFRow rowHead = sheet.createRow(1);
-        for (int i = 0; i < excelFieldList.size(); i++) {
-            XSSFCell cell = rowHead.createCell(i);
-            cell.setCellValue(excelFieldList.get(i).getName());
-            cell.setCellStyle(headerStyle);
-            if (excelFieldList.get(i).getComment()) {
-                // 前四个参数是坐标点,后四个参数是编辑和显示批注时的大小.
-                XSSFDrawing p = sheet.createDrawingPatriarch();
-                XSSFComment comment = p.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
-                // 输入批注信息
-                comment.setString(new XSSFRichTextString("必填"));
-                cell.setCellComment(comment);
+            for (int i = 1; i < list.size(); i++) {
+                Map<String, String> objectMap = list.get(i);
+                boolean error = false;
+                JSONArray jsonArray = new JSONArray();
+                TCUsualScore tcUsualScore = new TCUsualScore(examId, courseCode, markPaper.getCourseName(), paperNumber, sysUser.getId());
+                for (Map.Entry<String, String> entry : objectMap.entrySet()) {
+                    JSONObject jsonObject = new JSONObject();
+                    if (Objects.isNull(entry.getValue()) || Objects.equals(entry.getValue().trim(), "")) {
+                        errorData.add("excel第" + i + "行[").add(headMap.get(entry.getKey()) + "]为空;").add("\r\n");
+                        error = true;
+                    } else {
+                        String head = headMap.get(entry.getKey());
+                        Objects.requireNonNull(head, "表头信息异常");
+                        if (Objects.equals(head.trim(), "学号")) {
+                            tcUsualScore.setStudentCode(entry.getValue());
+                        } else if (Objects.equals(head.trim(), "姓名")) {
+                            tcUsualScore.setName(entry.getValue());
+                        } else {
+                            jsonObject.put("name", headMap.get(entry.getKey()));
+                            jsonObject.put("score", entry.getValue());
+                            jsonArray.add(jsonObject);
+                        }
+                    }
+                }
+                if (jsonArray.size() > 0) {
+                    tcUsualScore.setScore(jsonArray.toJSONString());
+                }
+                if (!error) {
+                    tcUsualScoreList.add(tcUsualScore);
+                }
             }
-        }
+            if (!CollectionUtils.isEmpty(tcUsualScoreList)) {
+                successData.add("共导入" + tcUsualScoreList.size() + "条数据");
 
-        // 样例行
-        XSSFCellStyle exampleStyle = wb.createCellStyle();
-        exampleStyle.setAlignment(HorizontalAlignment.LEFT);
-        exampleStyle.setFont(defaultFont);
-        XSSFRow rowExample = sheet.createRow(2);
-        for (int i = 0; i < excelFieldList.size(); i++) {
-            XSSFCell cell = rowExample.createCell(i);
-            if (excelFieldList.get(i).getCode().startsWith("score")) {
-                cell.setCellValue(new Random().nextInt(100) + 1);
-            } else if (excelFieldList.get(i).getCode().startsWith("key")) {
-                cell.setCellValue(new Random().nextInt(10) + 1);
+                QueryWrapper<TCUsualScore> tcScoreNormalQueryWrapper = new QueryWrapper<>();
+                tcScoreNormalQueryWrapper.lambda().eq(TCUsualScore::getExamId, examId)
+                        .eq(TCUsualScore::getCourseCode, courseCode)
+                        .eq(TCUsualScore::getCourseName, markPaper.getCourseName())
+                        .eq(TCUsualScore::getPaperNumber, paperNumber);
+                tcUsualScoreService.remove(tcScoreNormalQueryWrapper);
+                tcUsualScoreService.saveBatch(tcUsualScoreList);
+            }
+            messageMap.put("正确信息", successData.length() > 0 ? successData.toString() : "无");
+            messageMap.put("错误信息", errorData.length() > 0 ? errorData.toString() : "无");
+        } catch (Exception e) {
+            log.error(SystemConstant.LOG_ERROR, e);
+            if (e instanceof DuplicateKeyException) {
+                String errorColumn = e.getCause().toString();
+                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
+                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
+            } else if (e instanceof ApiException) {
+                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
             } else {
-                cell.setCellValue(excelFieldList.get(i).getValue());
+                ResultUtil.error(e.getMessage());
             }
-            cell.setCellStyle(exampleStyle);
-        }
-
-        for (int i = 0; i < cellCount; i++) {
-            sheet.autoSizeColumn(i);
-            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
-        }
-        ServletOutputStream outputStream = response.getOutputStream();
-        wb.write(outputStream);
-        outputStream.flush();
-        outputStream.close();
-        log.debug("导出Excel结束...");
-    }
-
-    /**
-     * 导入excel校验
-     *
-     * @param file
-     * @param examId
-     * @param paperNumber
-     * @return
-     */
-    @Override
-    public MarkPaper importExcelVaild(MultipartFile file, Long examId, String paperNumber) throws IOException {
-        String reqFileMd5 = ServletUtil.getRequestMd5();
-        String fileMd5 = DigestUtils.md5Hex(file.getBytes());
-        if (!Objects.equals(fileMd5, reqFileMd5)) {
-            throw ExceptionResultEnum.MD5_EQUALS_FALSE.exception();
         }
-        MarkPaper markPaper = markPaperService.getByExamIdAndPaperNumber(examId, paperNumber);
-        Objects.requireNonNull(markPaper, "未找到科目信息");
-        return markPaper;
+        log.debug("导入Excel结束...");
+        long end = System.currentTimeMillis();
+        log.info("============耗时{}秒============:", (end - start) / 1000);
+        return messageMap;
     }
 }

+ 21 - 108
distributed-print/src/main/java/com/qmth/distributed/print/api/TCFinalScoreController.java

@@ -1,31 +1,21 @@
 package com.qmth.distributed.print.api;
 
-import com.alibaba.excel.EasyExcel;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.qmth.boot.api.constant.ApiConstant;
-import com.qmth.boot.api.exception.ApiException;
 import com.qmth.distributed.print.business.bean.excel.ExcelField;
 import com.qmth.distributed.print.business.bean.result.EditResult;
-import com.qmth.distributed.print.business.entity.TCFinalScore;
+import com.qmth.distributed.print.business.service.PrintCommonService;
 import com.qmth.distributed.print.business.service.TCFinalScoreService;
 import com.qmth.distributed.print.business.service.TCUsualScoreService;
 import com.qmth.teachcloud.common.annotation.OperationLogDetail;
 import com.qmth.teachcloud.common.contant.SystemConstant;
-import com.qmth.teachcloud.common.entity.SysUser;
+import com.qmth.teachcloud.common.entity.MarkQuestion;
 import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
-import com.qmth.teachcloud.common.enums.FieldUniqueEnum;
 import com.qmth.teachcloud.common.enums.log.CustomizedOperationTypeEnum;
-import com.qmth.teachcloud.common.util.JacksonUtil;
 import com.qmth.teachcloud.common.util.ResultUtil;
-import com.qmth.teachcloud.common.util.ServletUtil;
-import com.qmth.teachcloud.mark.entity.MarkPaper;
+import com.qmth.teachcloud.mark.service.MarkQuestionService;
 import io.swagger.annotations.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.dao.DuplicateKeyException;
-import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.CollectionUtils;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
@@ -34,7 +24,8 @@ import javax.annotation.Resource;
 import javax.validation.constraints.Max;
 import javax.validation.constraints.Min;
 import java.io.IOException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * <p>
@@ -51,11 +42,14 @@ public class TCFinalScoreController {
     private final static Logger log = LoggerFactory.getLogger(TCFinalScoreController.class);
 
     @Resource
-    TCUsualScoreService tcUsualScoreService;
+    PrintCommonService printCommonService;
 
     @Resource
     TCFinalScoreService tcFinalScoreService;
 
+    @Resource
+    MarkQuestionService markQuestionService;
+
     @ApiOperation(value = "导入期末成绩-模板下载")
     @RequestMapping(value = "/final_score/template_download", method = RequestMethod.POST)
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.EXPORT)
@@ -63,13 +57,21 @@ public class TCFinalScoreController {
     public void finalScoreTemplateDownload(@ApiParam(value = "考试id", required = true) @RequestParam Long examId,
                                            @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
                                            @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) throws IOException {
+        List<MarkQuestion> markQuestionList = markQuestionService.listQuestionByExamIdAndPaperNumberAndPaperType(examId, paperNumber, null);
+        if (CollectionUtils.isEmpty(markQuestionList)) {
+            throw ExceptionResultEnum.ERROR.exception("未找到试卷结构");
+        }
+
         List<ExcelField> excelFieldList = new ArrayList<>();
         excelFieldList.add(new ExcelField("studentCode", "学号", true));
         excelFieldList.add(new ExcelField("name", "姓名", true));
         excelFieldList.add(new ExcelField("score", "成绩", true));
-        excelFieldList.add(new ExcelField("key1", "1-1", true));
-        excelFieldList.add(new ExcelField("key2", "1-2", false));
-        tcUsualScoreService.downLoadExaminationTemplate("1、所有字段均为必填字段;\n" +
+
+        for (int i = 0; i < markQuestionList.size(); i++) {
+            MarkQuestion markQuestion = markQuestionList.get(i);
+            excelFieldList.add(new ExcelField("key" + (i + 1), markQuestion.getMainNumber() + "-" + markQuestion.getSubNumber(), true));
+        }
+        printCommonService.scoreDownLoadExaminationTemplate("1、所有字段均为必填字段;\n" +
                 "2、期末成绩按总分,和小题分录入,题号按大题号-小题号方式录入,如下,1-1表示第一大题第一小题,2-1表示第二大题第一小题;\n" +
                 "3、请不要删除此行,也不要删除模板中的任何列;\n" +
                 "4、使用前请先删除样例数据。", "sheet1", "期末成绩导入模版", excelFieldList);
@@ -79,100 +81,11 @@ public class TCFinalScoreController {
     @RequestMapping(value = "/final_score/import", method = RequestMethod.POST)
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.IMPORT)
     @ApiResponses({@ApiResponse(code = 200, message = "导入成功", response = EditResult.class)})
-    @Transactional
     public Object finalScoreExamImport(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file,
                                        @ApiParam(value = "考试id", required = true) @RequestParam Long examId,
                                        @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
                                        @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) throws IOException {
-        log.debug("导入Excel开始...");
-        long start = System.currentTimeMillis();
-        MarkPaper markPaper = tcUsualScoreService.importExcelVaild(file, examId, paperNumber);
-
-        Map<String, String> messageMap = new LinkedHashMap<>();
-        try {
-            StringJoiner errorData = new StringJoiner("");
-            StringJoiner successData = new StringJoiner("");
-            List<Map<String, String>> list = EasyExcel.read(file.getInputStream()).headRowNumber(1).sheet(0).doReadSync();
-            log.info("list:{}", JacksonUtil.parseJson(list));
-
-            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
-            List<TCFinalScore> tcFinalScoreList = new ArrayList<>(list.size());
-            Map<String, String> headMap = list.get(0);
-            for (Map.Entry<String, String> entry : headMap.entrySet()) {
-                if (Objects.equals(entry.getKey(), 0) && Objects.nonNull(entry.getValue()) &&
-                        !Objects.equals(entry.getValue().trim(), "学号")) {
-                    throw ExceptionResultEnum.ERROR.exception("excel表头第一行为学号");
-                } else if (Objects.equals(entry.getKey(), 1) && Objects.nonNull(entry.getValue()) &&
-                        !Objects.equals(entry.getValue().trim(), "姓名")) {
-                    throw ExceptionResultEnum.ERROR.exception("excel表头第二行为姓名");
-                } else if (Objects.equals(entry.getKey(), 2) && Objects.nonNull(entry.getValue()) &&
-                        !Objects.equals(entry.getValue().trim(), "成绩")) {
-                    throw ExceptionResultEnum.ERROR.exception("excel表头第三行为成绩");
-                }
-            }
-
-            for (int i = 1; i < list.size(); i++) {
-                Map<String, String> objectMap = list.get(i);
-                boolean error = false;
-                JSONArray jsonArray = new JSONArray();
-                TCFinalScore tcFinalScore = new TCFinalScore(examId, courseCode, markPaper.getCourseName(), paperNumber, sysUser.getId());
-                for (Map.Entry<String, String> entry : objectMap.entrySet()) {
-                    JSONObject jsonObject = new JSONObject();
-                    if (Objects.isNull(entry.getValue()) || Objects.equals(entry.getValue().trim(), "")) {
-                        errorData.add("excel第" + i + "行[").add(headMap.get(entry.getKey()) + "]为空;").add("\r\n");
-                        error = true;
-                    } else {
-                        String head = headMap.get(entry.getKey());
-                        Objects.requireNonNull(head, "表头信息异常");
-                        if (Objects.equals(head.trim(), "学号")) {
-                            tcFinalScore.setStudentCode(entry.getValue());
-                        } else if (Objects.equals(head.trim(), "姓名")) {
-                            tcFinalScore.setName(entry.getValue());
-                        } else if (Objects.equals(head.trim(), "成绩")) {
-                            tcFinalScore.setScore(Double.valueOf(entry.getValue()));
-                        } else {
-                            jsonObject.put("name", headMap.get(entry.getKey()));
-                            jsonObject.put("score", entry.getValue());
-                            jsonArray.add(jsonObject);
-                        }
-                    }
-                }
-                if (jsonArray.size() > 0) {
-                    tcFinalScore.setScoreDetail(jsonArray.toJSONString());
-                }
-                if (!error) {
-                    tcFinalScoreList.add(tcFinalScore);
-                }
-            }
-            if (!CollectionUtils.isEmpty(tcFinalScoreList)) {
-                successData.add("共导入" + tcFinalScoreList.size() + "条数据");
-
-                QueryWrapper<TCFinalScore> tcScoreEndExamQueryWrapper = new QueryWrapper<>();
-                tcScoreEndExamQueryWrapper.lambda().eq(TCFinalScore::getExamId, examId)
-                        .eq(TCFinalScore::getCourseCode, courseCode)
-                        .eq(TCFinalScore::getCourseName, markPaper.getCourseName())
-                        .eq(TCFinalScore::getPaperNumber, paperNumber);
-                tcFinalScoreService.remove(tcScoreEndExamQueryWrapper);
-                tcFinalScoreService.saveBatch(tcFinalScoreList);
-            }
-            messageMap.put("正确信息", successData.length() > 0 ? successData.toString() : "无");
-            messageMap.put("错误信息", errorData.length() > 0 ? errorData.toString() : "无");
-        } catch (Exception e) {
-            log.error(SystemConstant.LOG_ERROR, e);
-            if (e instanceof DuplicateKeyException) {
-                String errorColumn = e.getCause().toString();
-                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
-                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
-            } else if (e instanceof ApiException) {
-                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
-            } else {
-                ResultUtil.error(e.getMessage());
-            }
-        }
-        log.debug("导入Excel结束...");
-        long end = System.currentTimeMillis();
-        log.info("============耗时{}秒============:", (end - start) / 1000);
-        return ResultUtil.ok(messageMap);
+        return ResultUtil.ok(tcFinalScoreService.finalScoreExcelImport(file, examId, courseCode, paperNumber));
     }
 
     @ApiOperation(value = "期末成绩列表")

+ 21 - 114
distributed-print/src/main/java/com/qmth/distributed/print/api/TCUsualScoreController.java

@@ -1,33 +1,19 @@
 package com.qmth.distributed.print.api;
 
-import com.alibaba.excel.EasyExcel;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.qmth.boot.api.constant.ApiConstant;
-import com.qmth.boot.api.exception.ApiException;
 import com.qmth.distributed.print.business.bean.excel.ExcelField;
 import com.qmth.distributed.print.business.bean.result.EditResult;
 import com.qmth.distributed.print.business.bean.result.ScoreResult;
-import com.qmth.distributed.print.business.entity.TCUsualScore;
+import com.qmth.distributed.print.business.service.PrintCommonService;
 import com.qmth.distributed.print.business.service.TCUsualScoreService;
 import com.qmth.teachcloud.common.annotation.OperationLogDetail;
 import com.qmth.teachcloud.common.contant.SystemConstant;
-import com.qmth.teachcloud.common.entity.SysUser;
-import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
-import com.qmth.teachcloud.common.enums.FieldUniqueEnum;
 import com.qmth.teachcloud.common.enums.log.CustomizedOperationTypeEnum;
-import com.qmth.teachcloud.common.util.JacksonUtil;
 import com.qmth.teachcloud.common.util.ResultUtil;
-import com.qmth.teachcloud.common.util.ServletUtil;
-import com.qmth.teachcloud.mark.entity.MarkPaper;
 import io.swagger.annotations.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.dao.DuplicateKeyException;
-import org.springframework.transaction.annotation.Transactional;
-import org.springframework.util.CollectionUtils;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
@@ -38,7 +24,8 @@ import javax.annotation.Resource;
 import javax.validation.constraints.Max;
 import javax.validation.constraints.Min;
 import java.io.IOException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * <p>
@@ -57,6 +44,9 @@ public class TCUsualScoreController {
     @Resource
     TCUsualScoreService tcUsualScoreService;
 
+    @Resource
+    PrintCommonService printCommonService;
+
     @ApiOperation(value = "成绩管理列表")
     @RequestMapping(value = "/score/list", method = RequestMethod.POST)
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.SEARCH)
@@ -65,7 +55,7 @@ public class TCUsualScoreController {
                             @ApiParam(value = "课程编码") @RequestParam(required = false) String courseCode,
                             @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                             @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
-        return ResultUtil.ok(tcUsualScoreService.scoreList(new Page<>(pageNumber, pageSize), examId, courseCode));
+        return ResultUtil.ok(printCommonService.scoreList(new Page<>(pageNumber, pageSize), examId, courseCode));
     }
 
     @ApiOperation(value = "导入平时成绩-模板下载")
@@ -73,15 +63,16 @@ public class TCUsualScoreController {
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.EXPORT)
     @ApiResponses({@ApiResponse(code = 200, message = "下载成功", response = Object.class)})
     public void usualScoreTemplateDownload(@ApiParam(value = "考试id", required = true) @RequestParam Long examId,
-                                 @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
-                                 @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) throws IOException {
+                                           @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
+                                           @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) throws IOException {
+        //TODO 待曹子轩补充接口
         List<ExcelField> excelFieldList = new ArrayList<>();
         excelFieldList.add(new ExcelField("studentCode", "学号", true));
         excelFieldList.add(new ExcelField("name", "姓名", true));
         excelFieldList.add(new ExcelField("score1", "作业1", true));
         excelFieldList.add(new ExcelField("score2", "作业2", true));
         excelFieldList.add(new ExcelField("score3", "作业3", false));
-        tcUsualScoreService.downLoadExaminationTemplate("1、所有字段均为必填字段;\n" +
+        printCommonService.scoreDownLoadExaminationTemplate("1、所有字段均为必填字段;\n" +
                 "2、平时成绩各项数据均需要填写;\n" +
                 "3、请不要删除此行,也不要删除模板中的任何列。\n" +
                 "4、使用前请先删除样例数据。", "sheet1", "平时成绩导入模版", excelFieldList);
@@ -91,95 +82,11 @@ public class TCUsualScoreController {
     @RequestMapping(value = "/usual_score/import", method = RequestMethod.POST)
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.IMPORT)
     @ApiResponses({@ApiResponse(code = 200, message = "导入成功", response = EditResult.class)})
-    @Transactional
     public Object usualScoreImport(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file,
-                              @ApiParam(value = "考试id", required = true) @RequestParam Long examId,
-                              @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
-                              @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) throws IOException {
-        log.debug("导入Excel开始...");
-        long start = System.currentTimeMillis();
-        MarkPaper markPaper = tcUsualScoreService.importExcelVaild(file, examId, paperNumber);
-
-        Map<String, String> messageMap = new LinkedHashMap<>();
-        try {
-            StringJoiner errorData = new StringJoiner("");
-            StringJoiner successData = new StringJoiner("");
-            List<Map<String, String>> list = EasyExcel.read(file.getInputStream()).headRowNumber(1).sheet(0).doReadSync();
-            log.info("list:{}", JacksonUtil.parseJson(list));
-
-            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
-            List<TCUsualScore> tcUsualScoreList = new ArrayList<>(list.size());
-            Map<String, String> headMap = list.get(0);
-            for (Map.Entry<String, String> entry : headMap.entrySet()) {
-                if (Objects.equals(entry.getKey(), 0) && Objects.nonNull(entry.getValue()) &&
-                        !Objects.equals(entry.getValue().trim(), "学号")) {
-                    throw ExceptionResultEnum.ERROR.exception("excel表头第一行为学号");
-                } else if (Objects.equals(entry.getKey(), 1) && Objects.nonNull(entry.getValue()) &&
-                        !Objects.equals(entry.getValue().trim(), "姓名")) {
-                    throw ExceptionResultEnum.ERROR.exception("excel表头第二行为姓名");
-                }
-            }
-
-            for (int i = 1; i < list.size(); i++) {
-                Map<String, String> objectMap = list.get(i);
-                boolean error = false;
-                JSONArray jsonArray = new JSONArray();
-                TCUsualScore tcUsualScore = new TCUsualScore(examId, courseCode, markPaper.getCourseName(), paperNumber, sysUser.getId());
-                for (Map.Entry<String, String> entry : objectMap.entrySet()) {
-                    JSONObject jsonObject = new JSONObject();
-                    if (Objects.isNull(entry.getValue()) || Objects.equals(entry.getValue().trim(), "")) {
-                        errorData.add("excel第" + i + "行[").add(headMap.get(entry.getKey()) + "]为空;").add("\r\n");
-                        error = true;
-                    } else {
-                        String head = headMap.get(entry.getKey());
-                        Objects.requireNonNull(head, "表头信息异常");
-                        if (Objects.equals(head.trim(), "学号")) {
-                            tcUsualScore.setStudentCode(entry.getValue());
-                        } else if (Objects.equals(head.trim(), "姓名")) {
-                            tcUsualScore.setName(entry.getValue());
-                        } else {
-                            jsonObject.put("name", headMap.get(entry.getKey()));
-                            jsonObject.put("score", entry.getValue());
-                            jsonArray.add(jsonObject);
-                        }
-                    }
-                }
-                if (jsonArray.size() > 0) {
-                    tcUsualScore.setScore(jsonArray.toJSONString());
-                }
-                if (!error) {
-                    tcUsualScoreList.add(tcUsualScore);
-                }
-            }
-            if (!CollectionUtils.isEmpty(tcUsualScoreList)) {
-                successData.add("共导入" + tcUsualScoreList.size() + "条数据");
-
-                QueryWrapper<TCUsualScore> tcScoreNormalQueryWrapper = new QueryWrapper<>();
-                tcScoreNormalQueryWrapper.lambda().eq(TCUsualScore::getExamId, examId)
-                        .eq(TCUsualScore::getCourseCode, courseCode)
-                        .eq(TCUsualScore::getCourseName, markPaper.getCourseName())
-                        .eq(TCUsualScore::getPaperNumber, paperNumber);
-                tcUsualScoreService.remove(tcScoreNormalQueryWrapper);
-                tcUsualScoreService.saveBatch(tcUsualScoreList);
-            }
-            messageMap.put("正确信息", successData.length() > 0 ? successData.toString() : "无");
-            messageMap.put("错误信息", errorData.length() > 0 ? errorData.toString() : "无");
-        } catch (Exception e) {
-            log.error(SystemConstant.LOG_ERROR, e);
-            if (e instanceof DuplicateKeyException) {
-                String errorColumn = e.getCause().toString();
-                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
-                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
-            } else if (e instanceof ApiException) {
-                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
-            } else {
-                ResultUtil.error(e.getMessage());
-            }
-        }
-        log.debug("导入Excel结束...");
-        long end = System.currentTimeMillis();
-        log.info("============耗时{}秒============:", (end - start) / 1000);
-        return ResultUtil.ok(messageMap);
+                                   @ApiParam(value = "考试id", required = true) @RequestParam Long examId,
+                                   @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
+                                   @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) throws IOException {
+        return ResultUtil.ok(tcUsualScoreService.usualScoreExcelImport(file, examId, courseCode, paperNumber));
     }
 
     @ApiOperation(value = "平时成绩列表")
@@ -187,10 +94,10 @@ public class TCUsualScoreController {
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.SEARCH)
     @ApiResponses({@ApiResponse(code = 200, message = "分页查询", response = EditResult.class)})
     public Object usualScoreList(@ApiParam(value = "考试id", required = true) @RequestParam Long examId,
-                                  @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
-                                  @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber,
-                                  @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
-                                  @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) throws IOException {
+                                 @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
+                                 @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber,
+                                 @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
+                                 @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) throws IOException {
         return ResultUtil.ok(true);
     }
 
@@ -207,7 +114,7 @@ public class TCUsualScoreController {
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.UPDATE)
     @ApiResponses({@ApiResponse(code = 200, message = "保存", response = EditResult.class)})
     public Object usualScoreSave(@ApiParam(value = "主键", required = true) @RequestParam Long id,
-                                  @ApiParam(value = "平时成绩json", required = true) @RequestParam String socreNormal) throws IOException {
+                                 @ApiParam(value = "平时成绩json", required = true) @RequestParam String socreNormal) throws IOException {
         return ResultUtil.ok(true);
     }
 
@@ -216,7 +123,7 @@ public class TCUsualScoreController {
     @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.UPDATE)
     @ApiResponses({@ApiResponse(code = 200, message = "编辑", response = EditResult.class)})
     public Object usualScoreEnable(@ApiParam(value = "主键", required = true) @RequestParam Long id,
-                                    @ApiParam(value = "启用/禁用", required = true) @RequestParam Boolean enable) throws IOException {
+                                   @ApiParam(value = "启用/禁用", required = true) @RequestParam Boolean enable) throws IOException {
         return ResultUtil.ok(true);
     }
 }

+ 3 - 3
distributed-print/src/main/java/com/qmth/distributed/print/api/TRBasicInfoController.java

@@ -3,7 +3,7 @@ package com.qmth.distributed.print.api;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.qmth.boot.api.constant.ApiConstant;
 import com.qmth.distributed.print.business.bean.result.ScoreResult;
-import com.qmth.distributed.print.business.service.TCUsualScoreService;
+import com.qmth.distributed.print.business.service.PrintCommonService;
 import com.qmth.teachcloud.common.annotation.OperationLogDetail;
 import com.qmth.teachcloud.common.contant.SystemConstant;
 import com.qmth.teachcloud.common.enums.log.CustomizedOperationTypeEnum;
@@ -30,7 +30,7 @@ import java.io.IOException;
 public class TRBasicInfoController {
 
     @Resource
-    TCUsualScoreService tcUsualScoreService;
+    PrintCommonService printCommonService;
 
     @ApiOperation(value = "报告管理列表")
     @RequestMapping(value = "/report/list", method = RequestMethod.POST)
@@ -40,7 +40,7 @@ public class TRBasicInfoController {
                              @ApiParam(value = "课程编码") @RequestParam(required = false) String courseCode,
                              @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                              @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
-        return ResultUtil.ok(tcUsualScoreService.scoreList(new Page<>(pageNumber, pageSize), examId, courseCode));
+        return ResultUtil.ok(printCommonService.scoreList(new Page<>(pageNumber, pageSize), examId, courseCode));
     }
 
     @ApiOperation(value = "查看报告")