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.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.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;

/**
 * @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 MessageSubordinateService messageSubordinateService;

    @Autowired
    private ArchiveDetailService archiveDetailService;

    @Autowired
    private ArchiveMasterRepository archiveMasterRepository;

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

            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.NURSE_DATA, new Date());
            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){

                    // 区分类型
                    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);
                        }
                        // 根据住院次数 患者id 查询是否存在记录 如果存在 那么就作废
                        messageDto.setApplyId(messageDto.getInpNo() + "-" + messageDto.getVisitId()+"-nurse-"+messageDto.getCommitTime());
                        if(!(archiveMaster.getArchiveState().equals("初审") || archiveMaster.getArchiveState().equals("已归档")  ||
                                archiveMaster.getArchiveState().equals("复审退回")  )){
                            String temp = archiveDetailService.updateAllFlag(messageDto.getApplyId(), messageDto.getSource());
                            if(temp != null){
                                messageLog.setRemark(temp);
                            }else{
                                patientMainStr = JSON.toJSONString(new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId()), SerializerFeature.WriteMapNullValue);
                                result = 1;
                                flag = true;
                            }
                        }else{
                            messageLog.setRemark("该病历已"+archiveMaster.getArchiveState()+"，不再接收");
                        }
                    }
                    // 保存消息从属表
                    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 {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e,e.getStackTrace()[0]);
                return AnalysisService.getReturnResult(false);
            } catch (Exception e1) {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e1,e1.getStackTrace()[0]);
                return outContent;
            }
        }
        return outContent;
    }

    @Override
    public String DoctorData(String xmlStr) {
        String outContent = "失败";
        try {
            // 1、定义变量
            boolean flag = false;
            Integer result = 0;
            String type = "", patientMainStr = null;
            ArchiveMaster archiveMaster ;
            long startTime = System.currentTimeMillis();
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.DOCTOR_DATA, new Date());
            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) {
                    // 区分类型
                    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);
                        }
                        // 根据住院次数 患者id 查询是否存在记录 如果存在 那么就作废
                        messageDto.setApplyId(messageDto.getInpNo() + "-" + messageDto.getVisitId() + "-doctor-" + messageDto.getCommitTime());
                        if(!(archiveMaster.getArchiveState().equals("初审") || archiveMaster.getArchiveState().equals("已归档")  ||
                                archiveMaster.getArchiveState().equals("复审退回")  )){
                            String temp = archiveDetailService.updateAllFlag(messageDto.getApplyId(), messageDto.getSource());
                            if (temp != null) {
                                messageLog.setRemark(temp);
                            } else {
                                result = 1;
                                flag = true;
                                patientMainStr = JSON.toJSONString(new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId()), SerializerFeature.WriteMapNullValue);
                            }
                        }else{
                            messageLog.setRemark("该病历已"+archiveMaster.getArchiveState()+"，不再接收");
                        }
                    }
                    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 {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e,e.getStackTrace()[0]);
                return AnalysisService.getReturnResult(false);
            } catch (Exception e1) {
                logger.error("出错咯！错误信息为{}，以及错误行数为:{}" ,e1,e1.getStackTrace()[0]);
            }
        }
        return outContent;
    }
}
