/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/19 14:39
 * Description:在院浏览
 */
package com.emr.controller;

import com.emr.annotation.OptionalLog;
import com.emr.entity.*;
import com.emr.service.*;
import com.emr.util.*;
import com.itextpdf.text.pdf.PdfReader;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/inHosp")
public class inHospitalController {
    //private Logger logger = Logger.getLogger(inHospitalController.class);

    @Autowired
    private Archive_MasterService archiveMasterService;

    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    @Autowired
    private Archive_DetailService archiveDetailService;

    @Autowired
    private Emr_PictureService emrPictureService;

    @Autowired
    private Zd_AssortService zd_assortService;

    @Autowired
    private Archive_Detail_PictureService archiveDetailPictureService;

    @Resource
    private LogService logService;

    @Value("${pictureUrl}")
    private String pictureUrl;

    @Value("${pdfUrl}")
    private String pdfUrl;

    @Value("${autoPdfUrl}")
    private String autoPdfUrl;

    @Value("${pdfErrorUrl}")
    private String pdfErrorUrl;


    //@Value("${pdfDelPicUrl}")
    //private String pdfDelPicUrl;

    @RequestMapping(value = "/inHospitals")
    public String inHospitals(Model model) {
        return "inHospitalDir/inHositalList";
    }

    @ResponseBody
    @RequestMapping(value = "/inHospitalList")
    public OffsetLimitPage inHospitalList(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        OffsetLimitPage result = archiveMasterService.selectByCol(archiveMasterVo, offset, limit);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"病历清单id","住院号","住院次数","名字","性别","身份证","入院科室","入院日期","主管医生","状态"};
        String[] fileNames = {"id","inpNo","visitId","name","sex","idNo","deptAdmissionTo","admissionDateTime","doctorInCharge","archivestate"};
        //文件名
        String fileName = "在院浏览" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Archive_Master> list = archiveMasterService.selectByCol(archiveMasterVo);
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        String result=utils.exportExcelToFilePath(response,utils.listConvert(list));
    }

    @ResponseBody
    @RequestMapping(value = "/getDept")
    public List<Emr_Dictionary> getDept(HttpServletResponse response, Emr_Dictionary emrDictionary) throws Exception {
        emrDictionary.setEffective(1);
        emrDictionary.setTypecode("dept_code");
        //科室列表
        return emrDictionaryService.dicByTypeCode(emrDictionary);
    }

    @ResponseBody
    @RequestMapping(value = "/getAssort")
    public List<Archive_Detail_Vo> getAssort(HttpServletResponse response, Archive_Detail_Vo archiveDetailVo) throws Exception {
        //分段列表
        List<Archive_Detail_Vo> newList=archiveDetailService.selectByClo(archiveDetailVo);
        //查询新生儿数据并存入list
        Integer page=archiveDetailService.selectChildByClo(archiveDetailVo);
        if(page!=0){
            Archive_Detail_Vo archiveDetailVoNew=new Archive_Detail_Vo();
            archiveDetailVoNew.setAssortId("1000");
            archiveDetailVoNew.setAssortName("新生儿病历");
            archiveDetailVoNew.setPrintFlag("0");
            archiveDetailVoNew.setPageNum(page);
            archiveDetailVoNew.setAssortSort((short)1000);
            newList.add(archiveDetailVoNew);
        }
        return newList;
    }

    //@OptionalLog(methods = "调用单个作废")
    @ResponseBody
    @RequestMapping(value = "/getAssortdetail")
    public OffsetLimitPage getAssortdetail(HttpServletResponse response, Archive_Detail_Vo archiveDetailVo, Integer offset, Integer limit) throws Exception {
        //分段详情列表分页
        OffsetLimitPage result =null;
        //判断是否是新生儿数据 assortId=1000
        if("1000".equals(archiveDetailVo.getAssortId())){
            result = archiveDetailService.selectChild(archiveDetailVo, offset, limit);
        }else {
             result = archiveDetailService.detailByClo(archiveDetailVo, offset, limit);
        }
        return result;
    }

    //@OptionalLog(methods = "调用单个作废")
    @ResponseBody
    @RequestMapping(value = "/getSourceByClo")
    public List<Archive_Detail_Vo> getSourceByClo(HttpServletResponse response, Archive_Detail_Vo archiveDetailVo) throws Exception {
        //分段详情来源列表
        return archiveDetailService.sourceByClo(archiveDetailVo);
    }

    @OptionalLog(methods = "调用单个作废")
    @ResponseBody
    @RequestMapping(value = "/updateState")
    public int updateState(HttpServletRequest request, HttpServletResponse response, Archive_Detail archiveDetail) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        archiveDetail.setFlag("1");
        //修改状态分段信息
        return archiveDetailService.updateCloById(archiveDetail);
    }


    @ResponseBody
    @RequestMapping(value = "/delPdfInfo")
    public int delPdfInfo(HttpServletRequest request, HttpServletResponse response, Archive_Detail archiveDetail) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Archive_Detail detail = archiveDetailService.selectByid(archiveDetail.getId());
        if (detail != null) {
            if (detail.getPdfPath() != null) {
                //将之前文件删除
                File file2 = new File(detail.getPdfPath());
                if (file2.exists() && file2.isFile()) {
                    file2.delete();
                }
                if(detail.getRecoverPdfPath()!=null &&detail.getRecoverPdfPath()!="") {
                    File file3 = new File(detail.getRecoverPdfPath());
                    if (file3.exists() && file3.isFile()) {
                        file3.delete();
                    }
                }
            }
        }
        //http://127.0.0.1:8080/emr_medical_record/static/img/login.jpg
        // 项目在容器中实际发布运行的根路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        // 设置存放图片文件的路径
        String pdfDelPicUrl = "static\\img\\delPicImg\\";
        int bol = archiveDetailService.delById(archiveDetail.getId());
        //备份都删除
        if (bol == 1) {
            Archive_Detail_Picture archiveDetailPicture = new Archive_Detail_Picture();
            archiveDetailPicture.setParentId(archiveDetail.getId());
            if (archiveDetail.getPdfPath() != null && archiveDetail.getPdfPath() != "") {
                archiveDetailPicture.setMaxPicture("static\\img\\delPicImg\\" + archiveDetail.getPdfPath() + "\\" + archiveDetail.getPdfPath() + "_");
            }
            archiveDetailPictureService.deleteByCol(archiveDetailPicture);
            //删除图片
            //将之前文件删除
            File file = new File(realPath + pdfDelPicUrl + archiveDetail.getPdfPath() + "\\");
            PrintToPdfUtil.delete(file);
        }


        //修改状态分段信息
        return bol;
    }

    @OptionalLog(methods = "调用多个作废")
    @ResponseBody
    @RequestMapping(value = "/updateStateAll")
    public int updateStateAll(HttpServletRequest request, HttpServletResponse response, Archive_Detail archiveDetail) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int bol = 0;
        String idStr = archiveDetail.getId();
        if (idStr.length() > 0) {
            String[] idArr = idStr.split(",");
            //archiveDetail.setFlag("1");
            for (int i = 0; i < idArr.length; i++) {
                archiveDetail.setId(idArr[i]);
                //修改状态分段信息
                bol = archiveDetailService.updateCloById(archiveDetail);
            }
        }
        return bol;
    }

    @ResponseBody
    @RequestMapping(value = "/saveInfo")
    public String saveInfo(HttpServletRequest request, HttpServletResponse response, Archive_Detail archiveDetail) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String result = "";
        //判断id是否为空
        if (archiveDetail.getId() == null || archiveDetail.getId() == "") {
            //生成id
            //插入记录
            int bol = archiveDetailService.insertSel(archiveDetail);
            if (1 == bol) {
                result = "添加成功!";
            } else {
                result = "添加失败!";
            }

        } else {
            //根据id查找是否存在记录
            Archive_Detail entity = archiveDetailService.selectByid(archiveDetail.getId());
            if (entity != null) {
                //修改记录
                int bol = archiveDetailService.updateCloById(archiveDetail);
                if (1 == bol) {
                    result = "修改成功!";
                } else {
                    result = "修改失败!";
                }
            } else {
                result = "该记录不存在!";
            }
        }

        return result;
    }

    //2021-03-15更新优化
    private String GeneratePDFFileByAssortID(String masterId, String assortID, String realPath, String flag) throws Exception {
        List<MergePDFItem> pdfList = new ArrayList();
        Archive_Detail archiveDetail = new Archive_Detail();
        archiveDetail.setFlag(flag);
        archiveDetail.setMasterid(masterId.trim());
        List<Archive_Detail> arList =new ArrayList<>();
        //如果是新生儿，则不加分段id的筛选条件,
        if("1000".equals(assortID)){
             arList =archiveDetailService.selectChildList(archiveDetail);
        }else{
            archiveDetail.setTitle(assortID);
            arList = archiveDetailService.selectByCol(archiveDetail);
        }

        List<Archive_Detail> errorPdfList = new ArrayList<>();
        int size = 0;
        if (arList == null || arList.size() == 0) {
            return "";
        }
        for (int m = 0; m < arList.size(); m++) {
            MergePDFItem mergePDFItem = new MergePDFItem();
            String str = arList.get(m).getPdfPath();
            if (str != "" && str != null) {
                if (str.indexOf("..\\static\\img\\pdfFiles\\") != -1) {
                    str = str.split("pdfFiles")[1];
                    str = realPath + "pdfFiles" + str;
                }
                if (!PrintToPdfUtil.checkPdfFile(str)) {
                    arList.get(m).setPdfPath(str);
                    errorPdfList.add(arList.get(m));
                } else {
                    mergePDFItem.setPdfPath(str);
                    mergePDFItem.setdObj(arList.get(m));
                    pdfList.add(mergePDFItem);
                }
            }
        }

        String pdfFileName = String.valueOf(System.currentTimeMillis());
        String pdfPath = autoPdfUrl.trim() + "/" + pdfFileName + ".pdf";

        if (pdfList.size() > 0) {
            //对所有地址的pdf进行合成
            //if (errorPdfList.size() != size) {
            PrintToPdfUtil.mergePdfFiles2(pdfList, pdfPath);
            //} else {
            // result = "";
            // }
            if (errorPdfList.size() > 0) {
                ExportTxtPaper.exportTxtPaper(pdfErrorUrl, "不存在或损坏PDF文件列表" + pdfFileName + ".txt", errorPdfList);
            }
        }
        return pdfPath;
    }


    /**
     * 根据病案号或类别或图片id获取图片列表，并生成PDF并返回pdf文件名
     *
     * @param response
     * @param request
     * @param imgStr
     * @param masterId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getPdfToPdf")
    public String getPdfToPdf(HttpServletResponse response, HttpServletRequest request, String imgStr, String masterId, String flag) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String result = "";
        // 项目在容器中实际发布运行的根路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        //realPath = realPath.split("target")[0]
        realPath = pictureUrl + "\\static\\img\\";
        //pdf名称
        String pdfFileName = String.valueOf(System.currentTimeMillis());
        //病案号文件夹
        if (masterId == "" && masterId == null) {
            result = "";
            return result;
        }
        //判断文件夹是否存在
        File fileDic = new File(realPath + masterId + "\\");
        if (!fileDic.exists() && !fileDic.isDirectory()) {
            fileDic.mkdirs();
        }
        List<Zd_Assort> zds = zd_assortService.selectByColm(new Zd_Assort()); //from db
        //from args
        //病案号/类别/id文件夹(图片路径下的子文件夹名称)
        //生成pdf(图片路径，pdf生成路径，图片路径文件夹列表)
        List imgList = new ArrayList();
        if (imgStr != "" && imgStr != null) {
            String[] imgArr = imgStr.split(",");
            if (imgArr.length > 0) {
                for (int i = 0; i < imgArr.length; i++) {
                    imgList.add(imgArr[i]);
                }
            }
        }

        for (int i = zds.size() - 1; i >= 0; i--) {
            String a = zds.get(i).getAssortId();
            if (imgList.indexOf(a) == -1) {
                zds.remove(i);
            }
        }

        ArrayList<String> fileList = new ArrayList<>();
        for (int i = 0; i < zds.size(); i++) {
            String asordID = zds.get(i).getAssortId();
            String pdfA = GeneratePDFFileByAssortID(masterId, asordID, realPath, flag);
            if (pdfA == "" || pdfA.length() == 0) {
                continue;
            }
            fileList.add(pdfA);
        }
        if (fileList.size() == 0) {
            return "";
        }

        String pdfPath = autoPdfUrl.trim() + "/" + String.valueOf(System.currentTimeMillis()) + ".pdf";
        PDFHelper.Append(fileList, pdfPath);
        //PrintToPdfUtil.mergePdfFiles(fileList, pdfPath);
        return pdfPath;
    }

    /**
     * 根据病案号或类别或图片id获取图片列表，并生成PDF并返回pdf文件名
     *
     * @param response
     * @param request
     * @param imgStr
     * @param masterId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getPdf")
    public String getPdf(HttpServletResponse response, HttpServletRequest request, String imgStr, String masterId) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String result = "";
        // 项目在容器中实际发布运行的根路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        realPath = pictureUrl + "\\";
        //pdf名称
        String pdfFile = String.valueOf(System.currentTimeMillis());
        String pdfPath = realPath + "pdfFiles\\" + pdfFile + ".pdf";
        //病案号文件夹
        if (masterId != "" && masterId != null) {
            realPath = realPath + masterId + "\\";
            //判断文件夹是否存在
            File fileDic = new File(realPath);
            if (!fileDic.exists() && !fileDic.isDirectory()) {
                fileDic.mkdirs();
            }

            //病案号/类别/id文件夹(图片路径下的子文件夹名称)
            //生成pdf(图片路径，pdf生成路径，图片路径文件夹列表)
            List imgList = new ArrayList();
            if (imgStr != "" && imgStr != null) {
                String[] imgArr = imgStr.split(",");
                if (imgArr.length > 0) {
                    for (int i = 0; i < imgArr.length; i++) {
                        imgList.add(imgArr[i]);
                    }
                }
            }

            //imgList.add(imgStr.split())imgStr.split(","));
            PrintToPdfUtil.toPdf(realPath, pdfPath, imgList);

            result = pdfFile + ".pdf";
        } else {
            result = "a000000.pdf";
        }
        return result;
    }

    /**
     * 根据病案号或类别或图片id获取图片列表，并生成PDF并返回pdf文件名
     *
     * @param response
     * @param request
     * @param idStr    *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getPdfById")
    public String getPdfById(HttpServletResponse response, HttpServletRequest request, @Param("id") String idStr) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String result = "";
        // 项目在容器中实际发布运行的根路径
        String realPath = pictureUrl + "\\";
        //pdf名称
        String pdfFile = String.valueOf(System.currentTimeMillis());
        String pdfPath = autoPdfUrl.trim() + "/" + pdfFile + ".pdf";
        Archive_Detail detail = new Archive_Detail();
        detail.setTitle(idStr);
        //根据所有id获取PDF列表
        List<Archive_Detail> arList = archiveDetailService.selectByIdStr(detail);
        //获取废除的pdf文件名列表archive_detail
        List pdfList = new ArrayList();
        //损坏PDF文件列表
        List<Archive_Detail> errorPdfList = new ArrayList<Archive_Detail>();
        int size = 0;
        //将所有记录的pdf数组里面\static\img\pdfFiles\typesPdf
        if (arList != null && arList.size() > 0) {
            for (int m = 0; m < arList.size(); m++) {
                String str = arList.get(m).getPdfPath();
                if (str != "" && str != null) {
                    size++;
                    if (str.indexOf("..\\static\\img\\pdfFiles\\") != -1) {
                        str = str.split("pdfFiles")[1];
                        str = realPath + "pdfFiles" + str;
                    }
                    if (!PrintToPdfUtil.checkPdfFile(str)) {
                        arList.get(m).setPdfPath(str);
                        errorPdfList.add(arList.get(m));
                    } else {
                        pdfList.add(str);
                    }
                }
            }
            if (pdfList.size() > 0) {
                //if (errorPdfList.size() != size) {
                //对所有地址的pdf进行合成
                PrintToPdfUtil.mergePdfFiles(pdfList, pdfPath);
                result = pdfPath;
                //} else {
                //  result = "";
                //}
                if (errorPdfList.size() > 0) {
                    ExportTxtPaper.exportTxtPaper(pdfErrorUrl, "不存在或损坏PDF文件列表" + pdfFile + ".txt", errorPdfList);
                }
            }
        } else {
            result = "";
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/delPdf")
    public String delPdf(HttpServletResponse response, HttpServletRequest request, String pdfName) throws Exception {
        String msg = "";
        // 项目在容器中实际发布运行的根路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        realPath = pictureUrl + "\\";
        realPath = realPath + "pdfFiles\\" + pdfName + ".pdf";
        //将之前文件删除
        File file1 = new File(realPath);
        if (file1.exists() && file1.isFile()) {
            file1.delete();
            msg = "删除成功";
        }
        return msg;
    }

    @ResponseBody
    @RequestMapping(value = "/delImg")
    public String delImg(HttpServletResponse response, HttpServletRequest request, Emr_Picture emrPicture) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String msg = "";
        int bol = 0;
        if (emrPicture.getId() != null && emrPicture.getId() != "" && emrPicture.getId() != "-1") {
            //判断记录是否存在
            Emr_Picture entity = emrPictureService.selectByid(emrPicture.getId());
            if (entity != null) {
                String realPath = pictureUrl + "\\";
                String imgPath = entity.getMaxPicture().replace("..", realPath);
                //将之前图片文件删除
                File file1 = new File(imgPath);
                if (file1.exists() && file1.isFile()) {
                    file1.delete();
                }
                // 设置存放图片文件的路径
                String path2 = "";

                //病案号
                if (entity.getRelationId() != null && entity.getRelationId() != "") {
                    path2 = path2 + entity.getRelationId() + "\\";
                }

                //类型
                if (entity.getAssortId() != null && entity.getAssortId() != "") {
                    path2 = path2 + entity.getAssortId() + "\\";
                }
                String pdfPath = realPath + entity.getRelationId() + "\\" + entity.getAssortId() + "\\" + entity.getAssortId() + ".pdf";

                // if (msg.equals("文件未被操作!")) {
                //将之前文件删除
                File file = new File(pdfPath);
                if (file1.exists() && file1.isFile()) {
                    file1.delete();
                }
                //重新生成pdf
                //读取指定路径下的文件名和目录名
                List arr = new ArrayList();
                //arr.add(pathType);
                //图片转PDF(病案号文件夹+类别文件夹)
                if (arr.size() > 0) {
                    msg = PrintToPdfUtil.toPdf(realPath + path2, pdfPath, arr);
                }
                //存在删除
                bol = emrPictureService.deleteById(emrPicture.getId());
                //判断图片是否存在如果不存在则删除类别PDF
                Emr_Picture obj = new Emr_Picture();
                obj.setRelationId(entity.getRelationId());
                obj.setAssortId(entity.getAssortId());
                List<Emr_Picture> picL = emrPictureService.selectByClo(obj);
                if (picL.size() == 0) {
                    Archive_Detail detailObj = new Archive_Detail();
                    detailObj.setMasterid(entity.getRelationId());
                    detailObj.setAssortid(entity.getAssortId());
                    String pdfpaht = pictureUrl + "\\" + entity.getRelationId() + "\\" + entity.getAssortId() + "\\" + entity.getAssortId() + ".pdf";
                    detailObj.setPdfPath(pdfpaht);
                    //该病案的类型无图片则删除该病案类型的PDF及删除PDF记录
                    List<Archive_Detail> detailsL = archiveDetailService.selectByColm(detailObj);
                    if (detailsL.size() > 0) {
                        archiveDetailService.delById(detailsL.get(0).getId());
                        // 判断pdf是否存在，将之前文件删除
                        File file2 = new File(pdfpaht);
                        if (file2.exists() && file2.isFile()) {
                            file2.delete();
                        }
                    }
                }
                // }
            }
        }
        // if (msg.equals("文件未被操作!")) {
        if (bol == 1) {
            msg = "删除成功!";
        } else {
            msg = "删除失败!";
        }
        //}else{
        // msg="文件正被操作!";
        // }
        return msg;
    }

    /**
     * 图片列表查询
     *
     * @param response
     * @param
     * @param emrPicture
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getPicList")
    public List<Emr_Picture> getPicList(HttpServletResponse response, Emr_Picture emrPicture) throws Exception {
        List<Emr_Picture> picList = emrPictureService.selectByClo(emrPicture);
        return picList;
    }


    /**
     * 批量图片上传
     *
     * @param resp
     * @param request
     * @param
     * @return
     * @throws IOException
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/uploadImgS", method = RequestMethod.POST)
    public String uploadImgS(HttpServletResponse resp, HttpServletRequest request, @RequestParam MultipartFile[] imgs) throws Exception {
        resp.setContentType("text/json");
        resp.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String firstFile = request.getParameter("fileName");
        String list = request.getParameter("list");
        String masterID = request.getParameter("masterID");
        int t = 0;
        //String id = request.getParameter("id");
        JSONArray fileObj = JSONArray.fromObject(list);
        String result = "";
        if (!masterID.isEmpty()) {
            String fileName = "";
            String path = null;
            String type = null;
            //type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            // 项目在容器中实际发布运行的根路径
            String realPath = pictureUrl + "\\";

            // 设置存放图片文件的路径
            String path2 = "";

            //病案号
            if (masterID != null && masterID != "") {
                path2 = path2 + masterID + "\\";
            }


            // 从session获取用户名
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String username = user.getUserName();
            //类循环
            if (fileObj != null && fileObj.size() > 0) {
                for (int x = 0; x < fileObj.size(); x++) {
                    JSONObject obj = fileObj.getJSONObject(x);
                    //类别
                    String pathType = "";
                    if (obj.get("selectVal") != null && obj.get("selectVal") != "") {
                        pathType = obj.get("selectVal") + "\\";

                        //图片id
//                        if (id != null && id != "") {
//                            path2 = path2 + id + "\\";
//                        } else {
//                            path2 = path2 + idTime + "\\";
//                        }

                        //判断文件夹是否存在
                        File fileDic = new File(realPath + path2 + pathType);
                        if (!fileDic.exists() && !fileDic.isDirectory()) {
                            fileDic.mkdirs();
                        }

                        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String nowTime = format1.format(new Date());

                        //创建时间id
                        String idTime = String.valueOf(System.currentTimeMillis());
                        String trueFileName = "";

                        //将其路径及文件名类型以及参数保存图片相关信息到分段详细表
                        Emr_Picture entity = new Emr_Picture();
                        entity.setRelationId(masterID);
                        entity.setAssortId(obj.get("selectVal").toString());
                        //entity.setMasterid(masterID);
                        entity.setUpdateTime(nowTime);
                        entity.setUpdater(username);


                        int bol = 0;
                        String id = obj.get("id").toString();
                        if (id != null && id != "" && !id.equals("-1")) {
                            Emr_Picture picList = emrPictureService.selectByid(id);

                            // entity.setTypeFlag(id);
                            //判断记录是否已经存在
                            if (picList != null) {
                                entity.setId(id);
                                //图片是否有改动有改动则删除之前重新上传
                                //String[] img= picList.getMaxPicture().split("/");

                                if (picList.getAssortId() != entity.getAssortId() || picList.getRelationId() != entity.getRelationId()) {

                                    //if(img[img.length-1]!= obj.get("fileSrc")){
                                    //将之前文件删除
//                                    File file1 = new File(realPath + "/static" + picList.getMaxPicture().split("static")[1]);
//                                    if (file1.exists() && file1.isFile()) {
//                                        file1.delete();
//                                    }
                                    //上传图片
                                    //imgs[x].transferTo(new File(realPath + path2 + pathType + trueFileName));
                                    //System.out.println(oldName);picList.getMaxPicture()

                                    if (picList.getMaxPicture().indexOf(path2 + pathType) == -1) {

                                        // 移动图片
                                        String startPath = picList.getMaxPicture().trim();
                                        String endPath = realPath + path2 + pathType;
                                        PrintToPdfUtil.moveTotherFolders(startPath, endPath);
                                        String[] oldName = picList.getMaxPicture().split("\\\\");

                                        //新的图片地址
                                        entity.setMaxPicture(realPath + path2 + pathType + oldName[oldName.length - 1]);
                                    }
                                    //被修改的类别重新生成pdf，查询出pdf记录
                                    //根据病案号和类别查询是否存在
                                    Archive_Detail detail = new Archive_Detail();
                                    detail.setMasterid(masterID);
                                    detail.setAssortid(picList.getAssortId());
                                    List<Archive_Detail> detailList = archiveDetailService.selectByColm(detail);
//                                  if(detailList!=null){
//                                    for(int s=0;s<detailList.size)
//                                    if(detailList.get(i).getPdfPath().indexOf(detail.getAssortid()+".pdf")!=-1){
//                                        //判断pdf是否存在，将之前文件删除
//                                        File file1 = new File(detailList.get(0).getPdfPath());
//                                        if (file1.exists() && file1.isFile()) {
//                                            //boolean b = file1.delete();
//                                            // if (!b) {
//                                            //FileWriter fw = new FileWriter(file1);
//                                            // fw.close();
//                                            file1.delete();
//                                            //}
//                                        }
//                                    }
                                    //}


                                    //读取指定路径下的文件名和目录名
                                    List arr = new ArrayList();
                                    arr.add(picList.getAssortId());
                                    //图片转PDF(病案号文件夹+类别文件夹)
                                    String str = PrintToPdfUtil.toPdf(realPath + path2 + picList.getAssortId(), realPath + detail.getMasterid() + "\\" + picList.getAssortId() + "\\" + picList.getAssortId() + ".pdf", arr);
                                    //判断pdf文件大小等于了则删除，并删除pdf记录
                                    File file = new File(realPath + detail.getMasterid() + "\\" + picList.getAssortId() + "\\" + picList.getAssortId() + ".pdf");
                                    if (file.exists() && file.isFile()) {
                                        //System.out.println("文件" + file.getName() + "的大小是：" + file.length());
                                        if (file.length() == 0) {
                                            String pdfPathVal = realPath + detail.getMasterid() + "\\" + picList.getAssortId() + "\\" + picList.getAssortId() + ".pdf";
                                            detail.setPdfPath(pdfPathVal);
                                            archiveDetailService.deleteByClo(detail);

                                            //file.delete();
                                            boolean b = file.delete();
                                            if (!b) {
                                                FileWriter fw = new FileWriter(file);
                                                fw.close();
                                                file.delete();
                                            }
                                            System.out.println("文件已经被成功删除");
                                            detail.setPdfPath("");
                                        }
                                    }

                                    //根据id修改记录
                                    bol = emrPictureService.updateCloByIdOrFlay(entity);
                                    //}
                                    if (bol == 1) {
                                        result = "批量上传成功!";
                                    } else {
                                        result = "批量上传失败!";
                                    }
                                }
                            } else {
                                //得到图片名
                                String oldName = imgs[t].getOriginalFilename();// 如apple1.jpg
                                String lasName = oldName.substring(oldName.lastIndexOf(".") + 1);
                                if ("GIF".equals(lasName.toUpperCase()) || "JPEG".equals(lasName.toUpperCase()) || "PNG".equals(lasName.toUpperCase()) || "JPG".equals(lasName.toUpperCase())) {

                                    // 自定义的文件名称String.valueOf(System.currentTimeMillis())
                                    trueFileName = firstFile + idTime + oldName;

                                    //上传图片
                                    imgs[t].transferTo(new File(realPath + path2 + pathType + trueFileName));
                                    entity.setId(idTime);
                                    entity.setCreater(username);
                                    entity.setCreateTime(nowTime);
                                    entity.setEffective(1);
                                    entity.setMaxPicture(realPath + path2 + pathType + trueFileName);

                                    //插入记录
                                    bol = emrPictureService.insertSel(entity);

                                }
                                t++;
                            }
                        } else {
                            //得到图片名
                            String oldName = imgs[t].getOriginalFilename();// 如apple1.jpg
                            String lasName = oldName.substring(oldName.lastIndexOf(".") + 1);
                            if ("GIF".equals(lasName.toUpperCase()) || "JPEG".equals(lasName.toUpperCase()) || "PNG".equals(lasName.toUpperCase()) || "JPG".equals(lasName.toUpperCase())) {
                                // 自定义的文件名称String.valueOf(System.currentTimeMillis())
                                trueFileName = firstFile + idTime + oldName;
                                //上传图片
                                imgs[t].transferTo(new File(realPath + path2 + pathType + trueFileName));
                                //新的图片地址
                                entity.setMaxPicture(realPath + path2 + pathType + trueFileName);
                                entity.setId(idTime);
                                entity.setCreater(username);
                                entity.setCreateTime(nowTime);
                                entity.setEffective(1);
                                //插入记录
                                bol = emrPictureService.insertSel(entity);
                            }
                            t = t + 1;
                        }

                        if (bol == 1) {
                            //根据类别生成pdf:pathType(String.valueOf(System.currentTimeMillis()) )
                            String pdfFile = pathType.replace("\\", "") + ".pdf";
                            //根据病案号和类别查询是否存在
                            Archive_Detail detail = new Archive_Detail();
                            detail.setMasterid(masterID);
                            detail.setAssortid(pathType.replace("\\", ""));
                            detail.setPdfPath(realPath + masterID + "\\" + pathType.replace("\\", "") + "\\" + pathType.replace("\\", ".pdf"));
                            List<Archive_Detail> voList = archiveDetailService.selectByColm(detail);

                            //pdf存在则删除记录和文件
                            if (voList.size() <= 0) {
                                //不存在添加记录和转换pdf
                                detail.setFlag("0");//显示
                                detail.setSource("后台");
                                detail.setSys("emr_medical_record");
                                detail.setTitle("自动生成"+obj.get("selectName")+"PDF");
                                detail.setUploaddatetime(nowTime);
                                detail.setPdfPath(realPath + masterID + "\\" + pathType + pdfFile);
                                //类名
                                int b = archiveDetailService.insertSel(detail);
                            }

                            //判断pdf是否存在，将之前文件删除
                            File file1 = new File(realPath + masterID + "\\" + pathType + pdfFile);
                            if (file1.exists() && file1.isFile()) {
                                file1.delete();
                                //FileUtils.forceDelete(file1);
                            }

                            //读取指定路径下的文件名和目录名
                           String pdfPathFile=realPath + path2+pathType.replace("\\", "")+"\\"+pathType.replace("\\", "")+".pdf";
                           //获取图片的绝对路径，根据路径合成一份pdf文件
                            entity = new Emr_Picture();
                            entity.setRelationId(masterID);
                            entity.setAssortId(obj.get("selectVal").toString());
                            List<Emr_Picture> imgsList=emrPictureService.selectByClo(entity);
                            result=PrintToPdfUtil.imgsListTopdf(pdfPathFile,imgsList);
                            if(result.equals("合成pdf成功")){
                                result = "批量上传成功!";
                            }else{
                                result=result;
                            }
                            /* 根据文件夹合成图片
                            List dirList = new ArrayList();
                            dirList.add(pathType.replace("\\", ""));
                            try {
                                PrintToPdfUtil.image2pdf(realPath + path2, dirList);
                            } catch (DocumentException e) {
                                e.printStackTrace();
                            }*/

                        } else {
                            result = "批量上传失败!";
                        }
                    } else {
                        result = "没有找到相对应的文件!";
                    }
                }
            }
        }

        return result;
    }

    /**
     * 图片上传
     *
     * @param resp
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public String uploadImg(HttpServletResponse resp, HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        resp.setContentType("text/json");
        resp.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String firstFile = request.getParameter("fileName");
        String id = request.getParameter("id");
        String masterID = request.getParameter("masterID");
        String assortID = request.getParameter("assortID");
        String result = "";
        if (!file.isEmpty()) {
            // logger.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            //logger.info("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase()) || "JPEG".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    realPath = realPath.split("target")[0] + pictureUrl;

                    //创建时间id
                    String idTime = String.valueOf(System.currentTimeMillis());
                    // 自定义的文件名称String.valueOf(System.currentTimeMillis())
                    String trueFileName = firstFile + idTime + fileName.split(".")[1];
                    // 设置存放图片文件的路径
                    String path2 = "\\static\\img\\uploads\\";

                    //病案号
                    if (masterID != null && masterID != "") {
                        path2 = path2 + masterID + "\\";
                    }
                    //类别
                    if (assortID != null && assortID != "") {
                        path2 = path2 + assortID + "\\";
                    }

                    //图片id
                    if (id != null && id != "") {
                        path2 = path2 + id + "\\";
                    } else {
                        path2 = path2 + idTime + "\\";
                    }

                    //判断文件夹是否存在
                    File fileDic = new File(realPath + path2);
                    if (!fileDic.exists() && !fileDic.isDirectory()) {
                        fileDic.mkdirs();
                    }
                    //logger.info("存放图片文件的路径:" + path);
                    path = realPath + path2 + trueFileName;

                    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String nowTime = format1.format(new Date());
                    //将其路径及文件名类型以及参数保存图片相关信息到分段详细表
                    Emr_Picture entity = new Emr_Picture();
                    entity.setRelationId(masterID);
                    entity.setAssortId(assortID);
                    entity.setUpdateTime(nowTime);
                    entity.setMaxPicture(".." + path2 + trueFileName);

                    // 从session获取用户名
                    Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                    String username = user.getUserName();//工号
                    entity.setUpdater(username);


                    int bol = 0;
                    if (id != null && id != "") {
                        Emr_Picture pic = new Emr_Picture();
                        pic.setTypeFlag(id);
                        List<Emr_Picture> list = emrPictureService.selectByClo(pic);
                        entity.setTypeFlag(id);
                        if (list.size() > 0) {
                            //将之前文件删除
                            File file1 = new File(realPath + "/static" + list.get(0).getMaxPicture().split("static")[1]);
                            if (file1.exists() && file1.isFile()) {
                                file1.delete();
                            }
                            //根据id修改记录
                            bol = emrPictureService.updateCloByIdOrFlay(entity);
                        } else {
                            entity.setId(idTime);
                            entity.setCreater(username);
                            entity.setCreateTime(nowTime);
                            entity.setEffective(1);
                            //插入记录
                            bol = emrPictureService.insertSel(entity);
                        }
                    } else {
                        entity.setId(idTime);
                        entity.setCreater(username);
                        entity.setCreateTime(nowTime);
                        entity.setEffective(1);
                        //插入记录
                        bol = emrPictureService.insertSel(entity);
                    }

                    if (bol == 1) {
                        //文件成功上传到指定目录下
                        file.transferTo(new File(path));

                        result = entity.getMaxPicture();
                    } else {
                        result = "保存文件信息失败!";
                    }

                } else {
                    result = "文件类型有误,请重新上传!";
                }
            } else {
                result = "文件类型为空!";
            }
        } else {
            result = "没有找到相对应的文件!";
        }
        return result;
    }


    /**
     * Pdf上传
     *
     * @param resp
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadPdf", method = RequestMethod.POST)
    public String uploadPdf(HttpServletResponse resp, HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        resp.setContentType("text/json");
        resp.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String firstFile = request.getParameter("fileName");
        String id = request.getParameter("id");
        String masterID = request.getParameter("masterID");
        String assortID = request.getParameter("assortID");
        String result = "";
        if (!file.isEmpty()) {
            // 成功获取照片原名字
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            //logger.info("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                if ("PDF".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    realPath = realPath.split("target")[0] + pictureUrl;
                    // 自定义的文件名称String.valueOf(System.currentTimeMillis())
                    String trueFileName = firstFile + fileName;
                    // 设置存放图片文件的路径
                    path = realPath + "\\static\\img\\uploads\\" + trueFileName;
                    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String nowTime = format1.format(new Date());
                    //将其路径及文件名类型以及参数保存图片相关信息到分段详细表
                    Archive_Detail entity = new Archive_Detail();
                    entity.setMasterid(masterID);
                    entity.setAssortid(assortID);
                    entity.setUploaddatetime(nowTime);
                    entity.setPdfPath("../static/img/uploads/" + trueFileName);
                    Archive_Detail detail = new Archive_Detail();
                    int bol = 0;
                    if (id != null && id != "") {
                        entity.setId(id);
                        detail = archiveDetailService.selectByid(id);
                        if (detail != null) {

                            //根据id修改记录
                            bol = archiveDetailService.updateCloById(entity);
                        }

                    } else {
                        //插入记录
                        bol = archiveDetailService.insertSel(entity);
                    }

                    if (bol == 1) {
                        //将之前文件删除
                        File file1 = new File(realPath + "/static/uploads/" + detail.getPdfPath().split("/")[3]);
                        if (file1.exists() && file1.isFile()) {
                            file1.delete();
                        }
                        file.transferTo(new File(path));
                        //文件成功上传到指定目录下
                        result = entity.toString();
                    } else {
                        result = "保存文件信息失败!";
                    }

                } else {
                    result = "文件类型有误,请重新上传!";
                }
            } else {
                result = "文件类型为空!";
            }
        } else {
            result = "没有找到相对应的文件!";
        }
        return result;
    }


    /**
     * 绝对路径Pdf上传 :路径：pdfUrl
     *
     * @param resp
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @Transactional
    @RequestMapping(value = "/uploadPdf2", method = RequestMethod.POST)
    public String uploadPdf2(HttpServletResponse resp, HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        resp.setContentType("text/json");
        resp.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String firstFile = request.getParameter("fileName");
        String id = request.getParameter("id");
        String masterID = request.getParameter("masterID");
        String assortID = request.getParameter("assortID");
        String title = request.getParameter("title");
        String source = request.getParameter("source");
        String flag = request.getParameter("flag");
        String sys = request.getParameter("sys");

        String result = "";
        String path = null;
        String type = null;
        String oldName = "";

        // 成功获取原名字
        String fileName = null;
        //type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
        //System.out.println("图片初始名称为：" + fileName + " 类型为：" + type);
        path = pdfUrl + "\\" + masterID + "\\" + assortID + "\\";
        //判断目录是否存在，不存在则创建目录
        File fileE = new File(path);
        if (!fileE.exists()) { //用来测试此路径名表示的文件或目录是否存在
            fileE.isDirectory(); //来判断这是不是一个文件夹。

            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdirs();//创建目录
                //System.out.println("测试文件夹不存在");
            }
        }
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = format1.format(new Date());
        //将其路径及文件名类型以及参数保存图片相关信息到分段详细表
        Archive_Detail entity = new Archive_Detail();
        entity.setMasterid(masterID);
        entity.setAssortid(assortID);
        entity.setUploaddatetime(nowTime);
        if (file != null) {
            fileName = format2.format(new Date()) + file.getOriginalFilename();
            entity.setPdfPath(path.replace("\\\\", "\\") + fileName);
        }
        entity.setTitle(title);
        entity.setFlag(flag);
        entity.setSource(source);
        //"emr_medical_record"
        entity.setSys(sys);

        Archive_Detail detail = new Archive_Detail();
        int bol = 0;
        //PDF文件操作
        if (!id.equals("")) {
            entity.setId(id);
            detail = archiveDetailService.selectByid(id);
            if (detail != null) {
                //判断类型是否变更
                if (assortID.equals(detail.getAssortid())) {
                    //相同
                } else {
                    //判断file是否为空
                    if (file == null) {
                        if (detail.getPdfPath() != null) {
                            String newFileName = (detail.getPdfPath()).substring((detail.getPdfPath()).lastIndexOf("\\") + 1);
                            entity.setPdfPath(path.replace("\\\\", "\\") + newFileName);
                            //不同pdf转移在删除
                            PrintToPdfUtil.copyFile(detail.getPdfPath(), entity.getPdfPath());
                        }
                    }
                }
                //根据id修改记录
                bol = archiveDetailService.updateCloById(entity);

            }
        } else {
            //插入记录
            if (file != null) {
                bol = archiveDetailService.insertSel(entity);
            } else {
                result = "没有找到相对应的文件!";
            }
        }
        if (file != null) {
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;

            if (type != null) {
                if ("PDF".equals(type.toUpperCase())) {
                    if (bol == 1) {
                        //将之前文件删除
                        if (detail.getId() != null) {
                            File file2 = new File(detail.getPdfPath());
                            if (file2.exists() && file2.isFile()) {
                                file2.delete();
                            }
                        }
                        file.transferTo(new File(path + fileName));
                        //文件成功上传到指定目录下
                        result = entity.toString();
                    } else {
                        result = "保存文件信息失败!";
                    }

                } else {
                    result = "文件类型有误,请重新上传!";
                }
            } else {
                result = "文件类型为空!";
            }
        } else {
            result = "没有找到相对应的文件!";
        }

        return result;
    }

//    @RequestMapping(value = "/pdfStream", method = RequestMethod.POST, params = "pdfStreamHandeler")
//    @ResponseBody
//    public void pdfStreamHandeler(@RequestParam("fileUrl") String fileUrl, HttpServletRequest request, HttpServletResponse response) {
//        if (StringUtil.isNotEmpty(fileUrl)) {
//            File file = new File(fileUrl);
//            byte[] data = null;
//            try {
//                FileInputStream input = new FileInputStream(file);
//                data = new byte[input.available()];
//                input.read(data);
//                response.getOutputStream().write(data);
//                input.close();
//            } catch (Exception e) {
//                System.out.println("pdf文件处理异常：" + e.getMessage());
//            }
//        }
//    }

    @RequestMapping(value = "/pdfStreamHandeler")
    public void pdfStreamHandeler(HttpServletRequest request, HttpServletResponse response) {
        String filePath = request.getParameter("url");
        //titleName为前端页面title显示的患者姓名，这里要去掉
        String[] list=filePath.split("titleName=");
        if(list.length>1){
            String path=list[0].substring(0,list[0].length()-1);
            filePath=list[0].substring(0,list[0].length()-1);
        }
        File file = new File(filePath);
        byte[] data = null;
        try {
            // 解决请求头跨域问题（IE兼容性  也可使用该方法）
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/pdf");
            FileInputStream input = new FileInputStream(file);
            data = new byte[input.available()];
            input.read(data);
            response.getOutputStream().write(data);
            input.close();
        } catch (Exception e) {
        }
    }


    @RequestMapping("getImg2")
    public void getImg2(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(path);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("insertLog")
    public void insertLog(HttpServletRequest request, HttpServletResponse response, Emr_Log logBo) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();//获取前面登录的用户名
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = format1.format(new Date());
        logBo.setCreateDate(nowTime);
        logBo.setCreater(username);
        //日志实体对象
        logBo.setSysFlag("EMR_Medical_Record");
        String idStr = logBo.getLogContent();
        logBo.setIp("10.10.01.1");

        if (idStr != null && idStr != "") {
            if (idStr.indexOf(",") != -1) {
                String[] idArr = idStr.split(",");
                for (int i = 0; i < idArr.length; i++) {
                    logBo.setLogTitle(idArr[i]);
                    logBo.setLogContent("调用手动作废.");
                    // 添加到数据库
                    logService.insert(logBo);
                }
            } else {
                logBo.setLogTitle(idStr);
                logBo.setLogContent("调用单手动作废.");
                // 添加到数据库
                logService.insert(logBo);
            }
        }

    }

    @ResponseBody
    @RequestMapping(value = "/delPdfPage")
    public int delPdfPage(HttpServletResponse response, HttpServletRequest request, Archive_Detail archiveDetail) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();//获取前面登录的用户名
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = format2.format(new Date());
        int pageNum = Integer.parseInt(archiveDetail.getTitle());
        int pageNum2 = 0;
        if (archiveDetail.getSys() != null && archiveDetail.getSys() != "") {
            pageNum2 = Integer.parseInt(archiveDetail.getSys());
        }
        int bol = 1;
        File file = new File(archiveDetail.getPdfPath());

        PdfReader pdfReader = new PdfReader(new FileInputStream(file));
        int pages = pdfReader.getNumberOfPages();
        // 项目在容器中实际发布运行的根路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        // 设置存放图片文件的路径
        String pdfDelPicUrl = realPath + "static\\img\\delPicImg\\";
        // System.out.println("pdf文件的总页数为:" + pages);

        if (pages != 1) {
            if ((pages >= pageNum && pageNum2 == 0) || (pages > ((pageNum2 - pageNum) + 1) && (pageNum2 != 0 && pages >= pageNum2))) {
                if (file.exists()) {
                    if (bol == 1) {
                        //判断是否有备份如果没有则备份pdf文件
                        Archive_Detail archiveDetail2 = archiveDetailService.selectByid(archiveDetail.getId());
                        if (archiveDetail2 != null) {
                            if (archiveDetail2.getRecoverPdfPath() == null|| archiveDetail2.getRecoverPdfPath() == "") {
                                //备份pdf文件复印并将记录保存
                                String recoverPdfPath = archiveDetail2.getPdfPath().replace(file.getName(), "") + nowTime + ".pdf";
                                archiveDetail2.setRecoverPdfPath(recoverPdfPath);
                                archiveDetailService.updateCloById(archiveDetail2);
                                //复印pdf备份
                                PrintToPdfUtil.copyFile2(archiveDetail2.getPdfPath(), recoverPdfPath);
                            }
                        }
                        List arrL = new ArrayList();
                        // bol = pdfDelPageTest.cutPdf(archiveDetail.getPdfPath(), archiveDetail.getPdfPath(), pageNum);//删除第n页
                        String pdfPath = archiveDetail.getPdfPath();
                        List<Map<String, String>> list = PrintToPdfUtil.pdfToImage(archiveDetail.getPdfPath(), pageNum, pageNum2, pdfDelPicUrl);
                        nowTime = format1.format(new Date());
                        //删除pdf页码成功，保存记录到数据库删除图片表中
                        Archive_Detail_Picture archiveDetailPicture = new Archive_Detail_Picture();
                        archiveDetailPicture.setCreater(username);
                        archiveDetailPicture.setCreateTime(nowTime);
                        archiveDetailPicture.setUpdateTime(nowTime);
                        archiveDetailPicture.setUpdater(username);
                        archiveDetailPicture.setEffective(1);
                        archiveDetailPicture.setParentId(archiveDetail.getId());
                        if (list.size() > 0) {
                            for (Map<String, String> map : list) {
                                if (map.get("max_picture") != null && map.get("max_picture") != "") {
                                    if (map.get("max_picture").indexOf("static") != -1) {
                                        String[] maxPicArr = map.get("max_picture").trim().split("static");
                                        String maxPic = maxPicArr[1];
                                        archiveDetailPicture.setMaxPicture("static" + maxPic);
                                    }
                                }
                                if (arrL.indexOf(archiveDetailPicture.getMaxPicture()) == -1) {
                                    arrL.add(archiveDetailPicture.getMaxPicture());
                                    archiveDetailPicture.setPictureNumber(Integer.parseInt(map.get("picture_number")));
                                    archiveDetailPictureService.insertSelective(archiveDetailPicture);
                                }
                            }

                        } else {
                            bol = 0;
                        }
                    } else {
                        //备份失败
                        bol = 4;
                    }
                } else {
                    //pdf文件不存在
                    bol = 2;
                }
            } else {
                //删除页码大于总页数
                bol = 3;
            }
        } else {
            bol = 5;
        }
        return bol;
    }

    //@OptionalLog(methods = "查询相关的页码图片列表")
    @ResponseBody
    @RequestMapping(value = "/selDelPicList")
    public List<Archive_Detail_Picture> selDelPicList(HttpServletRequest request, HttpServletResponse response, Archive_Detail_Picture archiveDetailPicture) {
        List<Archive_Detail_Picture> list = archiveDetailPictureService.selectByCol(archiveDetailPicture);
        return list;
    }

    //@OptionalLog(methods = "删除所有页码图片")
    @ResponseBody
    @RequestMapping(value = "/delPageImgAll")
    public int delPageImgAll(HttpServletRequest request, HttpServletResponse response, Archive_Detail_Picture archiveDetailPicture) {
        int bol = 0;
        String fileDirName = archiveDetailPicture.getMaxPicture();
        archiveDetailPicture.setMaxPicture(null);
        bol = archiveDetailPictureService.deleteByCol(archiveDetailPicture);
        if (bol == 1) {
            // 项目在容器中实际发布运行的根路径
            String realPath = request.getSession().getServletContext().getRealPath("/");
            // 设置存放图片文件的路径
            String pdfDelPicUrl = "static\\img\\delPicImg\\";
            //将之前文件目录下图片删除
            File file = new File(realPath + pdfDelPicUrl + fileDirName + "\\");
            PrintToPdfUtil.delete(file);
        }

        return bol;
    }

    //@OptionalLog(methods = "删除单张页码图片")
    @ResponseBody
    @RequestMapping(value = "/delPageImg")
    public int delPageImg(HttpServletRequest request, HttpServletResponse response, Archive_Detail_Picture archiveDetailPicture) {
        int bol = 0;
        bol = archiveDetailPictureService.deleteByCol(archiveDetailPicture);
        if (bol == 1) {
            // 项目在容器中实际发布运行的根路径
            String realPath = request.getSession().getServletContext().getRealPath("/");
            //将之前图片文件删除
            File file = new File(realPath + archiveDetailPicture.getMaxPicture());
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        }

        return bol;
    }

    //@OptionalLog(methods = "PDF文件添加页码")
    @ResponseBody
    @RequestMapping(value = "/addPdfPageBtn")
    public int addPdfPageBtn(HttpServletRequest request, HttpServletResponse response, Archive_Detail_Picture archiveDetailPicture) {
        String orgPdfPath = archiveDetailPicture.getMaxPicture();
        File file = new File(orgPdfPath);
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = format2.format(new Date());
        String filePath = file.getAbsolutePath().replace(file.getName(), "");
        String fileName = nowTime + "_" + file.getName();
        filePath += fileName;
        File file1 = new File(filePath);
        file.renameTo(file1);
        String result = PrintToPdfUtil.addPageNum(filePath, orgPdfPath);
        if (result != "" && result != null) {
            file1.deleteOnExit();
        }
        return 1;
    }

    //@OptionalLog(methods = "PDF文件还原页码")
    @ResponseBody
    @RequestMapping(value = "/returnPage")
    public String returnPage(HttpServletRequest request, HttpServletResponse response, Archive_Detail_Picture archiveDetailPicture) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime2 = format2.format(new Date());
        String result = "";
        int bol = 0;
        // 模板文件路径
        String templatePath = (archiveDetailPicture.getMinPicture());
        // 生成的文件路径
        String targetPath = archiveDetailPicture.getMinPicture();
        String realPath = request.getSession().getServletContext().getRealPath("/");
        // 图片路径
        String imagePath = realPath + archiveDetailPicture.getMaxPicture();
        // 页数
        int pageNum = archiveDetailPicture.getPictureNumber();
        File file = new File(templatePath);
        if(file.exists()) {

            //备份pdf文件
            //判断是否有备份如果没有则备份pdf文件
            Archive_Detail archiveDetail =archiveDetailService.selectByid(archiveDetailPicture.getParentId());
            if(archiveDetail!=null){
                String fileDirName = archiveDetail.getPdfPath();
                fileDirName = fileDirName.substring(fileDirName.lastIndexOf("\\") + 1).replace(".pdf", "");
                if (archiveDetail.getRecoverPdfPath() == null || archiveDetail.getRecoverPdfPath() == "") {
                    //备份pdf文件复印并将记录保存
                    String recoverPdfPath = archiveDetail.getPdfPath().replace(file.getName(), "") +  nowTime2 + ".pdf";
                    archiveDetail.setRecoverPdfPath(recoverPdfPath);
                    archiveDetailService.updateCloById(archiveDetail);
                    //复印pdf备份
                    PrintToPdfUtil.copyFile2(archiveDetail.getPdfPath(), recoverPdfPath);
                }
            }

            PdfReader pdfReader = new PdfReader(new FileInputStream(file));
            int pages = pdfReader.getNumberOfPages();
            if (pages >= 1) {
                if ((pages) >= pageNum) {
                    if (file.exists() && file.isFile()) {
                        result = AddImgToPdf.addImgToPdf(templatePath, targetPath, imagePath, pageNum);
                        if (result != "文件不存在") {
                            archiveDetailPicture.setMaxPicture(null);
                            archiveDetailPicture.setMinPicture(null);
                            archiveDetailPicture.setPictureNumber(null);
                            //删除记录
                            bol = archiveDetailPictureService.deleteByCol(archiveDetailPicture);
                            if (bol == 1) {
                               // file.delete();
                                //将之前文件删除
                                File file1 = new File(imagePath);
                                if (file1.exists() && file1.isFile()) {
                                    file1.delete();
                                }
                            }
                            result = "图片还原到" + pageNum + "页成功!";
                        } else {
                            result = "图片还原失败!";
                        }
                    }
                } else {
                    result = "图片还原" + pageNum + "要小于等于" + pages + "!";
                }
            } else {
                result = "pdf文件无内容!";
            }
        }else{
            result = "pdf文件不存在!";
        }
        return result;
    }

   //@OptionalLog(methods = "PDF文件还原最初")
    @ResponseBody
    @RequestMapping(value = "/returnPdfFile")
    public String returnPdfFile(HttpServletRequest request, HttpServletResponse response, Archive_Detail archiveDetail) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String result="";
        //判断是否有备份如果没有则备份pdf文件
        archiveDetail = archiveDetailService.selectByid(archiveDetail.getId());
        if(archiveDetail!=null){
            if(archiveDetail.getPdfPath()!="" && archiveDetail.getPdfPath()!=null && archiveDetail.getRecoverPdfPath()!="" && archiveDetail.getRecoverPdfPath()!=null){
                File file2=new File(archiveDetail.getPdfPath());
                if(file2.exists()) {
                    PrintToPdfUtil.copyFile2(archiveDetail.getRecoverPdfPath(), archiveDetail.getPdfPath());
                    //并删除图片记录
                    Archive_Detail_Picture archiveDetailPicture = new Archive_Detail_Picture();
                    archiveDetailPicture.setParentId(archiveDetail.getId());
                    String fileDirName = archiveDetail.getPdfPath();
                    fileDirName = fileDirName.substring(fileDirName.lastIndexOf("\\") + 1).replace(".pdf", "");
                    int bol = archiveDetailPictureService.deleteByCol(archiveDetailPicture);
                    if (bol == 1) {
                        // 项目在容器中实际发布运行的根路径
                        String realPath = request.getSession().getServletContext().getRealPath("/");
                        // 设置存放图片文件的路径
                        String pdfDelPicUrl = "static\\img\\delPicImg\\";
                        //将之前文件目录下图片删除
                        File file = new File(realPath + pdfDelPicUrl + fileDirName + "\\");
                        PrintToPdfUtil.delete(file);
                    }
                }else{
                    result="pdf文件不存在，所以不可备份!";
                }
            }else{
                result="暂无备份pdf文件!";
            }
        }
        return result;
    }

    //@OptionalLog(methods = "PDF文件重新备份")
    @ResponseBody
    @RequestMapping(value = "/bfPdfFile")
    public String bfPdfFile(HttpServletRequest request, HttpServletResponse response, Archive_Detail archiveDetail) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String result="";
        //判断是否有备份如果没有则备份pdf文件
        archiveDetail = archiveDetailService.selectByid(archiveDetail.getId());
        if(archiveDetail!=null){
            if(archiveDetail.getPdfPath()!="" && archiveDetail.getPdfPath()!=null && archiveDetail.getRecoverPdfPath()!="" && archiveDetail.getRecoverPdfPath()!=null){
                File file2=new File(archiveDetail.getPdfPath());
                if(file2.exists()) {
                    PrintToPdfUtil.copyFile2(archiveDetail.getPdfPath(), archiveDetail.getRecoverPdfPath());
                    //并删除图片记录
                    Archive_Detail_Picture archiveDetailPicture = new Archive_Detail_Picture();
                    archiveDetailPicture.setParentId(archiveDetail.getId());
                    String fileDirName = archiveDetail.getPdfPath();
                    fileDirName = fileDirName.substring(fileDirName.lastIndexOf("\\") + 1).replace(".pdf", "");
                    int bol = archiveDetailPictureService.deleteByCol(archiveDetailPicture);
                    if (bol == 1) {
                        // 项目在容器中实际发布运行的根路径
                        String realPath = request.getSession().getServletContext().getRealPath("/");
                        // 设置存放图片文件的路径
                        String pdfDelPicUrl = "static\\img\\delPicImg\\";
                        //将之前文件目录下图片删除
                        File file = new File(realPath + pdfDelPicUrl + fileDirName + "\\");
                        PrintToPdfUtil.delete(file);
                    }
                    result = "重新备份pdf文件成功!";
                }else{
                    result="pdf文件不存在，所以不可备份!";
                }
            }else{
                result="暂无备份pdf文件!";
            }
        }
        return result;
    }

    /**
     * 删除页批量图片上传
     *
     * @param resp
     * @param request
     * @param
     * @return
     * @throws IOException
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/uploadDelPageImgS", method = RequestMethod.POST)
    public String uploadDelPageImgS(HttpServletResponse resp, HttpServletRequest request, @RequestParam MultipartFile[] imgs) throws Exception {
        resp.setContentType("text/json");
        resp.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();//获取前面登录的用户名
        String parentId = request.getParameter("parentId");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = format1.format(new Date());
        String nowTime2 = format2.format(new Date());
        // 项目在容器中实际发布运行的根路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        // 设置存放删除页图片路径
        String path2 = "static\\img\\delPicImg\\";
        String result="";
        int bol=0;

        if (parentId != null && parentId != "") {
            //判断是否有备份如果没有则备份pdf文件
            Archive_Detail archiveDetail = archiveDetailService.selectByid(parentId);
            if(archiveDetail!=null) {
                File file = new File(archiveDetail.getPdfPath());
                if(file.exists()) {
                    String fileDirName = archiveDetail.getPdfPath();
                    fileDirName = fileDirName.substring(fileDirName.lastIndexOf("\\") + 1).replace(".pdf", "");
                    if (archiveDetail.getRecoverPdfPath() == null || archiveDetail.getRecoverPdfPath() == "") {
                        //备份pdf文件复印并将记录保存
                        String recoverPdfPath = archiveDetail.getPdfPath().replace(file.getName(), "") +  nowTime2 + ".pdf";
                        archiveDetail.setRecoverPdfPath(recoverPdfPath);
                        archiveDetailService.updateCloById(archiveDetail);
                        //复印pdf备份
                        PrintToPdfUtil.copyFile2(archiveDetail.getPdfPath(), recoverPdfPath);
                    }
                    //类循环
                    if (imgs != null && imgs.length > 0) {
                        Archive_Detail_Picture archiveDetailPicture = new Archive_Detail_Picture();
                        archiveDetailPicture.setParentId(parentId);
                        archiveDetailPicture.setPictureNumber(1);
                        archiveDetailPicture.setEffective(1);
                        archiveDetailPicture.setCreater(username);
                        archiveDetailPicture.setCreateTime(nowTime);
                        archiveDetailPicture.setUpdater(username);
                        archiveDetailPicture.setUpdateTime(nowTime);
                        archiveDetailPicture.setRemark("额外上传的图片");
                        String oldName = "";// 如apple1.jpg
                        String lasName = "";
                        String trueFileName = "";
                        String imgPath = "";
                        for (int t = 0; t < imgs.length; t++) {
                            //得到图片名
                            oldName = imgs[t].getOriginalFilename();// 如apple1.jpg
                            lasName = oldName.substring(oldName.lastIndexOf(".") + 1);
                            // 自定义的文件名称String.valueOf(System.currentTimeMillis())
                            trueFileName = nowTime2+System.currentTimeMillis() + oldName;
                            if ("GIF".equals(lasName.toUpperCase()) || "JPEG".equals(lasName.toUpperCase()) || "PNG".equals(lasName.toUpperCase()) || "JPG".equals(lasName.toUpperCase())) {
                                File fileDir = new File(realPath + path2 + fileDirName + "\\");
                                if (!fileDir.exists() && !fileDir.isDirectory()) {
                                    fileDir.mkdirs();
                                }
                                imgPath = path2 + fileDirName + "\\" + trueFileName;
                                //上传图片
                                imgs[t].transferTo(new File(realPath + imgPath));
                                archiveDetailPicture.setMaxPicture(imgPath);
                                //插入记录
                                bol = archiveDetailPictureService.insertSelective(archiveDetailPicture);
                                if (bol == 1) {
                                    result = "上传图片成功!";
                                } else {
                                    result = "上传图片失败!";
                                }
                            }
                        }

                    } else {
                        result = "上传图片不为空!";
                    }
                }else{
                    result = "pdf文件不存在或破损!";
                }
            } else {
                result = "记录不存在!";
            }
        }else{
            result="记录不存在!";
        }

        return result;
    }

}
 

