package com.ann.demo.service;

import com.alibaba.fastjson.JSON;
import com.ann.demo.entity.constant.AliasName;
import com.ann.demo.entity.constant.InterfaceName;
import com.ann.demo.entity.filing.dto.MessageDto;
import com.ann.demo.entity.interfaceEntity.ArchiveMaster;
import com.ann.demo.entity.interfaceEntity.ExamApply;
import com.ann.demo.entity.interfaceEntity.InspectionApply;
import com.ann.demo.entity.interfaceEntity.MessageLog;
import com.ann.demo.entity.normalEntity.MedicalRecordHomepage;
import com.ann.demo.entity.normalEntity.MedicalRecordHomepageCache;
import com.ann.demo.entity.normalEntity.OutPara;
import com.ann.demo.utils.XMLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;

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

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

    @Autowired
    MessageService messageService;

    @Autowired
    MessageSubordinateService messageSubordinateService;

    @Autowired
    ArchiveMasterService archiveMasterService;

    @Autowired
    ExamApplyService examApplyService;

    @Autowired
    MedicalRecordHomepageCacheService medicalRecordHomepageCacheService;

    /**
     * 2019-7-8
     *
     * @Param xmlStr 需要解析的字符串
     * @Param tClass 被解析字符串的实体类
     * @Param parameter 如果是报告 携带参数
     * 返回返回参数xml
     */
    public String getHIPMessageServerResult(String message, Class tClass, String parameter) throws Exception{
        long startTime = System.currentTimeMillis();
        String textContent = "成功啦~", type = "", typeCodeValue = "AE", outContent = "", patientMainStr = "";
        Date xmlCreateTime = null;
        Integer result = 0;
        long endTime = 0;

        MessageLog messageLog = new MessageLog(message, InterfaceName.HIP_MESSAGE_SERVER, new Date());
        // 只要没有传过 才会插入新的
        messageService.save(messageLog);
        MessageDto messageDto = XMLUtils.xpathToBean(message, tClass, parameter);
        if (messageDto != null) {
            String textContentTemp = null;
            if (Objects.equals(messageDto.getEntity(), ArchiveMaster.class.getName())) { // 患者信息
                ArchiveMaster archiveMaster = JSON.parseObject(messageDto.getObject().toString(), ArchiveMaster.class);
                textContentTemp = changeArchiveMaster(archiveMaster, messageDto.getAddFlag(), messageDto.getType());
            }
            if (textContentTemp != null) {
                textContent = textContentTemp;
            } else {
                xmlCreateTime = messageDto.getXmlCreateTime();
                type = messageDto.getType();
                typeCodeValue = "AA";
                result = 1;
            }
        } else {
            textContent = "传过来的消息无法解析。。";
        }

        outContent = XMLUtils.generateV3XmlStr(typeCodeValue, textContent);

        endTime = System.currentTimeMillis();
        messageLog.setValue(outContent, result, messageDto == null ? "" : JSON.toJSONString(messageDto), xmlCreateTime, (endTime - startTime), new Date(), type, textContent);
        messageService.save(messageLog);

        logger.info("-----------------------" + type + ":" + (endTime - startTime) + "-------------------------");
        return outContent;
    }

    private String changeArchiveMaster(ArchiveMaster archiveMaster, String changeStatus, String aliasName) {
        String textContent = null;
        if (changeStatus != null || aliasName != null) {
            String archiveMasterId = archiveMasterService.findArchiveMasterId(archiveMaster.getPatientId(), archiveMaster.getVisitId(), archiveMaster.getInpNo());
            if (archiveMasterId != null) {
                // 如果不是新增 都会查询id
                archiveMaster.setId(archiveMasterId);
                if (Objects.equals(changeStatus, "update")) {   // 更新患者住院信息
                    archiveMasterService.save(archiveMaster);
                } else if (Objects.equals(changeStatus, "delete")) {  // 取消入院
                    archiveMasterService.updateArchiveMasterValid(archiveMasterId);
                }
                if (aliasName != null) {
                    if (aliasName.equals(AliasName.TRANSFER_RECORD)) {  // 转科
                        archiveMasterService.transferDepartment(archiveMaster);
                    } else if (aliasName.equals(AliasName.DISCHARGE_RECORD)) {  // 出院
                        archiveMasterService.discharge(archiveMaster);
                    }else if(aliasName.equals(AliasName.PATIENT_UPDATE)){
                        if(!archiveMasterService.updateArchiveMaster(archiveMaster)){
                            textContent = "患者更新失败";
                        }
                    }
                }
            } else {
                if (Objects.equals(changeStatus, "new")) {  // 新增患者住院信息
                    archiveMasterService.save(archiveMaster);
                } else {
                    textContent = "没有入院信息";
                }
            }
        } else {
            textContent = "信息解析错误";
        }
        return textContent;
    }


    private String changeExamApply(ExamApply examApply) {
        String textContent = null;

        Integer count = examApplyService.countExamApply(examApply.getApplyId());
        // 如果 id存在 说明已经存了 就不能再存了
        if (count > 0) {
            if (Objects.equals(examApply.getResult(), "delete")) {
                if (!examApplyService.updateExamApplyIsValid(examApply.getApplyId())) {
                    textContent = "检查申请单删除失败了";
                }
            } else {
                textContent = "已经存在申请单了";
            }
        } else {
            if (Objects.equals(examApply.getResult(), "new")) {
                // 转换
                if (examApply.getReportType() != null) {
                    switch (examApply.getReportType()) {
                        case "病理":
                            examApply.setReportType(AliasName.PATHOLOGY_REPORT);
                            break;
                        case "超声":
                            examApply.setReportType(AliasName.ULTRASONIC_REPORT);
                            break;
                        case "心电":
                            examApply.setReportType(AliasName.EKG_REPORT);
                            break;
                        case "放射":
                            examApply.setReportType(AliasName.RADIATION_REPORT);
                            break;
                    }
                }

                examApplyService.save(examApply);
            } else {
                textContent = "该申请单不存在:" + examApply.getApplyId();
            }
        }
        return textContent;
    }

    private String changeApply(ExamApply examApply) {
        String textContent = null;
        ExamApply examApplyTemp = examApplyService.findExamApply(examApply.getApplyId());
        if(examApplyTemp != null){
            if (Objects.equals(examApply.getResult(), "delete")) {
                if (!examApplyService.updateExamApplyIsValid(examApply.getApplyId())) {
                    textContent = "申请单删除失败了";
                }
            }else if (Objects.equals(examApply.getIsOpen(), "F")) {
                examApplyTemp.setIsValid(1);
                examApplyTemp.setIsOpen("F");
                examApplyService.save(examApplyTemp);
            }else {
                textContent = "该申请单已存在";
            }
        }else{
            if (Objects.equals(examApply.getResult(), "new")) {
                if (examApply.getReportType() != null) {
                    switch (examApply.getReportType()) {
                        case "病理":
                            examApply.setReportType(AliasName.PATHOLOGY_REPORT);
                            break;
                        case "超声":
                            examApply.setReportType(AliasName.ULTRASONIC_REPORT);
                            break;
                        case "心电":
                            examApply.setReportType(AliasName.EKG_REPORT);
                            break;
                        case "放射":
                            examApply.setReportType(AliasName.RADIATION_REPORT);
                            break;
                        default:
                            examApply.setReportType(AliasName.INSPECTION_REPORT);
                            break;
                    }
                }
                examApplyService.save(examApply);
            } else {
                textContent = "该申请单不存在";
            }
        }
        return textContent;
    }

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


    public void delete() {
        try {
            String type = "", patientMainStr = "", json = "";
            MessageDto messageDto = null;
            System.out.println("我开始查询数据了。。。。");
            List<MessageLog> messageLogs = messageService.findAllMessage();
            for (MessageLog messageLog : messageLogs) {
                MedicalRecordHomepage medicalRecordHomepage = XMLUtils.xmlStrToObject1(messageLog.getInputContent(), MedicalRecordHomepage.class);
                if (medicalRecordHomepage != null) {
                    MedicalRecordHomepageCache medicalRecordHomepageCache = medicalRecordHomepageCacheService.handleMedicalRecordHomepageCache(medicalRecordHomepage);
                    if (medicalRecordHomepageCache != null) {
                        if (medicalRecordHomepageCacheService.save(medicalRecordHomepageCache)) {
                        }
                    }
                }
            }
        }catch (Exception e){

        }
    }


}
