package com.rf.psychological.scale.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.dao.dto.InstitutionRecordingUsersDTO;
import com.rf.psychological.scale.dao.dto.SubjectEntityDto2;
import com.rf.psychological.scale.dao.model.ScaleEntity;
import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.dao.model.UserRecordEntity;
import com.rf.psychological.scale.service.*;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.user.dao.model.UserFileEntity;
import com.rf.psychological.user.service.UserFileService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.*;
import com.rf.psychological.wxpay.model.PromotionInfo;
import com.rf.psychological.wxpay.service.PromotionInfoService;
import com.rf.psychological.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.rf.psychological.utils.FileUtil.html2pdf;

@Slf4j
@RestController
@RequestMapping("/result/download")
@Api(tags = "数据下载接口")
public class DataDownloadController {

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private UserRecordService userRecordService;

    @Autowired
    private UserService userService;

    @Autowired
    private ScaleService scaleService;

    @Autowired
    private UserFileService userFileService;

    @Autowired(required = false)
    private WxPayService wxPayService;

    @Autowired
    private PromotionInfoService promotionInfoService;

    /*@Value("${spring.profiles.active}")
    private String profile;*/


    //@SafetyProcess
    @ApiOperation(value = "测试结果下载")
    @GetMapping("/testResult")
    public String downloadTestResult(String id, HttpServletResponse response) throws Exception {
        if (id != null) {
            UserRecordEntity userRecordEntity = this.userRecordService.getUserRecordById(id);
            if (userRecordEntity == null) {
                return "该记录异常，下载失败";
            }
            File file = null;
            if (new File(userRecordEntity.getFileName()).exists()) {
                file = new File(userRecordEntity.getFileName());
                response.reset();
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {

                String fileName = userRecordEntity.getFileName();
                String testDate = userRecordEntity.getTestDate();
                String name = userRecordEntity.getName();
                testDate = testDate.substring(0, 10);
                testDate = testDate.replace("年", "-");
                testDate = testDate.replace("月", "-");
                //设置文件路径
                file = new File("./心理检测/检测结果/" + testDate + "/" + name + "/" + fileName);
                if (file.exists()) {
                    response.reset();
                    response.setContentType("application/octet-stream");
                    response.setCharacterEncoding("utf-8");
                    response.setContentLength((int) file.length());
                    response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    try {
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis);
                        OutputStream os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                        return "下载成功";
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return "下载失败";
    }

    @ApiOperation(value = "下载PDF测试报告")
    @GetMapping("/testResultPdf")
    public String downloadTestResultPdf(String id, HttpServletResponse response) {
        if (id != null) {
            UserRecordEntity userRecordEntity = this.userRecordService.getUserRecordById(id);
            if (userRecordEntity == null) {
                return "该记录异常，下载失败";
            }
            String PDFPath = generatePDFRecord(userRecordEntity,"pdf");
            if (PDFPath.equals("false")) {
                return "报告版本较早，暂无法下载";
            }
            List<String> htmlFilePathList = new ArrayList<>();
            htmlFilePathList.add(PDFPath);

            //生成PDF测试记录
            try {
                html2pdf(htmlFilePathList);
            } catch (Exception e) {
                log.error("生成测试文件失败" + e.getMessage());
                e.printStackTrace();
                return "下载失败";
            }
            String[] split = userRecordEntity.getFileName().split("/");
            String fileName = split[split.length - 1];
            String PDFName = fileName.replace(".xlsx", ".pdf");
            //下载PDF文件
            File z = new File("./h2p/export_pdf/PDFReport/" + PDFName);
            if (!z.exists()) return "下载失败";
            try {
                FileUtil.downloadFile(response, z, PDFName, true);
                return "下载成功";
            } catch (UnsupportedEncodingException e) {
                log.error("下载文件失败:" + e.getMessage());
                e.printStackTrace();
                return "下载失败";
            }
        }
        return "下载失败";
    }

    @Profile({"public"})
    @ApiOperation(value = "下载量表测试报告图片")
    @GetMapping("/testResultPng")
    public String downloadTestResultPng(String id, HttpServletResponse response) {
        if (id != null) {
            UserRecordEntity userRecordEntity = this.userRecordService.getUserRecordById(id);
            if (userRecordEntity == null) {
                return "该记录异常，下载失败";
            }
            String link = null;
            //if ("public".equals(profile)) {
                link = this.wxPayService.generateWxCode("scaleTestResults/testResults/index",userRecordEntity.getId(),"release");
            //}
            userRecordEntity.setImg(link);
            String PNGPath = generatePDFRecord(userRecordEntity,"trpng");
            if (PNGPath.equals("false")) {
                return "报告版本较早，暂无法下载";
            }
            List<String> htmlFilePathList = new ArrayList<>();
            htmlFilePathList.add(PNGPath);

            //生成图片测试记录
            try {
                Html2PNG.html2png(htmlFilePathList);
            } catch (Exception e) {
                log.error("生成测试文件失败" + e.getMessage());
                e.printStackTrace();
                return "下载失败";
            }
            String[] split = userRecordEntity.getFileName().split("/");
            String fileName = split[split.length - 1];
            String PNGName = fileName.replace(".xlsx", ".png");
            //下载图片文件
            File z = new File("./h2p/export_pdf/PDFReport/" + PNGName);
            if (!z.exists()) return "下载失败";
            try {
                FileUtil.downloadFile(response, z, PNGName, true);
                return "下载成功";
            } catch (UnsupportedEncodingException e) {
                log.error("下载文件失败:" + e.getMessage());
                e.printStackTrace();
                return "下载失败";
            }
        }
        return "下载失败";
    }

    @ApiOperation(value = "下载量表详情图片")
    @GetMapping("/scaleDetailPng")
    public String downloadScaleDetailPng(String flag, HttpServletResponse response) {
        SubjectEntity subjectEntity = this.subjectService.getSubjectEntityByFlag(flag);
        if (subjectEntity != null) {
            SubjectEntityDto2 subjectEntityDto2 = new SubjectEntityDto2(subjectEntity);
            PromotionInfo infoBySubjectId = this.promotionInfoService.findInfoBySubjectId(subjectEntity.getId());
            subjectEntityDto2.setPrice(infoBySubjectId == null ? 0.0:infoBySubjectId.getPrice());
            List<ScaleEntity> scaleEntityList = this.scaleService.getScaleByFlag(subjectEntity.getFlag());
            subjectEntityDto2.setTitleNum(scaleEntityList.size());
            int estimatedTime = scaleEntityList.size() / Constant.TEST_PLAN_STATUS_RUNNING + (scaleEntityList.size() % Constant.TEST_PLAN_STATUS_RUNNING != 0 ? 1 : 0);
            subjectEntityDto2.setEstimatedTime(estimatedTime);
            JSONObject userRecordJson = new JSONObject(true);
            userRecordJson.put("subjectEntityDto2",subjectEntityDto2);
            userRecordJson.put("name",subjectEntityDto2.getName());
            userRecordJson.put("link",this.wxPayService.generateWxCode("scalePage/beginTest/index",subjectEntityDto2.getFlag(),"release"));
            String PNGPath = generateHTMLRecord(userRecordJson,"sdpng");
            List<String> htmlFilePathList = new ArrayList<>();
            htmlFilePathList.add(PNGPath);

            //生成图片测试记录
            try {
                Html2PNG.html2png(htmlFilePathList);
            } catch (Exception e) {
                log.error("生成测试文件失败" + e.getMessage());
                e.printStackTrace();
                return "下载失败";
            }
            String[] split = PNGPath.split("/");
            String fileName = split[split.length - 1];
            String PNGName = fileName.replace(".html", ".png");
            //下载图片文件
            File z = new File("./h2p/export_pdf/PDFReport/" + PNGName);
            if (!z.exists()) return "下载失败";
            try {
                FileUtil.downloadFile(response, z, PNGName, true);
                return "下载成功";
            } catch (UnsupportedEncodingException e) {
                log.error("下载文件失败:" + e.getMessage());
                e.printStackTrace();
                return "下载失败";
            }
        }
        return "下载失败";
    }

    @ApiOperation(value = "用户PDF报告全部下载")
    @GetMapping("/allUserPDFReds")
    public String downloadAllPDFTestResult(String institutionNo, String name, String searchKey, String beginTime, String endTime, String groupId, HttpServletResponse response) {
        List<InstitutionRecordingUsersDTO> institutionUserRecordingList = this.userRecordService.getInstitution(institutionNo, name, searchKey, beginTime, endTime, groupId)
                .stream().sorted(Comparator.comparing(InstitutionRecordingUsersDTO::getTestDate)).collect(Collectors.toList());
        if (institutionUserRecordingList.isEmpty()) {
            return "无测试记录";
        }
        List<String> htmlFilePathList = new ArrayList<>();
        String PDFPath;
        for (int i = 0; i < institutionUserRecordingList.size(); i++) {
            UserRecordEntity userRecordEntity = new UserRecordEntity();
            userRecordEntity.setFlag(institutionUserRecordingList.get(i).getFlag());
            userRecordEntity.setPhone(institutionUserRecordingList.get(i).getPhone());
            userRecordEntity.setInstitutionNo(institutionUserRecordingList.get(i).getInstitutionNo());
            userRecordEntity.setFileName(institutionUserRecordingList.get(i).getFileName());
            userRecordEntity.setName(institutionUserRecordingList.get(i).getName());
            userRecordEntity.setTestResult(institutionUserRecordingList.get(i).getTestResult());
            userRecordEntity.setType(institutionUserRecordingList.get(i).getType());
            userRecordEntity.setTestResults(institutionUserRecordingList.get(i).getTestResults());
            PDFPath = generatePDFRecord(userRecordEntity,"pdf");
            if (!PDFPath.equals("false")) {
                htmlFilePathList.add(PDFPath);
            }
        }
        if (htmlFilePathList.size() < 1) {
            return "下载失败";
        }
        String flag = h2pdownload(htmlFilePathList, response);
        return flag;
    }

    @ApiOperation(value = "用户PDF报告批量下载")
    @GetMapping("/userPDFReds")
    public String downloadPDFTestResult(@RequestParam(value = "ids", required = false) List<String> recordingIds, HttpServletResponse response) {
        List<String> htmlFilePathList = new ArrayList<>();
        String PDFPath;
        for (int i = 0; i < recordingIds.size(); i++) {
            InstitutionRecordingUsersDTO recordingUsersDTO = this.userRecordService.getRecordingUsersDTOById(recordingIds.get(i));
            if (recordingUsersDTO != null) {
                UserRecordEntity userRecordEntity = new UserRecordEntity();
                userRecordEntity.setFlag(recordingUsersDTO.getFlag());
                userRecordEntity.setPhone(recordingUsersDTO.getPhone());
                userRecordEntity.setInstitutionNo(recordingUsersDTO.getInstitutionNo());
                userRecordEntity.setFileName(recordingUsersDTO.getFileName());
                userRecordEntity.setName(recordingUsersDTO.getName());
                userRecordEntity.setTestResult(recordingUsersDTO.getTestResult());
                userRecordEntity.setType(recordingUsersDTO.getType());
                userRecordEntity.setTestResults(recordingUsersDTO.getTestResults());
                PDFPath = generatePDFRecord(userRecordEntity,"pdf");
                if (!PDFPath.equals("false")) {
                    htmlFilePathList.add(PDFPath);
                }
            }
        }
        if (htmlFilePathList.size() < 1) {
            return "下载失败";
        }
        String flag = h2pdownload(htmlFilePathList, response);
        return flag;
    }

    /**
     * h2p并下载压缩包
     * @param htmlFilePathList
     * @return html 测试结果文件路径列表
     */
    private String h2pdownload(List<String> htmlFilePathList, HttpServletResponse response) {
        //生成PDF测试记录
        try {
            html2pdf(htmlFilePathList);
        } catch (Exception e) {
            log.error("生成测试文件失败"+e.getMessage());
            e.printStackTrace();
            return "下载失败";
        }
        //打包PDF
        String ZIPNAme = "PDFReport.zip";
        ZipUtils.createZip("./h2p/export_pdf/PDFReport","./h2p/export_pdf/"+ZIPNAme,true);
        //下载PDF压缩包
        File z = new File("./h2p/export_pdf/"+ZIPNAme);
        if(!z.exists())return "下载失败";
        try {
            FileUtil.downloadFile(response,z,ZIPNAme,true);
        } catch (UnsupportedEncodingException  e) {
            log.error("下载文件失败:"+e.getMessage());
            e.printStackTrace();
            return "下载失败";
        }
        return "下载成功";
    }

    /**
     * 处理PDF报告数据格式
     * @param userRecordEntity
     * @return html 测试结果文件路径列表
     */
    private String generatePDFRecord(UserRecordEntity userRecordEntity,String type) {
        UserEntity userEntity = this.userService.findPhoneAndInstitutionNoAndRoleType(userRecordEntity.getPhone(),userRecordEntity.getInstitutionNo(),Constant.DEFAULT_VALUE_ONE);
        UserFileEntity userFileEntity = this.userFileService.findByUserId(userEntity.getId());
        if (userFileEntity != null){
            userEntity.setAvatarUrl(userFileEntity.getPath());
        }
        String[] split = userRecordEntity.getFileName().split("/");
        String fileName = split[split.length-1];
        fileName = fileName.replace(".xlsx","");
        JSONObject userRecordJson = new JSONObject(true);
        userRecordJson.put("userEntity",userEntity);
        userRecordJson.put("userRecordEntity",userRecordEntity);

        //测试记录文件名
        userRecordJson.put("fileName",fileName);
        //量表或认知任务名称
        userRecordJson.put("name",userRecordEntity.getName());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginTime = df.format(new Date());
        userRecordJson.put("reportTime",beginTime);
        if (type.equals("trpng")){
            userRecordJson.put("userInfo",userEntity);
            userRecordJson.put("link",userRecordEntity.getImg());
            userRecordEntity.setImg("");
        }
        String testResult = userRecordEntity.getTestResult();
        //量表
        if (userRecordEntity.getType().equals(Constant.DEFAULT_VALUE_ZERO)){
            JSONArray resultList = JSONArray.parseArray(testResult);
            JSONObject resultJson = resultList.getJSONObject(0);
            SubjectEntity subjectEntity = this.subjectService.getSubjectEntityByFlag(userRecordEntity.getFlag());
            userRecordJson.put("subject",subjectEntity);
            if (testResult.contains("newTableContext") && resultJson.getInteger("version") == 2){
                JSONObject newTableContext = resultJson.getJSONObject("newTableContext");
                JSONArray result = newTableContext.getJSONArray("result");
                userRecordJson.put("result",result);
            }else {
                if (testResult.contains("tableContext")){
                    JSONArray tableContext = resultJson.getJSONArray("tableContext");
                    userRecordJson.put("tableContext",tableContext);
                }else {
                    return "false";
                }
            }
            //认知任务
        }else {
            String testResults = userRecordEntity.getTestResults();
            String[] splits = testResults.split(";");
            if (testResults.contains("version")){
                JSONObject testResultJson = new JSONObject(true);
                    int a = 0;
                for (int x = 0; x < splits.length; x++) {
                    if (a < 1 && (splits[x].contains("totalScoreDesc") || splits[x].contains("totalScore"))){
                        String b = splits[x];
                        JSONArray totalScores = JSONArray.parseArray(b.replace("totalScore:", ""));
                        JSONObject totalScore = totalScores.getJSONObject(0);
                        testResultJson.put("总分",totalScore.getString("totalScore"));
                        testResultJson.put("总分结论",totalScore.getString("totalScoreDesc"));
                        a ++;
                    }
                    if (splits[x].contains("Describe")){
                        String b = splits[x];
                        JSONArray dimensions = JSONArray.parseArray(b.replace("dimensions:", ""));
                        for (int y = 0; y < dimensions.size(); y++) {
                            JSONObject dimension = dimensions.getJSONObject(y);
                            testResultJson.put(dimension.getString("name"),dimension.getString("score"));
                            testResultJson.put(dimension.getString("name") + "结论",dimension.getString("Describe"));
                        }
                        a ++;
                    }
                    if (a < 1 && splits[x].contains("columnValue")){
                        JSONArray tableModule = JSONObject.parseObject(userRecordEntity.getTestResult()).getJSONArray("tableModule");
                        JSONArray columnValues = tableModule.getJSONObject(0).getJSONArray("columnValue");
                        String[] colName = columnValues.getString(0).split(";");
                        String[] colValue = columnValues.getString(1).split(";");
                        for (int y = 0; y < colName.length; y++){
                            testResultJson.put(colName[y],colValue[y]);
                        }
                    }
                }
                Set<String> keys = testResultJson.keySet();
                JSONArray tableContext = new JSONArray();
                // 获取第一层每个key对应的值 的类型
                for (String key : keys) {
                    //列值
                    List colValue = new ArrayList();
                    colValue.add(testResultJson.get(key));
                    JSONObject row = new JSONObject();
                    row.put("name", key);
                    row.put("value", colValue);
                    tableContext.add(row);
                }
                userRecordJson.put("tableContext",tableContext);
            }else {
                if (testResult.contains("tableContext")){
                    JSONArray tableContext = JSONArray.parseArray(testResult).getJSONObject(0).getJSONArray("tableContext");
                    userRecordJson.put("tableContext",tableContext);
                }else {
                    return "false";
                }
            }



        }

        System.out.println("11:"+userRecordJson);
        return generateHTMLRecord(userRecordJson,type);

    }


    /**
     * 创建HTML测试结果
     * @param userRecordJson
     * @return html 测试结果文件路径列表
     */
    private String generateHTMLRecord(JSONObject userRecordJson,String type) {
        BufferedReader in = null;
        PrintWriter out = null;
        File temp = new File("./h2p/export_pdf/PDFReport");
        String link = null;
        //模板html
        String resourceFilePath;
        //目标html
        String destFilePath;
        if (type.equals("pdf")){
            resourceFilePath = "./h2p/export_pdf/export.html";
            destFilePath = "./h2p/export_pdf/"+userRecordJson.getString("fileName")+".html";
        }else if (type.equals("trpng")){
            link = userRecordJson.getString("link");
            userRecordJson.remove("link");
            resourceFilePath = "./h2p/export_pdf/miniprogramReport.html";
            destFilePath = "./h2p/export_pdf/"+userRecordJson.getString("fileName")+".html";
        }else {
            link = userRecordJson.getString("link");
            userRecordJson.remove("link");
            resourceFilePath = "./h2p/export_pdf/miniprogramScaleDetail.html";
            destFilePath = "./h2p/export_pdf/"+userRecordJson.getString("name")+"-"+new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format(new Date())+".html";
        }
        if (!temp.exists()) {
            temp.mkdirs();
        }
        try {
            in = new BufferedReader(new FileReader(resourceFilePath));
            String line;
            int count=1;
            out = new PrintWriter(new BufferedWriter(new FileWriter(destFilePath)));
            while((line=in.readLine())!=null){
                if (type.equals("pdf")){
                    if(count==311){
                        out.println(line.replace("ReplaceData", JSON.toJSONString(userRecordJson)));  //替换
                    }else{
                        out.println(line);
                    }
                }else if (type.equals("trpng")){
                    if(count==592){
                        out.println(line.replace("ReplaceData", JSON.toJSONString(userRecordJson)));  //替换
                    }else if (count==593){
                        out.println(line.replace("base64img", JSON.toJSONString(link)));  //替换
                    }else {
                        out.println(line);
                    }
                }else {
                    if(count==352){
                        out.println(line.replace("scaleDetail", JSON.toJSONString(userRecordJson.get("subjectEntityDto2"))));  //替换
                    }else if (count==353){
                        out.println(line.replace("base64img", JSON.toJSONString(link)));  //替换
                    }else{
                        out.println(line);
                    }
                }
                count++;
            }
            return destFilePath;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                assert in != null;
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            assert out != null;
            out.close();
        }
    }

    @ApiOperation(value = "认知任务图片下载")
    @GetMapping("/CDTImg")
    public String downloadCDTImg(String id, HttpServletResponse response) throws Exception {
        if (id != null) {
            UserRecordEntity userRecordEntity = this.userRecordService.getUserRecordById(id);
            if (userRecordEntity == null) {
                return "该记录异常，下载失败";
            }
            String fileName = userRecordEntity.getImg();
            String name = userRecordEntity.getImg();
            String[] names = name.split("/");
            name = names[(names.length-1)];

            File file = null;
            file = new File(fileName);

            if (file.exists()) {
                response.reset();
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }

    @ApiOperation(value = "用户测试结果全部下载")
    @GetMapping("/allUserReds")
    public String downloadAllTestResult(String institutionNo, String name, String searchKey, String beginTime, String endTime, String groupId, HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Workbook wb = new XSSFWorkbook();
        //循环往excel中放数据时先放的在下面，所以这里升序，往excel放数据时候就是降序
        List<InstitutionRecordingUsersDTO> institutionUserRecordingList = this.userRecordService.getInstitution(institutionNo, name, searchKey, beginTime, endTime, groupId)
                .stream().sorted(Comparator.comparing(InstitutionRecordingUsersDTO::getTestDate)).collect(Collectors.toList());
        if (institutionUserRecordingList.isEmpty()) {
            return "无测试记录";
        }
        List<InstitutionRecordingUsersDTO> newInstitutionUserRecordingList = new ArrayList<>();
        List<InstitutionRecordingUsersDTO> oldInstitutionUserRecordingList = new ArrayList<>();
        String[] newTitle = new String[0];
        String[] oldTitle = new String[0];
        for (int i = 0; i < institutionUserRecordingList.size(); i++) {
            String testResults = institutionUserRecordingList.get(i).getTestResults();
            String[] splits = testResults.split(";");
            if (testResults.contains("version")){
                newInstitutionUserRecordingList.add(institutionUserRecordingList.get(i));
                String testResult = new String();
                for (int x = 0; x < splits.length; x++) {
                    if (Arrays.toString(splits).contains("columnValue")){
                        if (splits[x].contains("columnValue")){
                            JSONArray tableModule = JSONObject.parseObject(institutionUserRecordingList.get(i).getTestResult()).getJSONArray("tableModule");
                            JSONArray columnValues = tableModule.getJSONObject(0).getJSONArray("columnValue");
                            String[] colName = columnValues.getString(0).split(";");
                            String[] colValue = columnValues.getString(1).split(";");
                            for (int y = 0; y < colName.length; y++){
                                testResult += colName[y] + ":" + colValue[y] + ";";
                            }
                        }
                    }else {
                        if (splits[x].contains("totalScoreDesc")){
                            String b = splits[x];
                            JSONArray totalScores = JSONArray.parseArray(b.replace("totalScore:", ""));
                            JSONObject totalScore = totalScores.getJSONObject(0);
                            testResult += "总分:" + totalScore.getString("totalScore")+";总分结论:"+totalScore.getString("totalScoreDesc")+";";
                        }
                        if (splits[x].contains("Describe")){
                            String b = splits[x];
                            JSONArray dimensions = JSONArray.parseArray(b.replace("dimensions:", ""));
                            for (int y = 0; y < dimensions.size(); y++) {
                                JSONObject dimension = dimensions.getJSONObject(y);
                                testResult += dimension.getString("name") + ":" + dimension.getString("score") + ";"
                                        + dimension.getString("name") + "结论:" + dimension.getString("Describe") + ";";
                            }
                        }
                    }
                }
                splits = testResult.split(";");
                //标题行抽出字段
                newTitle = new String[splits.length + 7];
                newTitle[0] = "姓名";
                newTitle[1] = "性别";
                newTitle[2] = "职业";
                newTitle[3] = "出生日期";
                newTitle[4] = "登录名";
                newTitle[5] = "测试时间";
                newTitle[6] = "测试名称";
                for (int x = 0; x < splits.length; x++) {
                    String[] a = splits[x].split(":");
                    newTitle[x + 7] = a[0];

                }
            }else {
                oldInstitutionUserRecordingList.add(institutionUserRecordingList.get(i));

                //标题行抽出字段
                oldTitle = new String[splits.length + 7];
                oldTitle[0] = "姓名";
                oldTitle[1] = "性别";
                oldTitle[2] = "职业";
                oldTitle[3] = "出生日期";
                oldTitle[4] = "登录名";
                oldTitle[5] = "测试时间";
                oldTitle[6] = "测试名称";
                for (int y = 0; y < splits.length; y++) {
                    String[] a = splits[y].split(":");
                    oldTitle[y + 7] = a[0];

                }
            }
        }

        //设置sheet名称，并创建新的sheet对象
        String newSheetName = "用户测试结果新结构导出";
        String oldSheetName = "用户测试结果老结构导出";
        if (newInstitutionUserRecordingList.size() > 0){
            Sheet newDownSheet = wb.createSheet(newSheetName);
            wb = insertData(newDownSheet,wb,newTitle,newInstitutionUserRecordingList,name);
        }
        if (oldInstitutionUserRecordingList.size() > 0){
            Sheet oldDownSheet = wb.createSheet(oldSheetName);
            wb = insertData(oldDownSheet,wb,oldTitle,oldInstitutionUserRecordingList,name);
        }


        String foldDir = null;
        //获取配置文件中保存对应excel文件的路径，本地也可以直接写成F：excel/stuInfoExcel路径
        foldDir = "./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + "用户测试结果导出";
        //创建上传文件目录
        File fileDir = new File(foldDir);

        //如果文件夹不存在创建对应的文件夹
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String testTime = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format(new Date());
        //设置文件名
        String fileName = institutionNo + "-" + name + "-" + testTime + ".xlsx";

        OutputStream fileOut = new FileOutputStream(foldDir + "/" + fileName);
        wb.write(fileOut);
        fileOut.close();

        File file = new File(foldDir + "/" + fileName);
        if (file.exists()) {
            if (name.equals(Constant.SHEET_NAME_CDT) || name.equals(Constant.SHEET_NAME_DSST)) {
                File[] srcFiles = new File[institutionUserRecordingList.size() + 1];
                int size = institutionUserRecordingList.size();
                for (int i = 0; i < size; i++) {
                    if (!StringUtil.isEmpty(institutionUserRecordingList.get(i).getImg())) {
                        srcFiles[i] = new File(institutionUserRecordingList.get(i).getImg());
                    }
                }

                srcFiles[institutionUserRecordingList.size()] = new File(foldDir + "/" + fileName);
                File zipFile = new File(foldDir + "/" + name + ".zip");
                // 调用压缩方法
                zipFiles(srcFiles, zipFile);
                response.reset();
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) zipFile.length());
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name + ".zip", "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(zipFile);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                response.reset();
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        return "下载失败";
    }

    @ApiOperation(value = "用户测试结果批量导出下载")
    @GetMapping("/userReds")
    public String downloadTestResult(@RequestParam(value = "ids", required = false) List<String> recordingIds, String institutionNo, String name, HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Workbook wb = new XSSFWorkbook();
        List<InstitutionRecordingUsersDTO> institutionUserRecordingList = new ArrayList<>();
        for (int i = 0; i < recordingIds.size(); i++) {
            InstitutionRecordingUsersDTO recordingUsersDTO = this.userRecordService.getRecordingUsersDTOById(recordingIds.get(recordingIds.size()-i-1));
            if (recordingUsersDTO != null){
                institutionUserRecordingList.add(recordingUsersDTO);
            }
        }
        institutionUserRecordingList.stream().sorted(Comparator.comparing(InstitutionRecordingUsersDTO::getTestDate)).collect(Collectors.toList());


        List<InstitutionRecordingUsersDTO> newInstitutionUserRecordingList = new ArrayList<>();
        List<InstitutionRecordingUsersDTO> oldInstitutionUserRecordingList = new ArrayList<>();
        String[] newTitle = new String[0];
        String[] oldTitle = new String[0];
        for (int i = 0; i < institutionUserRecordingList.size(); i++) {
            String testResults = institutionUserRecordingList.get(i).getTestResults();
            String[] splits = testResults.split(";");
            if (testResults.contains("version")){
                newInstitutionUserRecordingList.add(institutionUserRecordingList.get(i));
                //institutionUserRecordingList.remove(i);
                //i--;
                String testResult = new String();
                for (int x = 0; x < splits.length; x++) {
                    if (Arrays.toString(splits).contains("columnValue")){
                        if (splits[x].contains("columnValue")){
                            JSONArray tableModule = JSONObject.parseObject(institutionUserRecordingList.get(i).getTestResult()).getJSONArray("tableModule");
                            JSONArray columnValues = tableModule.getJSONObject(0).getJSONArray("columnValue");
                            String[] colName = columnValues.getString(0).split(";");
                            String[] colValue = columnValues.getString(1).split(";");
                            for (int y = 0; y < colName.length; y++){
                                testResult += colName[y] + ":" + colValue[y] + ";";
                            }
                        }
                    }else {
                        if (splits[x].contains("totalScoreDesc")){
                            String b = splits[x];
                            JSONArray totalScores = JSONArray.parseArray(b.replace("totalScore:", ""));
                            JSONObject totalScore = totalScores.getJSONObject(0);
                            testResult += "总分:" + totalScore.getString("totalScore")+";总分结论:"+totalScore.getString("totalScoreDesc")+";";
                        }
                        if (splits[x].contains("Describe")){
                            String b = splits[x];
                            JSONArray dimensions = JSONArray.parseArray(b.replace("dimensions:", ""));
                            for (int y = 0; y < dimensions.size(); y++) {
                                JSONObject dimension = dimensions.getJSONObject(y);
                                testResult += dimension.getString("name") + ":" + dimension.getString("score") + ";"
                                        + dimension.getString("name") + "结论:" + dimension.getString("Describe") + ";";
                            }
                        }
                    }

                }
                splits = testResult.split(";");
                //标题行抽出字段
                newTitle = new String[splits.length + 7];
                newTitle[0] = "姓名";
                newTitle[1] = "性别";
                newTitle[2] = "职业";
                newTitle[3] = "出生日期";
                newTitle[4] = "登录名";
                newTitle[5] = "测试时间";
                newTitle[6] = "测试名称";
                for (int x = 0; x < splits.length; x++) {
                    String[] a = splits[x].split(":");
                    newTitle[x + 7] = a[0];

                }
            }else {
                oldInstitutionUserRecordingList.add(institutionUserRecordingList.get(i));

                //标题行抽出字段
                oldTitle = new String[splits.length + 7];
                oldTitle[0] = "姓名";
                oldTitle[1] = "性别";
                oldTitle[2] = "职业";
                oldTitle[3] = "出生日期";
                oldTitle[4] = "登录名";
                oldTitle[5] = "测试时间";
                oldTitle[6] = "测试名称";
                for (int y = 0; y < splits.length; y++) {
                    String[] a = splits[y].split(":");
                    oldTitle[y + 7] = a[0];

                }
            }
        }

        //设置sheet名称，并创建新的sheet对象
        String newSheetName = "用户测试结果新结构导出";
        String oldSheetName = "用户测试结果老结构导出";
        if (newInstitutionUserRecordingList.size() > 0){
            Sheet newDownSheet = wb.createSheet(newSheetName);
            wb = insertData(newDownSheet,wb,newTitle,newInstitutionUserRecordingList,name);
        }
        if (oldInstitutionUserRecordingList.size() > 0){
            Sheet oldDownSheet = wb.createSheet(oldSheetName);
            wb = insertData(oldDownSheet,wb,oldTitle,oldInstitutionUserRecordingList,name);
        }

        String foldDir = null;
        //获取配置文件中保存对应excel文件的路径，本地也可以直接写成F：excel/stuInfoExcel路径
        foldDir = "./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + "用户测试结果导出";
        //创建上传文件目录
        File fileDir = new File(foldDir);

        //如果文件夹不存在创建对应的文件夹
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String testTime = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format(new Date());
        //设置文件名
        String fileName = institutionNo + "-" + name + "-" + testTime + ".xlsx";

        OutputStream fileOut = new FileOutputStream(foldDir + "/" + fileName);
        wb.write(fileOut);
        fileOut.close();

        File file = new File(foldDir + "/" + fileName);
        if (file.exists()) {
            if (name.equals(Constant.SHEET_NAME_CDT) || name.equals(Constant.SHEET_NAME_DSST)) {
                File[] srcFiles = new File[institutionUserRecordingList.size() + 1];
                int size = institutionUserRecordingList.size();
                for (int i = 0; i < size; i++) {
                    if (!StringUtil.isEmpty(institutionUserRecordingList.get(i).getImg())) {
                        srcFiles[i] = new File(institutionUserRecordingList.get(i).getImg());
                    }
                }

                srcFiles[institutionUserRecordingList.size()] = new File(foldDir + "/" + fileName);
                //srcFiles[recordingIds.size()] = new File(foldDir + "/" + fileName);
                File zipFile = new File(foldDir + "/" + name + ".zip");
                // 调用压缩方法
                zipFiles(srcFiles, zipFile);
                response.reset();
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) zipFile.length());
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name + ".zip", "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(zipFile);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                response.reset();
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }

        return "下载失败";
    }

    @SneakyThrows
    @ApiOperation(value = "原始数据批量下载接口")
    @GetMapping("/planResultBatch")
    public String downloadPlanResultBatch(@RequestParam(value = "ids", required = false) List<String> recordingIds,HttpServletResponse response) {

        //原始记录文件
        File file = null;
        //原始记录复制后文件
        File destFile = null;
        //查找原始记录路径文件夹名称
        String testDate;
        //查找原始记录路径文件夹名称
        String folderName = null;
        //所有记录汇总后文件夹，用来压缩
        String filePath ="./心理检测/答题记录";
        //原始记录文件名
        String fileName = null;
        for (int i = 0; i < recordingIds.size(); i++) {
            UserRecordEntity userRecordEntity = this.userRecordService.getUserRecordById(recordingIds.get(i));
            String[] split = userRecordEntity.getFileName().split("/");
            if (split.length > 1){
                //if (new File(userRecordEntity.getFileName()).exists()){
                fileName = split[split.length-1];
            }else {
                fileName = userRecordEntity.getFileName();
            }
            testDate = userRecordEntity.getTestDate();
            folderName = userRecordEntity.getName();
            testDate = testDate.substring(0, 10);
            testDate = testDate.replace("年", "-");
            testDate = testDate.replace("月", "-");
            //设置文件路径
            file = new File("./心理检测/检测结果/" + testDate + "/" + folderName + "/" + fileName);
            if (file.exists()){
                destFile = new File(filePath+"/"+folderName+"/"+userRecordEntity.getPhone()+"-"+userRecordEntity.getTestDate()+"-"+folderName+".xlsx");
                //将原始文件进行复制
                FileUtils.copyFile(file, destFile);
            }

        }

        //将复制后的整个文件夹打包
        ZipUtils.createZip(filePath, filePath + ".zip", true);

        File zipFile = new File(filePath + ".zip");
        //下载压缩后文件
        if (zipFile.exists()) {
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) zipFile.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("answerRecord.zip", "UTF-8"));

            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(zipFile);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //将复制后的整个文件夹删除
                Path path = Paths.get(filePath);
                try (Stream<Path> walk = Files.walk(path)) {
                    walk.sorted(Comparator.reverseOrder())
                            .forEach(DataDownloadController::deleteDirectoryStream);
                }
                //删除生成的压缩包
                Files.delete(Paths.get(filePath + ".zip"));
            }
        }

        //删除生成的压缩包
        Files.delete(Paths.get(filePath + ".zip"));
        //将复制后的整个文件夹删除
        Path path = Paths.get(filePath);
        try (Stream<Path> walk = Files.walk(path)) {
            walk.sorted(Comparator.reverseOrder())
                    .forEach(DataDownloadController::deleteDirectoryStream);
        }

        return "下载失败";
    }


    @SneakyThrows
    @ApiOperation(value = "原始数据全部下载接口")
    @GetMapping("/planResultAll")
    public String downloadPlanResultAll(String institutionNo, String name, String searchKey, String beginTime, String endTime, String groupId, HttpServletResponse response) {

        //原始记录文件
        File file = null;
        //原始记录复制后文件
        File destFile = null;
        //查找原始记录路径文件夹名称
        String testDate;
        //查找原始记录路径文件夹名称
        String folderName = null;
        //所有记录汇总后文件夹，用来压缩
        String filePath ="./心理检测/答题记录";
        //原始记录文件名
        String fileName = null;
        List<InstitutionRecordingUsersDTO> institutionUserRecordingList = this.userRecordService.getInstitution(institutionNo, name, searchKey, beginTime, endTime, groupId)
                .stream().sorted(Comparator.comparing(InstitutionRecordingUsersDTO::getTestDate)).collect(Collectors.toList());
        if (institutionUserRecordingList.isEmpty()) {
            return "无测试记录";
        }
        for (int i = 0; i < institutionUserRecordingList.size(); i++) {
            InstitutionRecordingUsersDTO userRecordEntity = institutionUserRecordingList.get(i);

            if (new File(userRecordEntity.getFileName()).exists()){
                String[] split = userRecordEntity.getFileName().split("/");
                fileName = split[split.length-1];
            }else {
                fileName = userRecordEntity.getFileName();
            }

            testDate = userRecordEntity.getTestDate();
            folderName = userRecordEntity.getName();
            testDate = testDate.substring(0,10);
            testDate = testDate.replace("年","-");
            testDate = testDate.replace("月","-");
            //设置文件路径
            file = new File("./心理检测/检测结果/" + testDate + "/" + folderName + "/" + fileName);
            destFile = new File(filePath+"/"+folderName+"/"+userRecordEntity.getPhone()+"-"+userRecordEntity.getTestDate()+"-"+folderName+".xlsx");

            //将原始文件进行复制
            FileUtils.copyFile(file, destFile);

        }

        //将复制后的整个文件夹打包
        ZipUtils.createZip(filePath,filePath+".zip",true);

        File zipFile = new File(filePath+".zip");
        //下载压缩后文件
        if (zipFile.exists()) {
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) zipFile.length());
            response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode("answerRecord.zip", "UTF-8"));

            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(zipFile);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //将复制后的整个文件夹删除
                Path path = Paths.get(filePath);
                try (Stream<Path> walk = Files.walk(path)) {
                    walk.sorted(Comparator.reverseOrder())
                            .forEach(DataDownloadController::deleteDirectoryStream);
                }
                //删除生成的压缩包
                Files.delete(Paths.get(filePath+".zip"));
            }
        }

        //删除生成的压缩包
        Files.delete(Paths.get(filePath+".zip"));
        //将复制后的整个文件夹删除
        Path path = Paths.get(filePath);
        try (Stream<Path> walk = Files.walk(path)) {
            walk.sorted(Comparator.reverseOrder())
                    .forEach(DataDownloadController::deleteDirectoryStream);
        }

        return "下载失败";

    }

    public static void zipFiles(File[] srcFiles, File zipFile) {
        // 判断压缩后的文件存在不，不存在则创建
        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream = null;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        // 创建 FileInputStream 对象
        FileInputStream fileInputStream = null;

        try {
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFile);
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry = null;
            // 遍历源文件数组
            for (int i = 0; i < srcFiles.length; i++) {
                // 将源文件数组中的当前文件读入 FileInputStream 流中
                fileInputStream = new FileInputStream(srcFiles[i]);
                // 实例化 ZipEntry 对象，源文件数组中的当前文件
                zipEntry = new ZipEntry(srcFiles[i].getName());
                zipOutputStream.putNextEntry(zipEntry);
                // 该变量记录每次真正读的字节个数
                int len;
                // 定义每次读取的字节数组
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将Map字符串转换为Map
     *
     * @param
     * @return
     */
    public static Workbook insertData(Sheet downSheet,Workbook wb,String[] title,List<InstitutionRecordingUsersDTO> institutionUserRecordingList,String name){
        //设置单元格宽度自适应，在此基础上把宽度调至1.5倍
        for (int i = 0; i < title.length; i++) {
            downSheet.autoSizeColumn(i, true);
            int colWidth = downSheet.getColumnWidth(i) * 2;
            if (colWidth < 255 * 256) {
                downSheet.setColumnWidth(i, Math.max(colWidth, 3000));
            } else {
                downSheet.setColumnWidth(i, 6000);
            }
        }
        //获取表头行
        Row titleRow = downSheet.createRow(0);
        //创建单元格，设置style居中，字体，单元格大小等
        CellStyle style = wb.createCellStyle();
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Cell cell = null;
        //把已经写好的标题行写入excel文件中
        for (int i = 0; i < title.length; i++) {
            cell = titleRow.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        //把从数据库中取得的数据一一写入excel文件中
        Row row = null;

        int size = institutionUserRecordingList.size();
        for (int i = 0; i < size; i++) {
            InstitutionRecordingUsersDTO institutionRecordingUsersDTO = institutionUserRecordingList.get(institutionUserRecordingList.size() - i - 1);
            String testResultls = institutionRecordingUsersDTO.getTestResults();
            String[] splitl = testResultls.split(";");
            if (testResultls.contains("version")){
                String testResultl = new String();
                for (int x = 0; x < splitl.length; x++) {
                    if (Arrays.toString(splitl).contains("columnValue")){
                        if (splitl[x].contains("columnValue")){
                            JSONArray tableModule = JSONObject.parseObject(institutionRecordingUsersDTO.getTestResult()).getJSONArray("tableModule");
                            JSONArray columnValues = tableModule.getJSONObject(0).getJSONArray("columnValue");
                            String[] colName = columnValues.getString(0).split(";");
                            String[] colValue = columnValues.getString(1).split(";");
                            for (int y = 0; y < colName.length; y++){
                                testResultl += colName[y] + ":" + colValue[y] + ";";
                            }
                        }
                    }else {
                        if (splitl[x].contains("totalScoreDesc")){
                            String b = splitl[x];
                            JSONArray totalScores = JSONArray.parseArray(b.replace("totalScore:", ""));
                            JSONObject totalScore = totalScores.getJSONObject(0);
                            testResultl += "总分:" + totalScore.getString("totalScore")+";总分结论:"+totalScore.getString("totalScoreDesc")+";";
                        }
                        if (splitl[x].contains("Describe")){
                            String b = splitl[x];
                            JSONArray dimensions = JSONArray.parseArray(b.replace("dimensions:", ""));
                            for (int y = 0; y < dimensions.size(); y++) {
                                JSONObject dimension = dimensions.getJSONObject(y);
                                testResultl += dimension.getString("name") + ":" + dimension.getString("score") + ";"
                                        + dimension.getString("name") + "结论:" + dimension.getString("Describe") + ";";
                            }
                        }
                    }
                }
                splitl = testResultl.split(";");
                //continue;
            }/*else {
                splitl = testResultl.split(";");
            }*/
            //创建list.size()行数据
            row = downSheet.createRow(i + 1);

            //把值一一写进单元格里
            Cell cell4 = row.createCell(4);
            cell4.setCellValue(institutionRecordingUsersDTO.getPhone());
            cell4.setCellStyle(style);
            Cell cell5 = row.createCell(5);
            cell5.setCellValue(institutionRecordingUsersDTO.getTestDate());
            cell5.setCellStyle(style);
            Cell cell6 = row.createCell(6);
            cell6.setCellValue(name);
            cell6.setCellStyle(style);

            Cell cell0 = row.createCell(0);
            cell0.setCellValue(institutionRecordingUsersDTO.getPetName());
            cell0.setCellStyle(style);
            Cell cell2 = row.createCell(2);
            cell2.setCellValue(institutionRecordingUsersDTO.getProfession());
            cell2.setCellStyle(style);
            Cell cell1 = row.createCell(1);
            if (institutionRecordingUsersDTO.getGender().equals("0")) {
                cell1.setCellValue("男");
            } else {
                cell1.setCellValue("女");
            }
            cell1.setCellStyle(style);
            Cell cell3 = row.createCell(3);
            cell3.setCellValue(institutionRecordingUsersDTO.getBirthday());
            cell3.setCellStyle(style);

            for (int z = 0; z < splitl.length; z++) {
                String[] a = splitl[z].split(":");
                Cell rowCell = row.createCell(z + 7);
                if (a.length < 2){
                    rowCell.setCellValue("无");
                }else {
                    rowCell.setCellValue(a[1]);
                }
                rowCell.setCellStyle(style);
            }
        }

        return wb;
    }

    private static void deleteDirectoryStream(Path path) {
        try {
            Files.delete(path);
            //System.out.printf("删除文件成功：%s%n",path.toString());
        } catch (IOException e) {
            //System.err.printf("无法删除的路径 %s%n%s", path, e);
        }
    }

}
