package com.emr.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emr.dao.Archive_DetailMapper;
import com.emr.dao.CommomMapper;
import com.emr.dao.emrPdfWaterSet.EmrPdfWaterSetMapper;
import com.emr.entity.EmrComomSet;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.emr.entity.tScanAssort.T_Scan_Assort;
import com.emr.service.tScanAssort.T_Scan_AssortService;
import com.emr.util.Jpg2PdfUtil;
import com.emr.util.img2PdfUtil;
import com.emr.vo.User;
import com.emr.vo.commomSearch.CommomTree;
import com.emr.vo.commomSearch.CommomVo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/11/7 14:50
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/11/7 14:50
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Component
public class CommomService {
    //定义打印预览加载进度map
    private static Map<String, Integer> printLoadingMap = new HashMap<>();
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;
    @Value("${waterPicPath}")
    private String WATERPICPATH;
    @Value("${EMR_RECORD_JSP}")
    private String EMRRECORDJSP;
    @Value("${waterTifToJpgPath}")
    private String WATERTIFTOJPGPATH;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private CommomSetService commomSetService;
    @Autowired
    private T_Scan_AssortService scanAssortService;
    @Autowired
    private EmrPdfWaterSetMapper pdfWaterSetMapper;
    @Autowired
    private Archive_DetailMapper archiveDetailMapper;
    public static final Map<String, Object> CACHE_MAP = new ConcurrentHashMap<>();

    //获取所属医院用户名集合
    public static StringBuilder creaters(HttpServletRequest request) {
        List<User> userList = (List<User>) request.getSession().getAttribute("USER_LIST");
        StringBuilder creaters = new StringBuilder();
        for (int i = 0; i < userList.size(); i++) {
            if (userList.get(i).getRoleId() != 0) {
                creaters.append("'" + userList.get(i).getUserName() + "',");
            }
        }
        if (StringUtils.isNotBlank(creaters)) {
            creaters = new StringBuilder(creaters.substring(0, creaters.length() - 1));
        }
        return creaters;
    }

    //获取所属医院用户id
    public static String userIds(HttpServletRequest request) {
        List<User> userList = (List<User>) request.getSession().getAttribute("USER_LIST");
        StringBuilder userIds = new StringBuilder();
        for (User user : userList) {
            if (user.getRoleId() != 0) {
                userIds.append("'").append(user.getUserId()).append("',");
            }
        }
        if (StringUtils.isNotBlank(userIds)) {
            userIds = new StringBuilder(userIds.substring(0, userIds.length() - 1));
        }
        return userIds.toString();
    }

    /**
     * 获取所属医院下所有用户不包括admin
     *
     * @param userName
     * @param request
     * @return
     */
    public List<User> getUserList(String userName, HttpServletRequest request) throws Exception {
        List<User> userList = new ArrayList<>();
        //查询缓存时候存在
        //调用接口查询
        String resultString = "";
        // 创建uri
        String url = POWER_URLHEAD + "/font/getUserList?userName=" + userName;
        // 执行请求
        CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpGet(url));
        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        if (StringUtils.isNoneBlank(resultString)) {
            JSONObject jsonObject = JSON.parseObject(resultString);
            String extend = jsonObject.getString("extend");
            JSONObject extendObject = JSONObject.parseObject(extend);
            String userList1 = extendObject.getString("userList");
            userList = (List<User>) JSON.parseArray(userList1, User.class);
        }
        //设置进session
        request.getSession().setAttribute("USER_LIST", userList);
        return userList;
    }

    /**
     * 病案预览页面新增图片
     *
     * @param files
     * @param patientId
     * @param assortId
     * @return
     * @throws Exception
     */
    public ResultUtil updatePic(MultipartFile[] files, String patientId, String assortId) throws Exception {
        if (null != files) {
            //查询目录
            CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
            ResultUtil resultUtil = selectRootPath(patientId, commomVo.getInpatientNo());
            if (resultUtil.getCode().equals(0)) {
                String path = resultUtil.getMsg().replaceAll(" ", "");
                commomVo.setNewPath(commomVo.getFilePath());
                commomMapper.updateByPrimaryKeySelective(commomVo);
                List<MultipartFile> fileList = CollectionUtils.arrayToList(files);
                //定义批量添加进图片明细表集合
                SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
                Date date = new Date(System.currentTimeMillis());
                String format = fmt1.format(date);
                List<T_Scan_Assort> insertList = getScanAssortListByUpdatePic2(fileList, patientId, assortId, path, format);
                //批量新增图片记录
                scanAssortService.SimpleInsert(insertList);
                return ResultUtil.ok();
            } else {
                return resultUtil;
            }
        }
        return null;
    }

    public String getOperIp() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取访问真实IP
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                assert inet != null;
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    //脐血库显示pdf
    public void showRecordContentBloodFont(String patientId, String scanPages, String sources, String flag, HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (StringUtils.isNotBlank(patientId)) {
            patientId = patientId.replace("\'", "");
            //查询
            if (StringUtils.isNotBlank(flag)) {
                CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
                if (commomVo != null) {
                    String filePath = commomVo.getFilePath();
                    if (StringUtils.isNotBlank(filePath)) {
                        //flag = home_addr取home_addr字段，path_file取home_addr字段
                        String root1 = "";
                        if ("home_addr".equals(flag)) {
                            root1 = commomVo.getHomeAddr();
                        } else if ("file_path".equals(flag)) {
                            root1 = commomVo.getFilePath();
                        }
                        //组织src
                        List<String> src = new LinkedList<>();
                        String[] scanPageArr = scanPages.split(",");
                        for (int i = 0; i < scanPageArr.length; i++) {
                            String srcStr = "";
                            if (StringUtils.isNotBlank(scanPageArr[i])) {
                                srcStr = root1 + File.separator + scanPageArr[i];
                            }
                            src.add(srcStr);
                        }
                        List<String> filePaths = new LinkedList<>();
                        for (String srcs : src) {
                            File file = new File(srcs);
                            if (file.isFile()) {
                                filePaths.add(srcs);
                            }
                        }
                        if (!filePaths.isEmpty()) {
                            String mapKey = "admin" + "_" + patientId;
                            CACHE_MAP.put(mapKey, filePaths);
                        }
                    }
                } else {
                    List<String> commomTrees = archiveDetailMapper.getPDFRATH(patientId, scanPages);
                    if (!commomTrees.isEmpty()) {
                        String mapKey = "admin" + "_" + patientId;
                        CACHE_MAP.put(mapKey, commomTrees);

                    }
                }
            }
        }
    }


    //脐血库显示pdf
    public void showRecordContentBlood(String patientId, String scanPages, String sources, String flag, HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (StringUtils.isNotBlank(patientId)) {
            patientId = patientId.replace("\'", "");
            //查询
            if (StringUtils.isNotBlank(flag)) {
                CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
                if (StringUtils.isNotBlank(commomVo.getFilePath())) {
                    //flag = home_addr取home_addr字段，path_file取home_addr字段
                    String root1 = "";
                    if ("home_addr".equals(flag)) {
                        root1 = commomVo.getHomeAddr();
                    } else if ("file_path".equals(flag)) {
                        root1 = commomVo.getFilePath();
                    }
                    //组织src
                    List<String> src = new LinkedList<>();
                    String[] scanPageArr = scanPages.split(",");
                    for (int i = 0; i < scanPageArr.length; i++) {
                        String srcStr = "";
                        if (StringUtils.isNotBlank(scanPageArr[i])) {
                            srcStr = root1 + File.separator + scanPageArr[i];
                        }
                        src.add(srcStr);
                    }
                    List<String> filePaths = new LinkedList<>();
                    for (String srcs : src) {
                        File file = new File(srcs);
                        if (file.isFile()) {
                            filePaths.add(srcs);
                        }
                    }
                    if (!filePaths.isEmpty()) {
                        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                        String mapKey = user.getUserName() + "_" + patientId;
                        request.getSession().setAttribute(mapKey, filePaths);
                    }
                } else {
                    List<String> commomTrees = archiveDetailMapper.getPDFRATH(patientId, scanPages);
                    if (!commomTrees.isEmpty()) {
                        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                        String mapKey = user.getUserName() + "_" + patientId;
                        request.getSession().setAttribute(mapKey, commomTrees);
                    }
                }
            }
        }
    }

    /**
     * @Description: getEmrPdfWaterSet方法是定义第二文本水印 姓名 + 科室 + ip
     * @param: [emrPdfWaterSet]
     * @return: com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet
     * @author 曾文和
     * @createTime 2022/7/26 1:15
     */

    public EmrPdfWaterSet getEmrPdfWaterSet(EmrPdfWaterSet emrPdfWaterSet) {
        EmrPdfWaterSet emrPdfWaterSet1 = new EmrPdfWaterSet();
        BeanUtils.copyProperties(emrPdfWaterSet, emrPdfWaterSet1);
        //定义第二水印文本
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取reuqest
        HttpServletRequest request = attributes.getRequest();
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String text = "";
        if (StringUtils.isNotBlank(user.getUserName())) {
            text += " " + user.getUserName();
        }
        if (StringUtils.isNotBlank(user.getUserPosition())) {
            text = text + " " + user.getUserPosition();
        }
        text += " " + getOperIp();
        emrPdfWaterSet1.setText(text);
        return emrPdfWaterSet1;
    }

    //南方医院显示图像
    public void showRecordContentSouth(String patientId, String userName, String deptName, String scanPages, String sources, String flag, HttpServletResponse response) throws Exception {
        String pdfName = "档案管理PDF";
        if (StringUtils.isNotBlank(patientId)) {
            patientId = patientId.replace("\'", "");
            //查询
            if (StringUtils.isNotBlank(flag)) {
                CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
                //flag = home_addr取home_addr字段，path_file取home_addr字段
                String root1 = "";
                if ("home_addr".equals(flag)) {
                    root1 = commomVo.getHomeAddr();
                } else if ("file_path".equals(flag)) {
                    root1 = commomVo.getFilePath();
                }
                String root2 = commomVo.getNewPath();
                //组织src
                List<String> src = new LinkedList<>();
                String[] scanPageArr = scanPages.split(",");
                String[] sourceArr = sources.split(",");
                for (int i = 0; i < scanPageArr.length; i++) {
                    String srcStr = "";
                    if (StringUtils.isNotBlank(scanPageArr[i])) {
                        if ("1".equals(sourceArr[i])) {
                            srcStr = root1 + File.separator + scanPageArr[i];
                        } else {
                            srcStr = root2 + File.separator + scanPageArr[i];
                        }
                    }
                    src.add(srcStr);
                }
                List<String> filePaths = new LinkedList<>();
                for (String srcs : src) {
                    File file = new File(srcs);
                    if (file.isFile()) {
                        filePaths.add(srcs);
                    }
                }
                if (!filePaths.isEmpty()) {
                    //根据图片路径转换pdf
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                    //定义第二文本水印 姓名 + 科室 + ip
                    EmrPdfWaterSet emrPdfWaterSet1 = getEmrPdfWaterSet(emrPdfWaterSet);
                    img2PdfUtil.imageToPdf(response, filePaths, pdfName, emrPdfWaterSet, emrPdfWaterSet1);
                }
            }
        }
    }

    //接口显示pdf
    public void showRecordContentBloodFont(String patientId, String scanPages, String sources, String flag, String fileOutPath) throws Exception {
        if (StringUtils.isNotBlank(patientId)) {
            patientId = patientId.replace("\'", "");
            //查询
            if (StringUtils.isNotBlank(flag)) {
                CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
                //flag = home_addr取home_addr字段，path_file取home_addr字段
                String root1 = "";
                if ("home_addr".equals(flag)) {
                    root1 = commomVo.getHomeAddr();
                } else if ("file_path".equals(flag)) {
                    root1 = commomVo.getFilePath();
                }
                String root2 = commomVo.getNewPath();
                //组织src
                List<String> src = new LinkedList<>();
                String[] scanPageArr = scanPages.split(",");
                String[] sourceArr = sources.split(",");
                for (int i = 0; i < scanPageArr.length; i++) {
                    String srcStr = "";
                    if (StringUtils.isNotBlank(scanPageArr[i])) {
                        if ("1".equals(sourceArr[i])) {
                            srcStr = root1 + File.separator + scanPageArr[i];
                        } else {
                            srcStr = root2 + File.separator + scanPageArr[i];
                        }
                    }
                    src.add(srcStr);
                }
                List<String> filePaths = new LinkedList<>();
                for (String srcs : src) {
                    File file = new File(srcs);
                    if (file.isFile()) {
                        filePaths.add(srcs);
                    }
                }
                if (!CollectionUtils.isEmpty(filePaths)) {
                    //根据图片路径转换pdf
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                    img2PdfUtil.imageToPdfFont(filePaths, emrPdfWaterSet, fileOutPath);
                }
            }
        }
    }

    //接口显示pdf
    public void showRecordContentSouthFont(String patientId, String userName, String deptName, String scanPages, String sources, String flag, String fileOutPath) throws Exception {
        if (StringUtils.isNotBlank(patientId)) {
            patientId = patientId.replace("\'", "");
            //查询
            if (StringUtils.isNotBlank(flag)) {
                CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
                //flag = home_addr取home_addr字段，path_file取home_addr字段
                String root1 = "";
                if ("home_addr".equals(flag)) {
                    root1 = commomVo.getHomeAddr();
                } else if ("file_path".equals(flag)) {
                    root1 = commomVo.getFilePath();
                }
                String root2 = commomVo.getNewPath();
                //组织src
                List<String> src = new LinkedList<>();
                String[] scanPageArr = scanPages.split(",");
                String[] sourceArr = sources.split(",");
                for (int i = 0; i < scanPageArr.length; i++) {
                    String srcStr = "";
                    if (StringUtils.isNotBlank(scanPageArr[i])) {
                        if ("1".equals(sourceArr[i])) {
                            srcStr = root1 + File.separator + scanPageArr[i];
                        } else {
                            srcStr = root2 + File.separator + scanPageArr[i];
                        }
                    }
                    src.add(srcStr);
                }
                List<String> filePaths = new LinkedList<>();
                for (String srcs : src) {
                    File file = new File(srcs);
                    if (file.isFile()) {
                        filePaths.add(srcs);
                    }
                }
                if (!CollectionUtils.isEmpty(filePaths)) {
                    //根据图片路径转换pdf
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                    InetAddress netAddress = InetAddress.getLocalHost();
                    String ip = null;
                    if (null != netAddress) {
                        ip = netAddress.getHostAddress();
                    }
                    emrPdfWaterSet.setText(userName + " " + ip);
                    img2PdfUtil.imageToPdfFont(filePaths, emrPdfWaterSet, fileOutPath);
                }
            }
        }
    }

    //封装批量上传图片，返回上传图片记录
    private List<T_Scan_Assort> getScanAssortListByUpdatePic(List<MultipartFile> multipartFiles, String patientId, String assortId, String root) throws Exception {
        List<T_Scan_Assort> scanAssorts = new ArrayList<>();
        //遍历分类图片集合
        for (MultipartFile pic : multipartFiles) {
            //定义对象
            T_Scan_Assort scanAssort = new T_Scan_Assort();
            String picName = pic.getOriginalFilename();
            //判断图片名称是否存在，存在重命名
            picName = getPicName(root, picName, pic);
            //组织绝对路径
            String src = root + File.separator + picName;
            //上传图片
            pic.transferTo(new File(src));
            //设置进对象
            scanAssort.setPatientId(patientId);
            scanAssort.setAssortId(assortId);
            scanAssort.setScanPage(picName);
            scanAssort.setSource(Short.valueOf("2"));
            scanAssort.setIsDel(Short.valueOf("0"));
            scanAssorts.add(scanAssort);
        }
        return scanAssorts;
    }


    //封装批量上传图片，返回上传图片记录
    private List<T_Scan_Assort> getScanAssortListByUpdatePic2(List<MultipartFile> multipartFiles, String patientId, String assortId, String root, String format) throws Exception {
        List<T_Scan_Assort> scanAssorts = new ArrayList<>();
        //遍历分类图片集合
        for (MultipartFile pic : multipartFiles) {
            //定义对象
            T_Scan_Assort scanAssort = new T_Scan_Assort();
            String picName = pic.getOriginalFilename();
            //判断图片名称是否存在，存在重命名
            picName = getPicName(root, picName, pic);
            //组织绝对路径
            String src = root + File.separator + picName;
            //上传图片
            pic.transferTo(new File(src));
            //设置进对象
            scanAssort.setPatientId(patientId);
            scanAssort.setAssortId(assortId);
            scanAssort.setScanPage(picName);
            scanAssort.setSource(Short.valueOf("2"));
            scanAssort.setIsDel(Short.valueOf("0"));
            scanAssort.setUpDate(format);
            scanAssorts.add(scanAssort);
        }
        return scanAssorts;
    }


    //封装组织新增图片根目录
    private ResultUtil selectRootPath(String patientId, String inpatientId) {
        //查询设置的根目录
//        EmrComomSet emrComomSet = commomSetService.selectByPrimaryKey(1);
//        String newPicRoot = emrComomSet.getNewPicRoot();
        String filePath = null;
        List<CommomVo> commomVos = commomMapper.selectFilePath(patientId);
        for (CommomVo commomVo : commomVos) {
            filePath = commomVo.getFilePath();
        }

        if (StringUtils.isBlank(filePath)) {
            return ResultUtil.error("目录未设置,请先前往参数设置页面设置图片存在根目录!");
        }
        //组织存放目录
        //D:\新图像\202005\GDZT20120916076-2a41fe252a024978af7098afcf52ca1a
        //格式化年月
//        SimpleDateFormat fmt1 = new SimpleDateFormat("yyyyMM");
//        String path = filePath + File.separator + inpatientId + "-" + patientId;
//        path = path.replaceAll(" ", "");
//        //该目录不存在，创建目录
//        if (!new File(path).isDirectory()) {
//            new File(path).mkdirs();
//        }
        return ResultUtil.ok(filePath);
    }

    //验证图片是否存在，存在重命名
    private String getPicName(String root, String fullName, MultipartFile pic) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String src = root + File.separator + fullName;
        File file = new File(src);
        //判断是否存在，存在文件加日期
        if (file.exists()) {
            //原始名
            String baseName = FilenameUtils.getBaseName(pic.getOriginalFilename());
            //扩展名
            String ext = FilenameUtils.getExtension(pic.getOriginalFilename());
            fullName = baseName + "_" + fmt.format(new Date()) + "." + ext;
        }
        return fullName;
    }

    /**
     * 脐血库、祈福医院打印预览前加载图片
     *
     * @param patientId
     * @param rootPaths
     * @param names
     * @param sources
     * @return
     */
    public List<String> selectPrintPic(HttpServletResponse response, String patientId, String rootPaths, String names, String sources, String mapKey) {
        //获取登录用户信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<String> outs = new LinkedList<>();
        if (StringUtils.isNotBlank(names)) {
            String[] rootPathList = rootPaths.split(",");
            String[] nameList = names.split(",");
            String[] sourceList = sources.split(",");
            //获取水印设置
            EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
            //获取是否打印文本水印
            Short printEffective = emrPdfWaterSet.getPrintEffective();
            //获取是否打印图片水印
            Short printIsImg = emrPdfWaterSet.getPrintIsImg();
            //获取是否打印用户信息
            Short userEffective = emrPdfWaterSet.getUserEffective();
            Integer roleId = user.getRoleId();
            for (int i = 0; i < nameList.length; i++) {
                //定义图片根目录地址
                String rootPath = "";
                String srcPath;
                //组织原图片地址
                if ("1".equals(sourceList[i])) {
                    //扫描图片地址位于rootPathList第一个
                    rootPath = rootPathList[0];
                } else if ("99".equals(sourceList[i])) {
                    rootPath = nameList[0];
                } else {
                    rootPath = rootPathList[1];
                }
                //原图片地址
                if ("99".equals(sourceList[i])) {
                    srcPath = nameList[i];
                } else {
                    srcPath = rootPath + File.separator + nameList[i];
                }
                //定义输出地址
                String outSrc = "";
                //获取项目上下文地址
                if ((printEffective != null && printEffective == 1 ) ||
                        (printIsImg != null && printIsImg == 1) ) {
                    if ("99".equals(sourceList[i])) {
                        String rootSrcPath = selectRootByNotWater(srcPath);
                        String str2 = srcPath.substring(0, srcPath.indexOf(File.separator));
                        String picPath2 = srcPath.substring(str2.length() + 1, srcPath.length());
                        outSrc = EMRRECORDJSP + File.separator + rootSrcPath + picPath2;
                    } else {
                        //需要水印
                        //组织加水印后图片存放目录
                        String waterPicRoot = WATERPICPATH + patientId + File.separator + sourceList[i] + File.separator;
                        //目录不存在则创建
                        if (!new File(waterPicRoot).isDirectory()) {
                            new File(waterPicRoot).mkdirs();
                        }
                        //组织加水印后图片存放地址
                        String waterPicPath = waterPicRoot + nameList[i];
                        if (!new File(waterPicPath).exists()) {
                            //定义第二文本水印 姓名 + 科室 + ip
                            EmrPdfWaterSet emrPdfWaterSet1 = getEmrPdfWaterSet(emrPdfWaterSet);
                            if (userEffective == 1) {
                                img2PdfUtil.addWatermarkPic1(new File(srcPath), emrPdfWaterSet, waterPicPath, emrPdfWaterSet1);
                            } else {
                                img2PdfUtil.addWatermarkPic2(new File(srcPath), emrPdfWaterSet, waterPicPath);
                            }
                        }
                        //组织输出地址
                        String root = selectRootByNotWater(WATERPICPATH);
                        outSrc = EMRRECORDJSP + File.separator + root + "/jiashi/reload/" + patientId + File.separator + sourceList[i] + File.separator + nameList[i];
                    }
                } else {
                    //不需要水印
                    String root = "";
                    String picPath = "";
                    //判断是否是tif图片
                    boolean tifFileFlag = checkTifFile(srcPath);
                    if (tifFileFlag) {
                        //保存目录不存在新增
                        if (!new File(WATERTIFTOJPGPATH).isDirectory()) {
                            new File(WATERTIFTOJPGPATH).mkdirs();
                        }
                        Date date = new Date();
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");

                        String format1 = format.format(date);
                        try {
                            BufferedImage bufferegImage = ImageIO.read(new File(srcPath));
                            ImageIO.write(bufferegImage, "jpg", new File(WATERTIFTOJPGPATH + format1 + ".jpg"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        root = selectRootByNotWater(WATERTIFTOJPGPATH);
                        outSrc = EMRRECORDJSP + File.separator + root + "/jiashi/tifToJpgLoad/" + format1 + ".jpg";
                    } else {
                        //将原图片地址转换成映射地址
                        //获取盘符并转换映射地址的头部地址
                        root = selectRootByNotWater(srcPath);
                        //获取盘符后面的地址
                        String str1 = srcPath.substring(0, srcPath.indexOf(File.separator));
                        picPath = srcPath.substring(str1.length() + 1, srcPath.length());
                        outSrc = EMRRECORDJSP + File.separator + root + picPath;
                    }
                }
                outs.add(outSrc);
                Integer value = Math.round((i + 1) * 100 / nameList.length);
                printLoadingMap.put(mapKey, value);
            }
        }
        return outs;
    }


    public List<String> selectPrintPic2(HttpServletResponse response, String patientId, String names, String sources, String mapKey) {
        List<String> outs = new LinkedList<>();
        if (StringUtils.isNotBlank(names)) {
            String[] nameList = names.split(",");
//            String[] sourceList = sources.split(",");
            //获取水印设置
            EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
            //获取是否打印文本水印
            Short printEffective = emrPdfWaterSet.getPrintEffective();
            //获取是否打印图片水印
            Short printIsImg = emrPdfWaterSet.getPrintIsImg();
            for (int i = 0; i < nameList.length; i++) {
                //定义图片根目录地址
                String rootPath = "";
                //组织原图片地址
                //原图片地址
                String srcPath = nameList[i];
                //定义输出地址
                String outSrc = "";
                //获取项目上下文地址
                //不需要水印
                String root = "";
                String picPath = "";
                //判断是否是tif图片
                boolean tifFileFlag = checkTifFile(srcPath);
                if (tifFileFlag) {
                    String picSrc = WATERPICPATH + patientId + File.separator;
                    //目录不存在则创建
                    if (!new File(picSrc).isDirectory()) {
                        new File(picSrc).mkdirs();
                    }
                    //组织加水印后图片存放地址
                    picPath = picSrc + nameList[i];
                    //转换图片输出
                    //tifToJpg(srcPath,picPath);
                    outSrc = EMRRECORDJSP + File.separator + "reload" + File.separator + patientId + File.separator + nameList[i];
                } else {
                    //将原图片地址转换成映射地址
                    //获取盘符并转换映射地址的头部地址
                    root = selectRootByNotWater(srcPath);
                    //获取盘符后面的地址
                    String str1 = srcPath.substring(0, srcPath.indexOf(File.separator));
                    picPath = srcPath.substring(str1.length() + 1, srcPath.length());
                    outSrc = EMRRECORDJSP + File.separator + root + picPath;
                    outs.add(outSrc);
                }
                Integer value = Math.round((i + 1) * 100 / nameList.length);
                printLoadingMap.put(mapKey, value);
            }
        }
        return outs;
    }

    /**
     * 判断是否是tif图片
     *
     * @param srcPath
     * @return
     */
    private boolean checkTifFile(String srcPath) {
        InputStream is = null;
        try {
            is = new FileInputStream(new File(srcPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] content = new byte[0];
        try {
            content = IOUtils.toByteArray(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 判断图片类型jpg jpeg png bmp编码方式是tif格式的
        if (content[0] == 0x49 && content[1] == 0x49 && content[2] == 0x2A && content[3] == 0x00) {
            return true;
        }
        return false;
    }

    /*private static String tifToJpg(String tifUrl, String tifToJpgRoot) {
        File fileTiff = new File(tifToJpgRoot);
        if (fileTiff.exists()) {
            return tifToJpgRoot;
        }
        RenderedOp rd = JAI.create("fileload", tifUrl);//读取iff文件
        OutputStream ops = null;
        try {
            ops = new FileOutputStream(tifToJpgRoot);
            //文件存储输出流
            JPEGEncodeParam param = new JPEGEncodeParam();
            ImageEncoder image = ImageCodec.createImageEncoder("JPEG", ops, param); //指定输出格式
            image.encode(rd );
            //解析输出流进行输出
            ops.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tifToJpgRoot;
    }*/


    /**
     * 南方太和医院医院打印预览前加载图片
     *
     * @param patientId
     * @param rootPaths
     * @param names
     * @param sources
     * @return
     */
    public List<String> selectPrintPicTh(String patientId, String rootPaths, String names, String sources, String mapKey) {
        List<String> outs = new LinkedList<>();
        if (StringUtils.isNotBlank(names)) {
            String[] rootPathList = rootPaths.split(",");
            String[] nameList = names.split(",");
            String[] sourceList = sources.split(",");
            //获取水印设置
            EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
            //获取是否打印文本水印
            Short printEffective = emrPdfWaterSet.getPrintEffective();
            //获取是否打印图片水印
            Short printIsImg = emrPdfWaterSet.getPrintIsImg();
            CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
            //判断是否有两套图像
            int num = 0;
            if (null != commomVo.getFilePath2() && !"".equals(commomVo.getFilePath2())) {
                num = 1;
            }
            for (int i = 0; i < nameList.length; i++) {
                //定义图片根目录地址
                String rootPath = "";
                //组织原图片地址
                if (num == 1) {
                    rootPath = commomVo.getFilePath2();
                } else {
                    if ("1".equals(sourceList[i])) {
                        //扫描图片地址位于rootPathList第一个
                        rootPath = rootPathList[0];
                    } else {
                        rootPath = rootPathList[1];
                    }
                }
                //原图片地址
                String srcPath = rootPath + File.separator + nameList[i];
                //定义输出地址
                String outSrc = "";
                //获取项目上下文地址
                if ((printEffective != null && printEffective == 1) ||
                        (printIsImg != null && printIsImg == 1)) {
                    if (num == 1) {
                        //第二套打印图像输出
                        //组织加水印后图片存放目录
                        String waterPicRoot = WATERPICPATH + patientId + File.separator + 3 + File.separator;
                        //目录不存在则创建
                        if (!new File(waterPicRoot).isDirectory()) {
                            new File(waterPicRoot).mkdirs();
                        }
                        //组织加水印后图片存放地址
                        String waterPicPath = waterPicRoot + nameList[i];
                        if (!new File(waterPicPath).exists()) {
                            //定义第二文本水印 姓名 + 科室 + ip
                            EmrPdfWaterSet emrPdfWaterSet1 = getEmrPdfWaterSet(emrPdfWaterSet);
                            img2PdfUtil.addWatermarkPic1(new File(srcPath), emrPdfWaterSet, waterPicPath, emrPdfWaterSet1);
                        }
                        //组织输出地址
                        outSrc = EMRRECORDJSP + "\\reload\\" + patientId + File.separator + 3 + File.separator + nameList[i];
                    } else {
                        //组织加水印后图片存放目录
                        String waterPicRoot = WATERPICPATH + patientId + File.separator + sourceList[i] + File.separator;
                        //目录不存在则创建
                        if (!new File(waterPicRoot).isDirectory()) {
                            new File(waterPicRoot).mkdirs();
                        }
                        //组织加水印后图片存放地址
                        String waterPicPath = waterPicRoot + nameList[i];
                        if (!new File(waterPicPath).exists()) {
                            EmrPdfWaterSet emrPdfWaterSet1 = getEmrPdfWaterSet(emrPdfWaterSet);
                            img2PdfUtil.addWatermarkPic1(new File(srcPath), emrPdfWaterSet, waterPicPath, emrPdfWaterSet1);
                        }
                        //组织输出地址
                        outSrc = EMRRECORDJSP + "\\reload\\" + patientId + File.separator + sourceList[i] + File.separator + nameList[i];
                    }
                } else {
                    //不需要水印
                    //将原图片地址转换成映射地址
                    //获取盘符并转换映射地址的头部地址
                    String root = selectRootByNotWater(srcPath);
                    //获取盘符后面的地址
                    String str1 = srcPath.substring(0, srcPath.indexOf(File.separator));
                    String picPath = srcPath.substring(str1.length() + 1, srcPath.length());
                    outSrc = EMRRECORDJSP + File.separator + root + picPath;
                }
                outs.add(outSrc);
                Integer value = Math.round((i + 1) * 100 / nameList.length);
                printLoadingMap.put(mapKey, value);
            }
        }
        return outs;
    }

    /**
     * 根据地址转换映射头
     *
     * @param srcPath
     * @return
     */
    private String selectRootByNotWater(String srcPath) {
        //获取盘符
        String str = srcPath.substring(0, 1).toUpperCase();
        switch (str) {
            case "C":
                return "reloadC\\";
            case "D":
                return "reloadD\\";
            case "E":
                return "reloadE\\";
            case "F":
                return "reloadF\\";
            case "G":
                return "reloadG\\";
            case "H":
                return "reloadH\\";
            case "I":
                return "reloadI\\";
            case "J":
                return "reloadJ\\";
            case "K":
                return "reloadK\\";
            case "Z":
                return "reloadZ\\";
            default:
                ;
        }
        return null;
    }

    public Integer getPrintPicLoading(String mapKey) {
        Integer loadingPerson = printLoadingMap.get(mapKey);
        if (loadingPerson == null) {
            //为空返回0
            return 0;
        } else if (loadingPerson == 100) {
            //完成后移除内存
            printLoadingMap.remove(mapKey);
        }
        return loadingPerson;
    }

    /**
     * 批量添加
     *
     * @param tableName
     * @param commomMapper
     * @param operList
     */
    public void simpleInsert(String tableName, CommomMapper commomMapper, List operList) {
        if (!CollectionUtils.isEmpty(operList)) {
            ///查询表列数
            int colCount = commomMapper.selectColByTableName(tableName);
            List list = new ArrayList();
            int simpleInsertCount = 2100 / colCount;
            for (int i = 0; i < operList.size(); i++) {
                //处理批量添加sql太长问题，设定个数为180
                if (i > 0 && list.size() % simpleInsertCount == 0) {
                    list.clear();
                }
                list.add(operList.get(i));
                //是180的倍数或最后一个
                if (list.size() % simpleInsertCount == 0 || i == operList.size() - 1) {
                    commomMapper.SimpleInsert(list);
                }
            }
        }
    }
}
