package com.api.games.controller; import com.api.base.model.User; import com.api.base.service.UserService; import com.api.common.UtilFun; import com.api.common.execl.ExcelUtil; import com.api.config.ConstUser; import com.api.core.annotation.PowerEnable; import com.api.core.config.AuthUser; import com.api.core.controller.Ctrl; import com.api.core.response.Result; import com.api.core.response.ResultGenerator; import com.api.games.model.GameConfig; import com.api.games.model.UserConfig; import com.api.games.service.GameConfigService; import com.api.games.service.ScaleLogService; import com.api.games.service.UserConfigService; import io.swagger.annotations.*; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; /** * Created by wanghuiwen on 2020/02/23. */ @PowerEnable(name = "用户配置", url = "/user/config") @Api(value = "用户配置", tags = {"用户配置"}) @RestController @RequestMapping("/user/config") public class UserConfigController extends Ctrl { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource ScaleLogService scaleLogService; @Resource private UserConfigService userConfigService; @Resource private UserService userService; @Resource private GameConfigService gameConfigService; @ApiOperation(value = "用户配置删除", tags = {"用户配置"}, notes = "用户配置删除") @ApiImplicitParams({ @ApiImplicitParam(name = "id", required = true, value = "用户配置id", dataType = "Long", paramType = "query") }) @PostMapping(value = "/delete", name = "用户配置删除") public Result delete(@RequestParam Long id) { return userConfigService.delete(id); } @ApiOperation(value = "用户配置修改", tags = {"用户配置"}, notes = "用户配置修改,对象主键必填") @PostMapping(value = "/update", name = "用户配置修改") public Result update(User user, UserConfig config, Long configId, String configs) { return userConfigService.update(user, config, configId, configs); } @ApiOperation(value = "用户配置详细信息", tags = {"用户配置"}, notes = "用户配置详细信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", required = true, value = "用户配置id", dataType = "Long", paramType = "query") }) @PostMapping(value = "/detail", name = "用户配置详细信息") public Result detail(@RequestParam Integer id) { UserConfig userConfig = userConfigService.findById(id); return ResultGenerator.genSuccessResult(userConfig); } @ApiOperation(value = "用户配置信息", tags = {"用户配置"}, notes = "用户配置信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", required = true, value = "用户id", dataType = "Long", paramType = "query") }) @PostMapping(value = "/get", name = "用户配置信息") public Result detail(@RequestParam Long id) { UserConfig userConfig = userConfigService.findBy("userId", id); return ResultGenerator.genSuccessResult(userConfig); } @ApiOperation(value = "用户配置列表信息", tags = {"用户配置"}, notes = "用户配置列表信息") @ApiImplicitParams({ @ApiImplicitParam(name = "page", value = "页码", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "size", value = "每页显示的条数", dataType = "String", paramType = "query", defaultValue = "10") }) @PostMapping(value = "/list", name = "用户配置列表信息") public Result list(@RequestParam(required = false) String search, @RequestParam(required = false) String order, @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size) { return userConfigService.list(search, order, page, size); } @PostMapping(value = "/save", name = "添加用户") public Result list(User user, UserConfig config, String configs) { return userConfigService.add(user, config, configs); } @PostMapping(value = "/bind", name = "綁定設備") public Result list(Authentication authentication) { AuthUser user = getAuthUser(authentication); return userConfigService.bind(user); } @PostMapping(value = "/delay", name = "延迟") public Result delay(@ApiParam(hidden = true) Authentication authentication, Date date, String type, @RequestParam(required = false) Integer num, @RequestParam(required = false) Long msgId, @RequestParam(required = false) String start, @RequestParam(required = false) String end) { AuthUser user = getAuthUser(authentication); return userConfigService.delay(user, date, msgId, num, type, start, end); } @PostMapping(value = "/version", name = "获取已经执行的游戏版本") public Result version(@ApiParam(hidden = true) Authentication authentication, @RequestParam(required = false) Long msgId) { AuthUser user = getAuthUser(authentication); return userConfigService.getVersion(user, msgId); } @PostMapping(value = "/user/start", name = "测试标志用户状态") public Result start() { userConfigService.expired(); return ResultGenerator.genSuccessResult(); } @PostMapping(value = "/user/scale", name = "测试标志用户状态") public Result scale() { scaleLogService.notPerformed(); return ResultGenerator.genSuccessResult(); } @PostMapping(value = "/logout", name = "推出登录") public Result logout(Authentication authentication) { AuthUser user = getAuthUser(authentication); if (user.getType() == ConstUser.USER_ADMIN) { return ResultGenerator.genSuccessResult(); } UserConfig config = userConfigService.findBy("userId", user.getId()); if (config.getLoginOut() == 1) { return ResultGenerator.genFailResult(); } return ResultGenerator.genSuccessResult(); } @PostMapping("/download") public void downloadFile(@RequestParam(defaultValue = "{}") String search, @RequestParam(defaultValue = "{}") String order, HttpServletResponse response) { List> res = userConfigService.download(search, order); for(Map item : res){ String scaleStart = item.get("scaleStart") == null ? null : (String) item.get("scaleStart"); String scaleEnd = item.get("scaleEnd") == null ? null : (String) item.get("scaleEnd"); if (scaleStart != null && scaleEnd != null){ Calendar current = Calendar.getInstance(); Calendar calendarStart = Calendar.getInstance(); calendarStart.setTime(UtilFun.StringToDate(scaleStart, UtilFun.YYYYMMDDHHMMSS)); Calendar calendarEnd = Calendar.getInstance(); calendarEnd.setTime(UtilFun.StringToDate(scaleEnd, UtilFun.YYYYMMDDHHMMSS)); if (current.before(calendarStart)){ item.put("status", 0); } else if (current.after(calendarEnd)){ item.put("status", 2); } else if(current.after(calendarStart) && current.before(calendarEnd)){ item.put("status", 1); } } } int column = 15; int rowCount = res.size(); String fileTitle = UtilFun.DateToString(new Date(), UtilFun.YMD) + ".xlsx"; String[] title = {"ID", "用戶名", "狀態", "創建日期", "開始日期", "結束日期", "量表提示時間", "數字顯示的時長", "數字交換間隔", "正確數字出現次數", "隨機數字出現次數", "練習結束進入測試的時長", "每天遊戲次數", "遊戲版本", "遊戲時間段", "登出"}; File file = new File(fileTitle); BufferedInputStream bis = null; OutputStream os = null; // 设置强制下载不打开 response.setContentType("application/octet-stream"); // 设置文件名 response.addHeader("Content-Disposition", "attachment;fileName=" + fileTitle); response.addHeader("filename", fileTitle); response.setHeader("Access-Control-Expose-Headers", "filename,Content-Disposition"); try { OutputStream out = new FileOutputStream(file); XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作簿对象 XSSFSheet sheet = workbook.createSheet(UtilFun.DateToString(new Date(), UtilFun.YMD)); // 创建工作表 XSSFRow titleRow = sheet.createRow(0); // 产生表格标题行 XSSFCell cellTitle = titleRow.createCell(0); //创建表格标题列 XSSFCellStyle columnTopStyle = ExcelUtil.getColumnTopStyle(workbook);// 获取列头样式对象 XSSFCellStyle style = ExcelUtil.getStyle(workbook); // 获取单元格样式对象 // 合并表格标题行,合并列数为列名的长度,第一个0为起始行号,第二个1为终止行号,第三个0为起始列好,第四个参数为终止列号 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, column)); cellTitle.setCellStyle(columnTopStyle); //设置标题行样式 cellTitle.setCellValue(fileTitle); //设置标题行值 XSSFRow rowRowName = sheet.createRow(1); // 在索引2的位置创建行(最顶端的行开始的第二行) // 将列头设置到sheet的单元格中 for (int n = 0; n < title.length; n++) { XSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格 cellRowName.setCellType(CellType.STRING); // 设置列头单元格的数据类型 XSSFRichTextString text = new XSSFRichTextString(title[n]); cellRowName.setCellValue(text); // 设置列头单元格的值 cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式 } // 将查询出的数据设置到sheet对应的单元格中 for (int i = 0; i < rowCount; i++) { XSSFRow row = sheet.createRow(i + 2); // 创建所需的行数 for (int j = 0; j <= column; j++) { XSSFCell cell = null; // 设置单元格的数据类型 if (j == 0) { cell = row.createCell(j, CellType.NUMERIC); cell.setCellValue(i + 1); } else { String text = ""; switch (j) { case 1: { text = res.get(i).get("nickname").toString(); break; } case 2: { String status = res.get(i).get("status").toString(); if (status.equals("0")) text = "waiting"; else if(status.equals("1")) text = "processing"; else text = "end"; break; } case 3: { text = res.get(i).get("createTime").toString(); break; } case 4: { text = res.get(i).get("scaleStart").toString(); break; } case 5: { text = res.get(i).get("scaleEnd").toString(); break; } case 6: { text = res.get(i).get("scaleTime").toString(); break; } case 7: { text = res.get(i).get("showTime").toString(); break; } case 8: { text = res.get(i).get("hideTime").toString(); break; } case 9: { text = res.get(i).get("correct").toString(); break; } case 10: { text = res.get(i).get("supporting").toString(); break; } case 11: { text = res.get(i).get("practice").toString(); break; } case 12: { text = res.get(i).get("gameCount").toString(); break; } case 13:{ text = res.get(i).get("version").toString(); break; } case 14:{ List gameConfigList = (List)gameConfigService.listUid((Long) res.get(i).get("userId")).getData(); text = ""; for (GameConfig item: gameConfigList) text += item.getStartTime() + "-" + item.getEndTime() + " "; break; } case 15: { text = res.get(i).get("loginOut").toString().equals("0") ? "yes" : "no"; break; } default: { text = ""; break; } } cell = row.createCell(j, CellType.STRING); cell.setCellValue(text); // 设置单元格的值 } cell.setCellStyle(style); // 设置单元格样式 } } // 让列宽随着导出的列长自动适应 for (int colNum = 0; colNum <= column; colNum++) { int columnWidth = sheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { XSSFRow currentRow; // 当前行未被使用过 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { XSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellType() == CellType.STRING) { int length = currentCell.getStringCellValue() .getBytes().length; if (columnWidth < length) { columnWidth = length; } } } } if (colNum == 0) { sheet.setColumnWidth(colNum, (columnWidth - 2) * 256); } else { sheet.setColumnWidth(colNum, (columnWidth + 4) * 256); } } workbook.write(out); response.addHeader("Content-Length", String.valueOf(file.length())); byte[] buff = new byte[1024]; os = response.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(file)); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (os != null) os.close(); } catch (IOException e) { logger.error("close exception", e); } } } }