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.Identification;
import com.ann.demo.entity.constant.InterfaceName;
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.entity.normalEntity.*;
import com.ann.demo.interfaces.HomepageDictionary;
import com.ann.demo.service.*;
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.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 MessageService messageService;

    @Autowired
    private MedicalRecordHomepageCacheService medicalRecordHomepageCacheService;

    @Autowired
    private MessageSubordinateService messageSubordinateService;

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private ArchiveDetailService archiveDetailService;

    @Autowired
    ExamApplyService examApplyService;

    @Override
    public String HIPMessageServer(String action, String message) {
        String result = "";
        try {
            if (action != null && message != null && !(message.equals("") && action.equals(""))) {
                switch (action) {
                    case InterfaceName.PARAMETER_ADMISSION:
                        // 入院
                        result = analysisService.getHIPMessageServerResult(message, ArchiveMaster.class, InterfaceName.PARAMETER_ADMISSION);
                        break;
                    case InterfaceName.PARAMETER_DISCHARGE:
                        // 出院
                        result = analysisService.getHIPMessageServerResult(message, ArchiveMaster.class, InterfaceName.PARAMETER_DISCHARGE);
                        break;
                    case InterfaceName.PARAMETER_TRANSFER:
                        // 转科
                        result = analysisService.getHIPMessageServerResult(message, ArchiveMaster.class, InterfaceName.PARAMETER_TRANSFER);
                        break;
                    case InterfaceName.PARAMETER_CANCELLATION_DISCHARGE:
                        // 取消入院
                        result = analysisService.getHIPMessageServerResult(message, ArchiveMaster.class, InterfaceName.PARAMETER_CANCELLATION_DISCHARGE);
                        break;
                    case InterfaceName.PARAMETER_PATIENT_UPDATE:
                        // 患者信息更新
                        result = analysisService.getHIPMessageServerResult(message, ArchiveMaster.class, InterfaceName.PARAMETER_PATIENT_UPDATE);
                        break;
                }
            }
        }catch (Exception e){
            return  "";
        }
        // ---------------------------------------这里捕捉 参数为空
        return result;
    }

    @Override
    public String InpSummary(String xmlStr) {
        String outContent = "失败";
        try {
            // 1、定义变量
            long startTime = System.currentTimeMillis();
            boolean flag = false;
            Integer result = 0;
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.INP_SUMMARY, new Date());
            MedicalRecordHomepageCache medicalRecordHomepageCache = null;
            // if(messageService.countByInputContentAndInterfaceName(xmlStr,InterfaceName.INP_SUMMARY) == 0){
            messageService.save(messageLog);
            // 2、  解析
            MedicalRecordHomepage medicalRecordHomepage = XMLUtils.xmlStrToObject1(xmlStr, MedicalRecordHomepage.class);
            if (medicalRecordHomepage != null) {
                medicalRecordHomepageCache = medicalRecordHomepageCacheService.handleMedicalRecordHomepageCache(medicalRecordHomepage);
                if (medicalRecordHomepageCache != null) {
                    if (medicalRecordHomepageCacheService.save(medicalRecordHomepageCache)) {
                        flag = true;
                        result = 1;
                    } else {
                        messageLog.setRemark("已保存");
                    }
                }else{
                    messageLog.setRemark("没有入院信息。。。");
                }
            }else{
                messageLog.setRemark("消息解析错误。。。");
            }

            outContent = AnalysisService.getReturnResult(flag);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(outContent, result, medicalRecordHomepageCache == null ? null : JSON.toJSONString(medicalRecordHomepageCache), xmlCreateTime, (endTime - startTime), new Date(), AliasName.MEDICAL_RECORD_HOMEPAGE);
            messageService.save(messageLog);
            logger.info("-----------------------病案首页总用时长:" + (endTime - startTime) + "-------------------------");
        }catch (Exception e){
            try {
                outContent = AnalysisService.getReturnResult(false);
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e,e.getStackTrace()[0]);
            } catch (Exception ex) {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,ex,ex.getStackTrace()[0]);
            }
        }
        return outContent;
    }

    @Override
    public String handNumbnessReport(String xmlStr) {
        String outContent = null;
        try {
            // 手麻系统 判断消息是否传过  存入消息  然后解析消息  然后存到附属表
            // 1、定义变量
            boolean flag = false;
            Integer result = 0;
            String type = "", patientMainStr = null,archiveMasterId = null;
            long startTime = System.currentTimeMillis();
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.HANDNUMBNESS_REPORT, new Date());
            messageService.save(messageLog);

            // 2、  解析
            MessageDto messageDto = XMLUtils.xpathToBean(xmlStr, HandNumbnessReport.class, InterfaceName.HANDNUMBNESS_REPORT);
            if (messageDto != null) {
                archiveMasterId = messageService.getArchiveMasterId(messageDto.getInpNo(), messageDto.getVisitId());
                if(archiveMasterId != null){
                    // 保存消息从属表
                    patientMainStr = JSON.toJSONString(new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId()), SerializerFeature.WriteMapNullValue);
                    if (messageDto.getType().equals("麻醉单")) {
                        type = AliasName.HANDNUMBNESS_REPORT;
                    } else {
                        type = AliasName.OTHER;
                    }
                    messageDto.setType(type);
                    result = 1;
                    flag = true;
                    xmlCreateTime = messageDto.getXmlCreateTime();
                }else{
                    messageLog.setRemark("没有入院消息。。");
                }

            } else {
                messageLog.setRemark("传过来的消息无法解析。。");
            }

            // 4、判断是否成功  失败 的原因 我们插入报错 然后无法解析xml 传入参数为null
            outContent = AnalysisService.getReturnResult(flag);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type);
            messageService.save(messageLog);
            if (flag) {
                messageSubordinateService.save(new MessageSubordinate(messageLog.getId(), patientMainStr, JSON.toJSONString(messageLog)));
            }
            logger.info("-----------------------麻醉记录单总用时长:" + (endTime - startTime) + "-------------------------");
        }catch (Exception e){
            try {
                outContent = AnalysisService.getReturnResult(false);
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e,e.getStackTrace()[0]);
            } catch (Exception ex) {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,ex,ex.getStackTrace()[0]);
            }
        }
        return outContent;
    }

    @Override
    public String ICUReport(String xmlStr) {
        String outContent = "失败";
        try {
            // 1、定义变量
            long startTime = System.currentTimeMillis();
            boolean flag = false;
            Integer result = 0;
            String type = "", patientMainStr = null,archiveMasterId = null;
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.ICU_REPORT, new Date());
            messageService.save(messageLog);
            // 2、  解析
            MessageDto messageDto = XMLUtils.xpathToBean(xmlStr, ICUReport.class, InterfaceName.ICU_REPORT);
            if (messageDto != null) {
                archiveMasterId = messageService.getArchiveMasterId(messageDto.getInpNo(), messageDto.getVisitId());
                if(archiveMasterId != null){
                    // 保存消息从属表
                    patientMainStr = JSON.toJSONString(new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId()), SerializerFeature.WriteMapNullValue);
                    xmlCreateTime = messageDto.getXmlCreateTime();
                    result = 1;
                    type = messageDto.getType();
                    flag = true;
                }else{
                    messageLog.setRemark("没有入院消息。。");
                }
            } else {
                messageLog.setRemark("传过来的消息无法解析。。");
            }
            // 4、判断是否成功  失败 的原因 我们插入报错 然后无法解析xml 传入参数为null
            outContent = AnalysisService.getReturnResult(flag);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type);
            messageService.save(messageLog);

            if (flag) {
                messageSubordinateService.save(new MessageSubordinate(messageLog.getId(), patientMainStr, JSON.toJSONString(messageLog)));
            }
            logger.info("-----------------------ICU报告总用时长:" + (endTime - startTime) + "-------------------------");
        }catch (Exception e){
            try {
                outContent = AnalysisService.getReturnResult(false);
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e,e.getStackTrace()[0]);
            } catch (Exception ex) {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,ex,ex.getStackTrace()[0]);
            }
        }
        return outContent;
    }

    @Override
    public String BloodTransfusionUrl(String xmlStr) {
        String outContent = "失败";
        try {
            // 1、定义变量
            boolean flag = false;
            Integer result = 0;
            String type = "";
            String patientMainStr = null, remark = null,archiveMasterId = null;
            long startTime = System.currentTimeMillis();
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.BLOODAPPLY_REPORT, new Date());

            messageService.save(messageLog);
            // 2、  解析
            MessageDto messageDto = XMLUtils.xpathToBean(xmlStr, BloodApply.class, InterfaceName.BLOODAPPLY_REPORT);
            if (messageDto != null) {
                archiveMasterId = messageService.getArchiveMasterId(messageDto.getInpNo(), messageDto.getVisitId());
                if(archiveMasterId != null){


                    // 判断是否作废
                    if (Objects.equals(messageDto.getAddFlag(), "DELETE")) {
                        remark = archiveDetailService.updateFlag(messageDto.getApplyId());
                    } else {
                        // 保存消息从属表
                        PatientMainDto patientMainDto = new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId());
                        patientMainStr = JSON.toJSONString(patientMainDto, SerializerFeature.WriteMapNullValue);
                    }

                    if (remark != null) {
                        messageLog.setRemark(remark);
                    } else {
                        result = 1;
                        flag = true;
                    }
                }else{
                    messageLog.setRemark("没有入院消息。。");
                }
                xmlCreateTime = messageDto.getXmlCreateTime();
                type = messageDto.getType();
            } else {
                messageLog.setRemark("传过来的消息无法解析。。");
            }

            outContent = AnalysisService.getReturnResult(flag);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type);
            messageService.save(messageLog);
            if (flag) {
                messageSubordinateService.save(new MessageSubordinate(messageLog.getId(), patientMainStr, JSON.toJSONString(messageLog)));
            }
            logger.info("-----------------------输血单总用时长:" + (endTime - startTime) + "-------------------------");
        }catch (Exception e){
            try {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e,e.getStackTrace()[0]);
                return AnalysisService.getReturnResult(false);
            } catch (Exception e1) {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e1,e1.getStackTrace()[0]);
            }
        }
        return outContent;
    }

}
