package com.ann.demo.service;

import com.ann.demo.entity.filing.ArchiveDetail;
import com.ann.demo.entity.filing.dto.MessageDto;
import com.ann.demo.entity.interfaceEntity.ArchiveMaster;
import com.ann.demo.entity.interfaceEntity.CommonTable;
import com.ann.demo.entity.interfaceEntity.CommonTable1;
import com.ann.demo.entity.normalEntity.OutPara;
import com.ann.demo.primaryRepository.ScanningFileRepository;
import com.ann.demo.primaryEntity.ScanningFile;
import com.ann.demo.repository.CommonTable1Repository;
import com.ann.demo.repository.CommonTableRepository;
import com.ann.demo.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 解析逻辑
 *
 * @Author: LeiJiaXin
 * @Date: 2019/8/20 16:29
 */
@Component
public class AnalysisService {

    final Logger logger = LoggerFactory.getLogger(AnalysisService.class);


    @Autowired
    private ScanningFileRepository scanningFileRepository;

    @Autowired
    private ArchiveDetailService archiveDetailService;

    @Autowired
    private CommonTableRepository commonTableRepository;

    @Autowired
    private CommonTable1Repository commonTable1Repository;

    @Autowired
    private ArchiveMasterService archiveMasterService;

    public void handleScanningFile(List<ScanningFile> scanningFileList) {
        //处理ScanningFile\
        for (ScanningFile scanningFile: scanningFileList) {
            String remark = null;
            String status = "1";
            try{
                remark = handlePdfFile(scanningFile);
            }catch (Exception e){
                remark = e.getMessage();
                logger.error("处理扫描文件出错：{}" ,e.getMessage());
            }

            if(remark != null){
                status = "2";
            }else{
                remark = LocalDateTime.now().toString();
            }
            scanningFile.setRemark(remark);
            scanningFile.setStatus(status);
            scanningFileRepository.save(scanningFile);
        }

    }

    public String handlePdfFile(ScanningFile scanningFile) throws Exception{
        //处理ScanningFile
        // 判断病案首页数据是否存在
        CommonTable commonTable = commonTableRepository.findByInpNoAndVisitId(scanningFile.getInpNo(), scanningFile.getVisitId());
        if(commonTable == null){
            String masterId = scanningFile.getApplyId() != null ? scanningFile.getApplyId() : UUID.randomUUID().toString();
            commonTable = new CommonTable(masterId,scanningFile.getPatientId(),scanningFile.getAge(),scanningFile.getSex(),scanningFile.getVisitId(),scanningFile.getName(),
                    scanningFile.getAdmissDate(),scanningFile.getDisDate(),scanningFile.getDisDept(),scanningFile.getAttending(),scanningFile.getInpNo(),"扫描系统");
//            //保存公共表
            commonTableRepository.save(commonTable);
            //保存公共表1
            commonTable1Repository.save( new CommonTable1(commonTable.getMasterId(),scanningFile.getBirthday(),scanningFile.getIdCard(),scanningFile.getAdmissDept(),scanningFile.getAdmissDoctor()));
        }

        Object[] objects = WebServiceUtils.connect(scanningFile.getPath() + "\\" + scanningFile.getFileName());
        if (objects == null) {
            return "下载图片出错了。。。";
        }

        String number = scanningFile.getNumber();
        // Integer number = 1;
        //37006704-10-47-1.CDP 截成  10-47-1.CDP
        number = number.substring(number.indexOf("-")+1,number.length());
        //10-47-1.CDP 截成  47-1.CDP
        number = number.substring(number.indexOf("-")+1,number.length());
        //47-1.CDP 截成47
        number = number.substring(0,number.indexOf("-"));

//        byte[] bytes = (byte[]) objects[0];
        String applyId = commonTable.getMasterId() + "~" + (number != null ? number : "");
        // 给临时图片填充内容
        File imageTempFile = FileUtils.createFile("images", scanningFile.getInpNo(), scanningFile.getVisitId(), applyId);
        File imageFile = FileUtils.getImageFileByByteArray(objects, imageTempFile);
        if (imageFile == null) {
            return "填充临时图片出错了。。。";
        }

        File pdfFile = FileUtils.createFile("pdfs", scanningFile.getInpNo(), scanningFile.getVisitId(), applyId);
        String pdfPath = PdfUtils.imagesToPdf(imageFile, pdfFile);
        //存入pdf地址
        if (pdfPath == null) {
            return "image转成pdf出错了。。。";
        }


//        // 如果存在 那就更新
//        ArchiveDetail archiveDetail = archiveDetailService.isExit(commonTable.getMasterId(), "1", "扫描系统", applyId);
//        if (archiveDetail == null) {
//            archiveDetail = new ArchiveDetail(commonTable.getMasterId(), new Date(), "1", "扫描系统", applyId, pdfPath,Integer.valueOf(number));
//            archiveDetailService.save(archiveDetail);
//        }
        String assortId = "1";
        switch (scanningFile.getAssortId()){
            case "1": // 病案首页
                assortId = "3";
                break;
            case "2":  //出院（或死亡）记录（小结）
                assortId = "113";
                break;
            case "3": //入院记录
                assortId = "9";
                break;
            case "4": //病程记录
                assortId = "11";
                break;
            case "5": //死亡病例讨论
                assortId = "14";
                break;
            case "6": //特殊病情及治疗记录
                assortId = "20";
                break;
            case "7": //会诊记录单
                assortId = "15";
                break;
            case "8": //病重(病危)护理记录
                assortId = "121";
                break;
            case "9": //知情同意书
                assortId = "20";
                break;
            case "10": //辅助检查报告单
                assortId = "110";
                break;
            case "11": //医嘱单
                assortId = "25";
                break;
            case "12": //体温单
                assortId = "5";
                break;
            case "13": //护理记录
                assortId = "2";
                break;
            case "14": //死亡患者门诊病历
                assortId = "18";
                break;
            case "15": //其他资料
                assortId = "18";
                break;
        }
        archiveDetailService.save(new ArchiveDetail(commonTable.getMasterId(), new Date(), assortId, "扫描系统", applyId, pdfPath,Integer.valueOf(number)));
        return null;
    }

    public String handlePdfFile1(MessageDto messageDto) throws Exception{
        String pdfPath = "";
        ArchiveMaster archiveMaster = archiveMasterService.findByInpNoAndVisitIdAndIsValid(messageDto.getInpNo(),messageDto.getVisitId());
        if(archiveMaster == null){
            return "没有患者信息";
        }
        File imageFile = FileUtils.createFile("images", messageDto.getInpNo(), messageDto.getVisitId(),"");
        if(DownloadUtils.downloadImageFile("","", imageFile) == null){
            return "下载图像出错";
        }
        File pdfFile = FileUtils.createFile("pdfs", messageDto.getInpNo(), messageDto.getVisitId(), messageDto.getApplyId());
        //存入pdf地址
        pdfPath = PdfUtils.imagesToPdf(imageFile, pdfFile);
        if (pdfPath == null) {
            return "image转成pdf出错了。。。";
        }
        ArchiveDetail archiveDetail = new ArchiveDetail(archiveMaster.getId(), new Date(), messageDto.getType(), "扫描系统", messageDto.getApplyId(), pdfPath,Integer.valueOf(messageDto.getPageNum()));
        archiveDetail.setTitle(messageDto.getApplyId());
        archiveDetailService.save(archiveDetail);
        if(archiveDetail.getId() != null){
            return null;
        }
        return "出错了";
    }

    public static String getReturnResult(boolean resultCode,String remark) throws Exception{
        OutPara outPara = new OutPara();
        if (resultCode) {
            outPara.setRESULT_CODE(true);
            outPara.setRESULT_CONTENT("成功");
        } else {
            outPara.setRESULT_CODE(false);
            outPara.setRESULT_CONTENT(remark);
        }
        return XMLUtils.generateXmlStr(outPara);
    }


}
