package com.ann.demo.interfaces.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ann.demo.entity.constant.AliasName;
import com.ann.demo.entity.constant.InterfaceName;
import com.ann.demo.entity.constant.WebserviceId;
import com.ann.demo.entity.filing.ArchiveDetail;
import com.ann.demo.entity.filing.MessageScanning;
import com.ann.demo.entity.filing.MessageSubordinate;
import com.ann.demo.entity.filing.dto.MessageDto;
import com.ann.demo.entity.filing.dto.PatientMainDto;
import com.ann.demo.entity.interfaceEntity.*;
import com.ann.demo.interfaces.HomepageDictionary;
import com.ann.demo.repository.ArchiveMasterRepository;
import com.ann.demo.repository.MessageScanningRepository;
import com.ann.demo.service.*;
import com.ann.demo.utils.FileUtils;
import com.ann.demo.utils.XMLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.WebService;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: LeiJiaXin
 * @Date: 2019/6/11 17:01
 */

@WebService(serviceName = "HomepageDictionary", // 与接口中指定的name一致
        targetNamespace = "http://interfaces.demo.ann.com/", // 与接口中的命名空间一致,一般是接口的包名倒
        endpointInterface = "com.ann.demo.interfaces.HomepageDictionary"// 接口地址
)
public class HomepageDictionaryImpl implements HomepageDictionary {

    private static final Logger logger = LoggerFactory.getLogger(HomepageDictionaryImpl.class);

    @Autowired
    private ArchiveMasterService archiveMasterService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageSubordinateService messageSubordinateService;

    @Autowired
    private ArchiveDetailService archiveDetailService;

    @Autowired
    private ArchiveMasterRepository archiveMasterRepository;

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private MessageScanningRepository messageScanningRepository;

    @Override
    public String NurseData(String xmlStr) {
        String outContent = "失败";
        try {
            // 1、定义变量
            boolean flag = false;
            Integer result = 0;
            String type = "", patientMainStr = null,remark = null,masterId = null;
            ArchiveMaster archiveMaster ;
            long startTime = System.currentTimeMillis();
            Date xmlCreateTime = null;

            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.NURSE_DATA, new Date(), WebserviceId.NURSE_DATA);
            messageService.save(messageLog);
            // 2、  解析
            MessageDto messageDto = XMLUtils.xpathToBean(xmlStr, EMRData.class, InterfaceName.NURSE_DATA);
            if (messageDto != null) {
                archiveMaster = archiveMasterRepository.findByInpNoAndVisitIdAndIsValid(messageDto.getInpNo(),messageDto.getVisitId(),0);
                if(archiveMaster != null){
                    masterId  = archiveMaster.getId();
                    // 区分类型
                    String reportType = messageDto.getType();
                    if (reportType != null) {
                        if (AliasName.NURSE_MAP.containsKey(reportType)) {
                            String subType = messageDto.getSubType();
                            if (AliasName.NURSE_MAP.containsKey(subType)) {
                                type = AliasName.NURSE_MAP.get(subType);
                            } else {
                                // 如果都不包含，但是有大类 那么归为其他记录
                                if (subType != null && !subType.equals("")) {
                                    type = AliasName.OTHER;
                                } else {
                                    type = AliasName.NURSE_MAP.get(reportType);
                                }
                            }
                            messageDto.setType(type);
                        }
                        if(! (archiveMaster.getArchiveState().equals("初审") || archiveMaster.getArchiveState().equals("已归档"))){
                            String addFlag = messageDto.getAddFlag();
                            if(Objects.equals(addFlag,"delete") || Objects.equals(addFlag,"update") || Objects.equals(addFlag,"insert")){
                                if(Objects.equals(messageDto.getIsOld(),"0")){
                                    if(messageDto.getType().equals("20")){
                                        messageDto.setType("8");
                                    }
                                    messageDto.setApplyId(messageDto.getInpNo() + "-" + messageDto.getVisitId()+"-nurse-"+messageDto.getCommitTime());
                                    remark = archiveDetailService.updateAllFlag(archiveMaster.getId(),messageDto.getApplyId(), messageDto.getSource());

                                }else if(Objects.equals(messageDto.getIsOld(),"1")){
                                    ArchiveDetail archiveDetail = archiveDetailService.isExit(archiveMaster.getId(), messageDto.getType(), messageDto.getSource(), messageDto.getApplyId());
                                    if(archiveDetail == null && !Objects.equals(addFlag,"insert")){
                                        remark = messageDto.getSubType()+"没有生成对应的文件不能"+addFlag;
                                    }else{
                                        if(Objects.equals(addFlag,"delete")){
                                            if(!archiveDetailService.delete(archiveDetail.getId())){
                                                remark = messageDto.getSubType()+"删除失败！";
                                            }else{
                                                remark = "ok";
                                            }
                                        }
                                    }
                                }else{
                                    remark = "数据有问题";
                                }
                            }else{
                                remark = "标识不包括insert/update/delete";
                            }

                        }else{
                            remark = "该病历已"+archiveMaster.getArchiveState()+"，不再接收";
                        }
                    }
                    // 保存消息从属表xmlCreateTime
                    xmlCreateTime = messageDto.getXmlCreateTime();
                }else{
                    remark =  "没有入院消息";
                }
            } else {
                remark =  "传过来的消息无法解析";
            }

            if(remark == null || remark.equals("ok") ){
                result = 1;
                flag = true;
                patientMainStr = JSON.toJSONString(new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId()), SerializerFeature.WriteMapNullValue);
            }

            // 4、判断是否成功  失败 的原因 我们插入报错 然后无法解析xml 传入参数为null
            outContent = AnalysisService.getReturnResult(flag,remark);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(masterId,outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type,remark);
            messageService.save(messageLog);
            if( remark == null && flag){
                messageSubordinateService.save(new MessageSubordinate(messageLog.getId(), patientMainStr, JSON.toJSONString(messageLog)));
            }
        }catch (Exception e){
            // 生成一个临时文件
            try {
                logger.error("消息出错，请检查消息内容，错误详情:{},消息所在位置：{}",e.getMessage(), FileUtils.createFile("NurseData",null,xmlStr));
            } catch (IOException e1) {
                return outContent;
            }
            return outContent;
        }
        return outContent;
    }

    @Override
    public String DoctorData(String xmlStr) {
        String outContent = "失败";
        try {
            // 1、定义变量
            boolean flag = false;
            Integer result = 0;
            String type = "", patientMainStr = null,remark = null,masterId = null;
            ArchiveMaster archiveMaster ;
            long startTime = System.currentTimeMillis();
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.DOCTOR_DATA, new Date(),WebserviceId.DOCTOR_DATA);
            messageService.save(messageLog);
            // 2、  解析
            MessageDto messageDto = XMLUtils.xpathToBean(xmlStr, EMRData.class, InterfaceName.DOCTOR_DATA);
            if (messageDto != null) {
                archiveMaster = archiveMasterRepository.findByInpNoAndVisitIdAndIsValid(messageDto.getInpNo(),messageDto.getVisitId(),0);
                if(archiveMaster != null) {
                    masterId = archiveMaster.getId();
                    // 区分类型
                    String reportType = messageDto.getType();
                    if (reportType != null) {
                        // 分配类型
                        if (AliasName.DOCTOR_MAP.containsKey(reportType)) {
                            String subType = messageDto.getSubType();
                            if (AliasName.DOCTOR_MAP.containsKey(subType)) {
                                type = AliasName.DOCTOR_MAP.get(subType);
                            } else {
                                // 如果都不包含，但是有大类 那么归为其他记录
                                if (subType != null && !subType.equals("")) {
                                    type = AliasName.OTHER;
                                } else {
                                    type = AliasName.DOCTOR_MAP.get(reportType);
                                }
                            }
                            messageDto.setType(type);
                        }

                        if(! (archiveMaster.getArchiveState().equals("初审") || archiveMaster.getArchiveState().equals("已归档")   )){
                            String addFlag = messageDto.getAddFlag();
                            if(Objects.equals(addFlag,"delete") || Objects.equals(addFlag,"update")
                                    || Objects.equals(addFlag,"insert") ){
                                if(Objects.equals(messageDto.getIsOld(),"0")){
                                    messageDto.setApplyId(messageDto.getInpNo() + "-" + messageDto.getVisitId()+"-doctor-"+messageDto.getCommitTime());
                                    remark = archiveDetailService.updateAllFlag(archiveMaster.getId(),messageDto.getApplyId(), messageDto.getSource());

                                }else if(Objects.equals(messageDto.getIsOld(),"1")){
                                    ArchiveDetail archiveDetail = archiveDetailService.isExit(archiveMaster.getId(), messageDto.getType(), messageDto.getSource(), messageDto.getApplyId());

                                    if(archiveDetail == null && !Objects.equals(addFlag,"insert") ){
                                        remark = messageDto.getSubType()+"没有生成对应的文件不能"+addFlag;
                                    }else{
                                        if(Objects.equals(addFlag,"delete")){
                                            if(!archiveDetailService.delete(archiveDetail.getId())){
                                                remark = messageDto.getSubType()+"删除失败！";
                                            }else{
                                                remark = "ok";
                                            }
                                        }
                                    }
                                }else{
                                    remark = "数据有问题";
                                }
                            }else{
                                remark = "标识不包括insert/update/delete";
                            }

                        }else{
                            remark = "该病历已"+archiveMaster.getArchiveState()+"，不再接收";
                        }
                    }
                    xmlCreateTime = messageDto.getXmlCreateTime();
                }else{
                    remark = "没有入院消息。。";
                }
            } else {
                remark = "传过来的消息无法解析。。";
            }

            if(remark == null || remark.equals("ok")){
                result = 1;
                flag = true;
                patientMainStr = JSON.toJSONString(new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId()), SerializerFeature.WriteMapNullValue);
            }

            // 4、判断是否成功  失败 的原因 我们插入报错 然后无法解析xml 传入参数为null
            outContent = AnalysisService.getReturnResult(flag,remark);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(masterId,outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type,remark);
            messageService.save(messageLog);
            if( remark == null && flag){
                messageSubordinateService.save(new MessageSubordinate(messageLog.getId(), patientMainStr, JSON.toJSONString(messageLog)));
            }
        }catch (Exception e){
            // 生成一个临时文件
            try {
                logger.error("消息出错，请检查消息内容，错误详情:{},消息所在位置：{}",e.getMessage(), FileUtils.createFile("DoctorData",null,xmlStr));
            } catch (IOException e1) {
                return outContent;
            }
            return outContent;
        }
        return outContent;
    }

    @Override
    public String ScanningFile(String xmlStr) {
        MessageScanning scanning = new MessageScanning();
        ArchiveMaster archiveMaster = null;
        Integer status = 2;
        scanning.setContent(xmlStr);
        messageScanningRepository.save(scanning);
        MessageDto messageDto = new MessageDto();

        String outContent = "失败",remark = null;
        try {
            boolean flag = false;
            messageDto = XMLUtils.xpathToBean(xmlStr, EMRData.class, InterfaceName.SCANNING_FILE);
            if (messageDto != null) {
                archiveMaster = archiveMasterService.findByInpNoAndVisitIdAndIsValid(messageDto.getInpNo(),messageDto.getVisitId());
                if(archiveMaster != null){
                    remark = analysisService.handlePdfFile(messageDto,archiveMaster);
                    if(remark == null){
                        status =1;
                        flag = true;
                        outContent ="成功";
                    }
                }else{
                    remark = "没有患者信息";
                }
            } else {
                remark = "传过来的消息无法解析";
            }
        }catch (Exception e){
            remark = e.toString();
            logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e,e.getStackTrace()[0]);
        }

        if(remark != null){
            remark = remark+"~"+new Date().toString();
        }

        scanning.setAssortId(messageDto.getType());
        scanning.setStatus(status);
        scanning.setRemark(remark);
        scanning.setMasterId(archiveMaster.getId());
        scanning.setApplyId(messageDto.getApplyId());
        messageScanningRepository.save(scanning);

        return outContent;
    }
}
