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.constant.WebserviceId;
import com.ann.demo.entity.filing.ArchiveDetail;
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 ArchiveDetailService archiveDetailService;

    @Autowired
    private ArchiveMasterService archiveMasterService;


    @Override
    public String InpSummary(String xmlStr) {
        String outContent = "失败";
        String remark = null;
        String masterId = null;
        try {
            // 1、定义变量
            long startTime = System.currentTimeMillis();
            boolean flag = false;
            Integer result = 2;
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.INP_SUMMARY, new Date(),WebserviceId.INP_SUMMARY);
            MedicalRecordHomepageCache medicalRecordHomepageCache = null;
            messageService.save(messageLog);
            // 2、  解析
            MedicalRecordHomepage medicalRecordHomepage = XMLUtils.xmlStrToObject1(xmlStr, MedicalRecordHomepage.class);
            if (medicalRecordHomepage != null) {
                if(medicalRecordHomepage.getCommonTable() !=  null ){
                    if(medicalRecordHomepage.getCommonTable().getYZY001() != null &&
                            medicalRecordHomepage.getCommonTable().getYZY002() != null){
                        ArchiveMaster archiveMaster = archiveMasterService.findByPatientIdAndVisitIdAndIsValid(medicalRecordHomepage.getCommonTable().getYZY001() , medicalRecordHomepage.getCommonTable().getYZY002() );
                        if(archiveMaster !=  null){
                            masterId = archiveMaster.getId();
                            medicalRecordHomepageCache = medicalRecordHomepageCacheService.handleMedicalRecordHomepageCache(archiveMaster.getId(),medicalRecordHomepage);
                            if (medicalRecordHomepageCache != null) {
                                if (medicalRecordHomepageCacheService.save(medicalRecordHomepageCache)) {
                                    flag = true;
                                    result = 1;
                                } else {
                                    remark = "病案首页缓存保存出错";
                                }
                            } else {
                                remark = "构建病案首页缓存出错";
                            }
                        }else{
                            remark = "患者ID或者住院次数为空";
                        }
                    }else{
                        remark = "没有入院信息";
                    }
                }else{
                    remark = "解析公共表失败";
                }
            }else{
                remark = "消息解析错误";
            }

            messageLog.setRemark(remark);
            outContent = AnalysisService.getReturnResult(flag,remark);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(masterId,outContent, result, medicalRecordHomepageCache == null ? null : JSON.toJSONString(medicalRecordHomepageCache), xmlCreateTime, (endTime - startTime), new Date(), AliasName.MEDICAL_RECORD_HOMEPAGE,remark);
            messageService.save(messageLog);
            logger.info("-----------------------病案首页总用时长:" + (endTime - startTime) + "-------------------------");
        }catch (Exception e){
            try {
                outContent = AnalysisService.getReturnResult(false,e.getMessage());
                logger.error("当前参数：{},报错信息：{}","InpSummary",e.getMessage());
            } catch (Exception ex) {
                logger.error("当前参数：{},报错信息：{}","InpSummary",ex.getMessage());
            }
        }
        return outContent;
    }

    @Override
    public String handNumbnessReport(String xmlStr) {
        String outContent = null;
        String remark = null;
        try {
            // 手麻系统 判断消息是否传过  存入消息  然后解析消息  然后存到附属表
            // 1、定义变量
            boolean flag = false;
            Integer result = 2;
            String type = "", patientMainStr = null,archiveMasterId = null;
            long startTime = System.currentTimeMillis();
            Date xmlCreateTime = null;
            MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.HANDNUMBNESS_REPORT, new Date(),WebserviceId.HANDNUMBNESS_REPORT);
            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){
                    messageLog.setMasterId(archiveMasterId);
                    // 保存消息从属表
                    patientMainStr = JSON.toJSONString(new PatientMainDto(messageDto.getInpNo(), messageDto.getVisitId()), SerializerFeature.WriteMapNullValue);
                    result = 1;
                    flag = true;
                    type = messageDto.getType();
                    xmlCreateTime = messageDto.getXmlCreateTime();
                }else{
                    remark = "没有入院消息";
                }

            } else {
                remark = "传过来的消息无法解析";
            }

            // 4、判断是否成功  失败 的原因 我们插入报错 然后无法解析xml 传入参数为null
            outContent = AnalysisService.getReturnResult(flag,remark);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(archiveMasterId,outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type,remark);
            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,remark);
                logger.error("当前参数：{},报错信息：{}","handNumbnessReport",e.getMessage());
            } catch (Exception ex) {
                logger.error("当前参数：{},报错信息：{}","handNumbnessReport",ex.getMessage());
            }
        }
        return outContent;
    }

    @Override
    public String ICUReport(String xmlStr) {
        String outContent = "失败";
        String remark= null;
        MessageLog messageLog = new MessageLog(xmlStr, InterfaceName.ICU_REPORT, new Date(), WebserviceId.ICU_REPORT);
        try {
            // 1、定义变量
            long startTime = System.currentTimeMillis();
            boolean flag = false;
            Integer result = 0;
            String type = "", patientMainStr = null,archiveMasterId = null;
            Date xmlCreateTime = null;
            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){
                    String addFlag = messageDto.getAddFlag();
                    messageDto.setApplyId(messageDto.getDetailType()+"~"+messageDto.getApplyId());
                    //3、做增删改 增删新增从属 删除不新增
                    if(Objects.equals(addFlag,"insert") || Objects.equals(addFlag,"update") || Objects.equals(addFlag,"delete")){
                        ArchiveDetail archiveDetail = archiveDetailService.isExit(archiveMasterId, messageDto.getType(), messageDto.getSource(), messageDto.getApplyId());
                        if(archiveDetail == null && !Objects.equals(addFlag,"insert")){
                            remark = messageDto.getDetailType()+"没有生成对应的文件不能"+ addFlag;
                        }else{
                            if(Objects.equals(addFlag,"delete")){
                                if(!archiveDetailService.delete(archiveDetail.getId())){
                                    remark = messageDto.getSubType()+"删除失败！";
                                }else{
                                    remark = "ok";
                                }
                            }
                        }
                    }else{
                        remark = "标识不包括insert/update/delete";
                    }

                    xmlCreateTime = messageDto.getXmlCreateTime();
                    type = messageDto.getType();
                }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);
            }

            outContent = AnalysisService.getReturnResult(flag,remark);
            long endTime = System.currentTimeMillis();
            messageLog.setValue(archiveMasterId,outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type,remark);
            // 4、更新消息表
            messageService.save(messageLog);
            // 5、根据条件插入消息从属表
            if (remark == null && flag) {
                messageSubordinateService.save(new MessageSubordinate(messageLog.getId(), patientMainStr, JSON.toJSONString(messageLog)));
            }
        }catch (Exception e){
            try {
                outContent = AnalysisService.getReturnResult(false,remark);
                logger.error("当前参数：{},报错信息：{}","ICUReport",e.getMessage());
            } catch (Exception ex) {
                logger.error("当前参数：{},报错信息：{}","ICUReport",ex.getMessage());
            }
        }
        return outContent;
    }

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

            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) {
                        result = 1;
                        flag = true;
                    }
                }else{
                    remark = "没有入院消息";
                }
                xmlCreateTime = messageDto.getXmlCreateTime();
                type = messageDto.getType();
            } else {
                remark = "传过来的消息无法解析";
            }

            outContent = AnalysisService.getReturnResult(flag,remark);
            //  更新日志表
            long endTime = System.currentTimeMillis();
            messageLog.setValue(archiveMasterId,outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type,remark);
            messageService.save(messageLog);
            if (flag) {
                messageSubordinateService.save(new MessageSubordinate(messageLog.getId(), patientMainStr, JSON.toJSONString(messageLog)));
            }
        }catch (Exception e){
            try {
                logger.error("当前参数：{},报错信息：{}","BloodTransfusionUrl",e.getMessage());
                return AnalysisService.getReturnResult(false,remark);
            } catch (Exception ex) {
                logger.error("当前参数：{},报错信息：{}","BloodTransfusionUrl",ex.getMessage());
            }
        }
        return outContent;
    }

}
