package com.emr.controller;

import com.emr.dao.Archive_DetailMapper;
import com.emr.dao.Archive_MasterMapper;
import com.emr.dao.CommomMapper;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.dao.commomSearch.ScanPathMapper;
import com.emr.dao.emrPdfWaterSet.EmrPdfWaterSetMapper;
import com.emr.dao.recordLock.Emr_LockMapper;
import com.emr.dao.tScanAssort.T_Scan_AssortMapper;
import com.emr.entity.Power_User;
import com.emr.entity.Zd_Assort;
import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.emr.entity.recordType.Emr_Type;
import com.emr.service.FontService;
import com.emr.service.Zd_AssortServiceImpl;
import com.emr.service.batchExport.BatchExportService;
import com.emr.service.pushRcvBasic.PushRcvBasicService;
import com.emr.service.recordType.EmrTypeService;
import com.emr.service.tScanAssort.T_Scan_AssortService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.Jpg2PdfUtil;
import com.emr.vo.ArchiveMasterVo;
import com.emr.vo.FontVo.*;
import com.emr.vo.Msg;
import com.emr.vo.PushRcvBasicDTO;
import com.emr.vo.ZhFyImageVo;
import com.emr.vo.commomSearch.CommomTree;
import com.emr.vo.commomSearch.CommomVo;
import com.emr.vo.commomSearch.ScanPathVo;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Utilities;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.codec.TiffImage;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/9/16 9:48
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/9/16 9:48
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("font/")
public class FontController {
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;
    @Autowired
    private Emr_LockMapper lockMapper;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private T_Scan_AssortMapper scanAssortMapper;
    @Autowired
    private FontService fontService;

    @Autowired
    private EmrTypeService emrTypeService;
    @Autowired
    private Zd_AssortServiceImpl assortService;
    @Autowired
    private Emr_Apply_ApproveMapper apply_approveMapper;
    @Autowired
    private T_Scan_AssortService tScanAssortService;
    @Autowired
    private PushRcvBasicService pushRcvBasicService;

    @Autowired
    private Archive_MasterMapper archiveMasterMapper;
    @Autowired
    private Archive_DetailMapper archiveDetailMapper;
    @Autowired
    private EmrPdfWaterSetMapper pdfWaterSetMapper;
    @Autowired
    private BatchExportService batchExportService;

    /**
     * 2.1
     *
     * @MethodName getLockList
     * @Description: 返回锁定记录接口
     * @Param lockVo.patientId, admissTimes, admissId
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-09-16
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-09-16
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getLockList", method = RequestMethod.GET)
    @ResponseBody
    public Msg getLockList(LockVo lock) throws Exception {
        FontCommom commom = new FontCommom();
        BeanUtils.copyProperties(lock, commom);
        List<FontCommom> list = commomMapper.isExistInpatient(commom);
        if (CollectionUtils.isEmpty(list)) {
            return Msg.fail("该病案不存在!");
        }
        //根据条件查询结果
        List<LockVo> locks = lockMapper.seleceAll(lock);
        if (null == locks || locks.isEmpty()) {
            return Msg.fail("无该锁定记录!");
        }
        return Msg.success().add("list", locks);
    }

    /**
     * 2.2
     *
     * @MethodName getInpatientList
     * @Description: 返回病案记录接口
     * @Param lockVo.patientId, admissTimes, admissId
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-09-16
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-09-16
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getInpatientList")
    @ResponseBody
    public Msg getInpatientList(FontCommom commom) throws Exception {
        Msg msg = getScanAssortVoList(commom, 0);
        if (msg.getCode() == 200) {
            return msg;
        }
        //根据条件查询结果
        List<FontCommom> inpatientList = commomMapper.getInpatientList(commom);
        if (null != inpatientList && !inpatientList.isEmpty()) {
            return Msg.success().add("list", inpatientList);
        } else {
            return Msg.fail("该病案不存在!");
        }
    }


    /**
     * 封装查询分段信息的判断及查询分段信息
     */
    private Msg getScanAssortVoList(FontCommom commom, int flag) throws Exception {
        //判断参数是否不为全空
        if (StringUtils.isNotBlank(commom.getPatientId()) && StringUtils.isBlank(commom.getInpatientNo()) && StringUtils.isBlank(commom.getAdmissId()) && StringUtils.isNotBlank(commom.getName())
                && null == commom.getAdmissTimes() && StringUtils.isBlank(commom.getDisDate()) && StringUtils.isBlank(commom.getIdCard())) {
            return Msg.fail("由于数据太大,参数不能全为空!");
        }
        //判断参数不只带住院次数
        if (StringUtils.isBlank(commom.getInpatientNo()) && StringUtils.isBlank(commom.getAdmissId())
                && null != commom.getAdmissTimes() && StringUtils.isBlank(commom.getDisDate()) && StringUtils.isBlank(commom.getIdCard())) {
            return Msg.fail("由于数据太大,参数不能只带住院次数!");
        }
        //判断住院记录是否存在
        if (flag == 1) {
            //是否需要判断
            List<FontCommom> list = commomMapper.isExistInpatient(commom);
            if (CollectionUtils.isEmpty(list)) {
                return Msg.fail("该病案不存在!");
            }
        }
        return Msg.success();
    }

    /**
     * 2.3
     *
     * @MethodName getScanAssortPathList
     * @Description: 返回分段页数与PDF路径接口(无PDF)
     * @Param lockVo.patientId, admissTimes, admissId
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-09-16
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-09-16
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getScanAssortPathList", method = RequestMethod.GET)
    @ResponseBody
    public Msg getScanAssortPathList(FontCommom commom) throws Exception {
        Msg msg = getScanAssortVoList(commom, 1);
        if (msg.getCode() == 200) {
            return msg;
        }
        //根据条件查询分段信息
        List<ScanAssortVo> scanAssortVos = scanAssortMapper.seleteScanAssortPath(commom);
        List<ScanAssortVoNotFilePath> scanAssortVos1 = new ArrayList<>();
        if (null != scanAssortVos && !scanAssortVos.isEmpty()) {
            for (ScanAssortVo scanAssortVo : scanAssortVos) {
                if (StringUtils.isNotBlank(scanAssortVo.getFilePath()) && StringUtils.isNotBlank(scanAssortVo.getScanPage())) {
                    String[] pages = scanAssortVo.getScanPage().split(",");
                    // 实例化图片
                    Image image = null;
                    //不成张合成的高度
                    float tempHeight = 0;
                    Short pageCount = 0;
                    for (String filePath : pages) {
                        if (StringUtils.isNotBlank(filePath)) {
                            filePath = scanAssortVo.getFilePath() + "\\" + filePath;
                            File file1 = new File(filePath);
                            if (file1.exists()) {
                                if (file1.getName().endsWith(".tif") || file1.getName().endsWith(".tiff")) {
                                    Object localObject1 = null;
                                    Object localObject2 = null;
                                    URL paramURL = Utilities.toURL(filePath);
                                    try {
                                        if ("file".equals(paramURL.getProtocol())) {
                                            localObject2 = paramURL.getFile();
                                            localObject2 = Utilities
                                                    .unEscapeURL((String) localObject2);
                                            localObject1 = new RandomAccessFileOrArray(
                                                    (String) localObject2);
                                        } else {
                                            localObject1 = new RandomAccessFileOrArray(paramURL);
                                        }

                                        int pageNums = TiffImage
                                                .getNumberOfPages((RandomAccessFileOrArray) localObject1);
                                        if (pageNums > 0) {
                                            for (int i = 1; i <= pageNums; i++) {
                                                localObject2 = TiffImage.getTiffImage(
                                                        (RandomAccessFileOrArray) localObject1, i);
                                                image = (Image) localObject2;
                                            }
                                        }
                                        if (localObject1 != null) {
                                            ((RandomAccessFileOrArray) localObject1).close();
                                        }

                                    } finally {
                                        if (localObject1 != null) {
                                            ((RandomAccessFileOrArray) localObject1).close();
                                        }
                                    }
                                } else if (file1.getName().endsWith(".png")
                                        || file1.getName().endsWith(".jpg")
                                        || file1.getName().endsWith(".gif")
                                        || file1.getName().endsWith(".jpeg")
                                ) {
                                    // 实例化图牿
                                    image = Image.getInstance(filePath);
                                }
                                // 获得图片的高庿
                                float heigth = image.getHeight();
                                float width = image.getWidth();
                                // 合理压缩，h>w，按w压缩，否则按w压缩
                                int percent = Jpg2PdfUtil.getPercent(heigth, width);

                                // 设置图片居中显示
                                image.setAlignment(Image.ALIGN_CENTER);
                                // 按百分比显示图片的比便
                                if (width > 1024 || heigth > 786) {
                                    image.scalePercent(percent + 5);
                                    pageCount++;
                                    //整张，把合成的高度置为0；
                                    tempHeight = 0;
                                } else if (heigth < 786) {
                                    if (tempHeight == 0) {
                                        pageCount++;
                                    }
                                    tempHeight += heigth;
                                    if (tempHeight > 786) {
                                        pageCount++;
                                        tempHeight = heigth;
                                    }
                                }
                            }
                        }
                    }
                    scanAssortVo.setPageCount(pageCount);
                }
                ScanAssortVoNotFilePath vo1 = new ScanAssortVoNotFilePath();
                BeanUtils.copyProperties(scanAssortVo, vo1);
                scanAssortVos1.add(vo1);
            }
        } else {
            return Msg.fail("查询无该记录!");
        }
        return Msg.success().add("list", scanAssortVos1);
    }

    /**
     * @description: 潮州人医一次性接口导出2月到3月份出院病历知情同意书
     * @author linjj
     * @date: 2024/3/25 15:25
     */
    @RequestMapping(value = "downloadPdfBlood", method = RequestMethod.GET)
    @ResponseBody
    public void downloadPdf(HttpServletResponse response) {
        //查询需要下载患者
        List<ArchiveMasterVo> list = archiveMasterMapper.getMasterID();
        for (ArchiveMasterVo archiveMaster : list) {
            String masterId = archiveMaster.getId();
            List<String> pdfPaths = archiveDetailMapper.selectPDFRATH2(masterId, "7A9C621E3F4F4C9CA95292141C5E15E8");
            if (pdfPaths!=null||pdfPaths.isEmpty()){
                String newPath = "D:\\jiashi\\copy" + File.separator + archiveMaster.getName() + "-" + archiveMaster.getInpNo()+"-知情同意书";
                if (!new File(newPath).isDirectory()) {
                    new File(newPath).mkdirs();
                }
                for (String pdfPath:pdfPaths){
                    String newSrc = newPath + File.separator + new File(pdfPath).getName();
                    try (InputStream inputStream = new FileInputStream(pdfPath);
                         OutputStream outputStream = new FileOutputStream(newSrc)) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        System.out.println("文件拷贝完成");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 2.4
     *
     * @MethodName getScanAssortFilePathList
     * @Description: 返回分段页数与PDF路径接口
     * @Param lockVo.patientId, admissTimes, admissId
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-09-16
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-09-16
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getScanAssortFilePathList", method = RequestMethod.GET)
    @ResponseBody
    public Msg getScanAssortFilePathList(FontCommom commom, HttpServletResponse response) throws Exception {
        Msg msg = getScanAssortVoList(commom, 1);
        if (msg.getCode() == 200) {
            return msg;
        }
        //根据条件查询分段信息
        List<ScanAssortVo> scanAssortVos = scanAssortMapper.seleteScanAssortPath(commom);
        List<ScanAssortVo1> scanAssortVos1 = new ArrayList<>();
        if (null != scanAssortVos && !scanAssortVos.isEmpty()) {
            // 实例化图片
            Image image = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
            // 循环获取图片文件夹内的图牿
            Document doc = new Document();
            PdfWriter.getInstance(doc, baos);
            // 开启文档
            doc.open();
            try {
                for (ScanAssortVo scanAssortVo : scanAssortVos) {
                    if (StringUtils.isNotBlank(scanAssortVo.getFilePath()) && StringUtils.isNotBlank(scanAssortVo.getScanPage())) {
                        //转换pdf
                        String[] pages = scanAssortVo.getScanPage().split(",");
                        //不成张合成的高度
                        float tempHeight = 0;
                        short pageCount = 0;
                        for (String filePath : pages) {
                            if (StringUtils.isNotBlank(filePath)) {
                                filePath = scanAssortVo.getFilePath() + "\\" + filePath;
                                File file1 = new File(filePath);
                                if (file1.exists()) {
                                    if (file1.getName().endsWith(".tif") || file1.getName().endsWith(".tiff")) {
                                        Object localObject1 = null;
                                        Object localObject2 = null;
                                        URL paramURL = Utilities.toURL(filePath);
                                        try {
                                            if ("file".equals(paramURL.getProtocol())) {
                                                localObject2 = paramURL.getFile();
                                                localObject2 = Utilities
                                                        .unEscapeURL((String) localObject2);
                                                localObject1 = new RandomAccessFileOrArray(
                                                        (String) localObject2);
                                            } else {
                                                localObject1 = new RandomAccessFileOrArray(paramURL);
                                            }

                                            int pageNums = TiffImage
                                                    .getNumberOfPages((RandomAccessFileOrArray) localObject1);
                                            if (pageNums > 0) {
                                                for (int i = 1; i <= pageNums; i++) {
                                                    localObject2 = TiffImage.getTiffImage(
                                                            (RandomAccessFileOrArray) localObject1, i);
                                                    image = (Image) localObject2;
                                                }
                                            }
                                            if (localObject1 != null) {
                                                ((RandomAccessFileOrArray) localObject1).close();
                                            }

                                        } finally {
                                            if (localObject1 != null) {
                                                ((RandomAccessFileOrArray) localObject1).close();
                                            }
                                        }
                                    } else if (file1.getName().endsWith(".png")
                                            || file1.getName().endsWith(".jpg")
                                            || file1.getName().endsWith(".gif")
                                            || file1.getName().endsWith(".jpeg")
                                    ) {
                                        // 实例化图牿
                                        image = Image.getInstance(filePath);
                                    }
                                    // 获得图片的高庿
                                    float heigth = image.getHeight();
                                    float width = image.getWidth();
                                    // 合理压缩，h>w，按w压缩，否则按w压缩
                                    int percent = Jpg2PdfUtil.getPercent(heigth, width);

                                    // 设置图片居中显示
                                    image.setAlignment(Image.ALIGN_CENTER);
                                    // 按百分比显示图片的比便
                                    if (width > 1024 || heigth > 786) {
                                        image.scalePercent(percent + 5);
                                        pageCount++;
                                        //整张，把合成的高度置为0；
                                        tempHeight = 0;
                                    } else if (heigth < 786) {
                                        if (tempHeight == 0) {
                                            pageCount++;
                                        }
                                        tempHeight += heigth;
                                        if (tempHeight > 786) {
                                            pageCount++;
                                            tempHeight = heigth;
                                        }
                                    }
                                    doc.add(image);
                                }
                            }
                        }
                        scanAssortVo.setPageCount(pageCount);
                        byte[] bytes = baos.toByteArray();
                        String filePath1 = Base64Utils.encodeToString(bytes);
                        scanAssortVo.setFilePath(filePath1);
                    } else {
                        scanAssortVo.setFilePath("");
                    }
                    ScanAssortVo1 vo1 = new ScanAssortVo1();
                    BeanUtils.copyProperties(scanAssortVo, vo1);
                    scanAssortVos1.add(vo1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (doc.isOpen()) {
                    doc.close();
                }
                baos.flush();
                baos.close();
            }
        } else {
            return Msg.fail("查询无该记录!");
        }
        return Msg.success().add("list", scanAssortVos1);
    }

    /**
     * 2.8
     *
     * @MethodName updateTableCommom
     * @Description: 操作公共表commomtable、commomtable1
     * @Param
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-09-16
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-09-16
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "updateTableCommom", method = RequestMethod.POST)
    @ResponseBody
    public Msg updateTableCommom(CommomVo commom) throws Exception {
        return fontService.updateTableCommom(commom);
    }


    /**
     * @description: 第三方调阅病案影像图像
     * @params: patientId
     * @params: flag
     * @author linjj
     * @date: 2023/5/18 15:45
     */
    @RequestMapping("showRecordIframeBlood")
    public String showRecordIframeBlood(String patientId, String flag, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        Power_User user = new Power_User();
        user.setUserName("admin");
        user.setRoleId(0);
        //打印分类集合
        List<Emr_Type> emrTypes = null;
        List<Zd_Assort> zdAssorts = null;
        int isDownload = 0;
        try {
            emrTypes = emrTypeService.selectAllByCreater2(1, request);
            //病案分段集合
            zdAssorts = assortService.selectAllByPower(user);
            isDownload = apply_approveMapper.selectIsPowerByUser(user.getUserName(), patientId, 3);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("emrTypes", emrTypes);
        model.addAttribute("zdAssorts", zdAssorts);
        model.addAttribute("isDownload", isDownload);
        //查询是否有打印权限
        int printFlag = 1;
        int moveFlag = 1;
        model.addAttribute("moveFlag", moveFlag);
        model.addAttribute("printFlag", printFlag);
        model.addAttribute("flag", flag);
        return "recordManage/commomSearch/showRecordIframeBlood";
    }

    /**
     * @description: 珠海妇幼根据住院号住院次数返回患者病案信息
     * @params: inpatientNo
     * @params: admissTimes
     * @author linjj
     * @date: 2023/9/8 10:40
     */
    @RequestMapping(value = "getPathListByInpatientNo", method = RequestMethod.POST)
    @ResponseBody
    public Msg getPathListByInpatientNo(String inpatientNo, String admissTimes) {
        if (StringUtils.isBlank(inpatientNo)) {
            return Msg.fail("inpatientNo住院号不得为空");
        }
        if (StringUtils.isBlank(admissTimes)) {
            return Msg.fail("admissTimes住院次数不得为空");
        }
        List<ZhFyImageVo> list = tScanAssortService.getPathListByInpatientNo(inpatientNo, admissTimes);
        return Msg.successData(list);
    }


    /**
     * @description: 珠海妇幼根据患者出院时间返回患者病案信息
     * @params: startTime
     * @params: endTime
     * @author linjj
     * @date: 2023/9/8 10:40
     */
    @RequestMapping(value = "getPathListByDisDate", method = RequestMethod.POST)
    @ResponseBody
    public Msg getPathListByDisDate(String startTime, String endTime) {
        if (StringUtils.isBlank(startTime)) {
            return Msg.fail("startTime开始时间范围不得为空");
        }
        if (StringUtils.isBlank(endTime)) {
            return Msg.fail("endTime结束时间范围不得为空");
        }
        List<ZhFyImageVo> list = tScanAssortService.getPathListByDisDate(startTime, endTime);
        return Msg.successData(list);
    }

    /**
     * @description: 病案回收存储调用接口
     * @author linjj
     * @date: 2023/9/26 11:09
     */
    @RequestMapping(value = "addRcvBasic", method = RequestMethod.POST)
    @ResponseBody
    public Msg addRcvBasic(@RequestBody List<PushRcvBasicDTO> list) {
        int i = pushRcvBasicService.addRcvBasic(list);
        if (i == 1) {
            return Msg.success();
        }
        return Msg.fail();
    }
    /**
     * @description: 批量导出国家病历
     * @params: taskid
     * @return: String
     * @author linjj
     * @date: 2024/4/12 22:43
     */
    @ResponseBody
    @RequestMapping(value = "BatchExportPdf")
    public String  batchExportPdf(int taskId) throws Exception {
        return batchExportService.batchExportPdf(taskId);
    }

    /**
     * 下载pdf病例到本地
     * @param taskId
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "downloadPdfZip", produces = {"text/json;charset=UTF-8"}, method = RequestMethod.POST)
    public String  downloadPdfZip(int taskId,HttpServletResponse response) throws IOException {
        return batchExportService.downloadPdfZip(taskId,response);
    }
}
