package com.diagbot.facade.data;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.diagbot.dto.AnalyzeRunDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.data.AHomePageDTO;
import com.diagbot.entity.BasDoctorInfo;
import com.diagbot.entity.BehospitalInfo;
import com.diagbot.entity.HomePage;
import com.diagbot.entity.MedPacsResult;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.BehospitalInfoFacade;
import com.diagbot.service.impl.HomePageServiceImpl;
import com.diagbot.util.*;
import com.diagbot.vo.AnalyzeRunVO;
import com.diagbot.vo.data.*;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AHomePageFacade extends HomePageServiceImpl{

    @Autowired
    @Qualifier("homePageServiceImpl")
    private HomePageServiceImpl homePageService;

    @Autowired
    private AHomeDiagnoseInfoFacade aHomeDiagnoseInfoFacade;

    @Autowired
    private AHomeOperationInfoFacade aHomeOperationInfoFacade;

    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;

    @Autowired
    private ReadProperties readProperties;

    @Autowired
    private AMedAbnormalInfoFacade aMedAbnormalInfoFacade;
    @Autowired
    private SendDataDealFacade sendDataDealFacade;

    @Autowired
    private ABasDoctorInfoFacade aBasDoctorInfoFacade;

    @Value("${log_switch.enable}")
    private boolean logSwitch;

    @Value("${xml_analyse.enable}")
    private boolean xmlAnalyse;

    private TZDBConn tzDBConn = new TZDBConn();

    /**
     * 同步前一天病案首页
     */
    public void executeHomePage() {
        //String sql="select * from br_rechome where cjcxrq>=dateadd(day,-2,getdate()) and cjcxrq<=getdate()";
        //同步前一天的数据
        String sql="select * from br_rechome where cjcxrq>=(select CONVERT(varchar,GETDATE()-2,23)) and cjcxrq<(select CONVERT(varchar,GETDATE(),23))";
        List<HomePage> homePageList = tzDBConn.getHomePage(sql);
        /*
        int mod=Math.floorMod(homePageList.size(),500);
        int div=Math.floorDiv(homePageList.size(),500);
        for (int i = 0; i <= homePageList.size(); i++) {
            System.out.println((i-1)*500+"---"+(i*500));
            homePageList=homePageList.subList((i*500),(i+1)*500);
            execute(homePageList);
        }
        */
        execute(homePageList);
    }

    /**
     * 运行质控-验证数据有效性
     * @param aHomePageIngVO
     * @return
     */
    public RespDTO<Map<String, Object>> executeHomePageIng(AHomePageIngVO aHomePageIngVO){
        if(aHomePageIngVO.getHomePages()!=null && aHomePageIngVO.getHomePages().size()>0){
            //验证数据有效性
            for (AHomePageVO aHomePageVO:aHomePageIngVO.getHomePages()) {
                /*if("".equals(aHomePageVO.getHomePageId())) {
                    return RespDTO.onError("请输入病案首页编号!");
                }else */if(aHomePageVO.getHospitalId()==null){
                    return RespDTO.onError("请输入医院编码!");
                }else if("".equals(aHomePageVO.getBehospitalCode())){
                    return RespDTO.onError("请输入病人住院编码!");
                }
                //出院诊断
                if(aHomePageVO.getLeaveDiags()!=null && aHomePageVO.getLeaveDiags().size()>0){
                    for (AHomeDiagnoseVO aHomeDiagnoseVO:aHomePageVO.getLeaveDiags()){
                        /*if("".equals(aHomeDiagnoseVO.getHomePageId())) {
                            return RespDTO.onError("出院诊断未输入病案首页编号!");
                        }else */if(aHomeDiagnoseVO.getHospitalId()==null){
                            return RespDTO.onError("出院诊断未输入医院编码!");
                        }else if("".equals(aHomeDiagnoseVO.getDiagnoseOrderNo())){
                            return RespDTO.onError("出院诊断未输入顺序号!");
                        }
                    }
                };

                //住院手术
                if(aHomePageVO.getOperations()!=null && aHomePageVO.getOperations().size()>0){
                    for (AHomeOperationVO aHomeOperationVO:aHomePageVO.getOperations()){
                        /*if("".equals(aHomeOperationVO.getHomePageId())) {
                            return RespDTO.onError("住院手术未输入病案首页编号!");
                        }else */if(aHomeOperationVO.getHospitalId()==null){
                            return RespDTO.onError("住院手术未输入医院编码!");
                        }else if("".equals(aHomeOperationVO.getOperationOrderNo())){
                            return RespDTO.onError("住院手术未输入顺序号!");
                        }
                    }
                }
            }

            //装载数据
            updateHomePageIng(aHomePageIngVO);

            //评分后返回结构体
            return homePageIng(aHomePageIngVO);

        }else{
            return RespDTO.onError("未接收到数据!");
        }
    }

    /**
     * 更新数据到数据库
     * @param aHomePageIngVO
     */
    public void updateHomePageIng(AHomePageIngVO aHomePageIngVO){
        try {
            List<HomePage> homePageList=Lists.newArrayList();
            aHomePageIngVO.getHomePages().stream().forEach(s->{
                HomePage homePage1 = this.getOne(new QueryWrapper<HomePage>()
                        .eq("behospital_code", s.getBehospitalCode()), false);
                if(homePage1 != null){
                    s.setHomePageId(homePage1.getHomePageId());
                }
                //初始化入参
                HomePage homePage=new HomePage();
                BeanUtil.copyProperties(s,homePage);
                if (StringUtil.isNotEmpty(s.getBirthday())){
                    homePage.setBirthday(DateUtil.parseDate(s.getBirthday()));
                }
                if (StringUtil.isNotEmpty(s.getBehospitalDate())){
                    homePage.setBehospitalDate(DateUtil.parseDateTime(s.getBehospitalDate()));
                }
                if (StringUtil.isNotEmpty(s.getLeaveHospitalDate())){
                    homePage.setLeaveHospitalDate(DateUtil.parseDateTime(s.getLeaveHospitalDate()));
                }
                if (StringUtil.isNotEmpty(s.getQcDate())){
                    homePage.setQcDate(DateUtil.parseDateTime(s.getQcDate()));
                }

                // 拆分年龄
                if (StringUtil.isNotEmpty(s.getAgeType())) {
                    List<String> ageTypeList = SplitUtil.splitAge(s.getAgeType());
                    for (String ageType : ageTypeList) {
                        String[] ageTypeArr = ageType.split(",");
                        if (ageTypeArr.length != 2) continue;
                        homePage.setAge(ageTypeArr[0]);
                        homePage.setAgeUnit(ageTypeArr[1]);
                    }
                }

                // 拆分新生儿年龄
                if (StringUtil.isNotBlank(s.getNewbornAgeUnit())) {
                    List<String> newbornAgeUnitList = SplitUtil.splitAge(s.getNewbornAgeUnit());
                    for (String newbornAgeUnit : newbornAgeUnitList) {
                        String[] newbornAgeUnitArr = newbornAgeUnit.split(",");
                        if (newbornAgeUnitArr.length != 2) continue;
                        if (newbornAgeUnitArr[1].equals("月")) {
                            homePage.setNewbornMonth(newbornAgeUnitArr[0]);
                        } else if (newbornAgeUnitArr[1].equals("天")) {
                            homePage.setNewbornDay(newbornAgeUnitArr[0]);
                        }
                    }
                }

                // 拆分新生儿出生体重
                if (StringUtil.isNotBlank(s.getNewbornWeightUnit())) {
                    List<String> newbornWeightUnitList = SplitUtil.splitWeight(s.getNewbornWeightUnit());
                    for (String newbornWeightUnit : newbornWeightUnitList) {
                        String[] newbornWeightUnitArr = newbornWeightUnit.split(",");
                        if (newbornWeightUnitArr.length != 2) continue;
                        homePage.setNewbornWeight(newbornWeightUnitArr[0]);
                    }
                }

                // 拆分新生儿入院体重
                if (StringUtil.isNotBlank(s.getNewbornBehospitalWeightUnit())) {
                    List<String> newbornBehospitalWeightUnitList = SplitUtil.splitWeight(s.getNewbornBehospitalWeightUnit());
                    for (String newbornBehospitalWeightUnit : newbornBehospitalWeightUnitList) {
                        String[] newbornBehospitalWeightUnitArr = newbornBehospitalWeightUnit.split(",");
                        if (newbornBehospitalWeightUnitArr.length != 2) continue;
                        homePage.setNewbornBehospitalWeight(newbornBehospitalWeightUnitArr[0]);
                    }
                }

                // 拆分总费用
                if(StringUtil.isNotBlank(s.getBehospitalFee())){
                    List<String> behospitalFeeList = SplitUtil.splitTotalFees(s.getBehospitalFee());
                    for(String fee : behospitalFeeList){
                        String[] feeArr = fee.split(",");
                        if(feeArr.length != 2) continue;
                        if(feeArr[0].equals("总费用")){
                            homePage.setTotalFee(feeArr[1]);
                        }else if(feeArr[0].equals("自付金额")){
                            homePage.setOwnFee(feeArr[1]);
                        }
                    }
                }

                // 拆分综合医疗服务类
                if (StringUtil.isNotBlank(s.getGeneralMedicalFee())) {
                    List<String> generalMedicalFeeList = SplitUtil.splitFees(s.getGeneralMedicalFee());
                    for (String fee : generalMedicalFeeList) {
                        String[] feeArr = fee.split(",");
                        if (feeArr.length != 2) continue;
                        if (feeArr[0].equals("一般医疗服务费")) {
                            homePage.setGeneralFee(feeArr[1]);
                        } else if (feeArr[0].equals("一般治疗服务费")) {
                            homePage.setServiceFee(feeArr[1]);
                        } else if (feeArr[0].equals("护理费")) {
                            homePage.setNurseFee(feeArr[1]);
                        } else if (feeArr[0].equals("其他费用")) {
                            homePage.setOtherFee(feeArr[1]);
                        }
                    }
                }

                // 拆分诊断类
                if(StringUtil.isNotBlank(s.getDiagnoseTypeFee())) {
                    List<String> diagnoseTypeFeeList = SplitUtil.splitFees(s.getDiagnoseTypeFee());
                    for (String diagnoseTypeFee : diagnoseTypeFeeList) {
                        String[] diagnoseTypeFeeArr = diagnoseTypeFee.split(",");
                        if (diagnoseTypeFeeArr.length != 2) continue;
                        if (diagnoseTypeFeeArr[0].equals("病理诊断费")) {
                            homePage.setPathologyFee(diagnoseTypeFeeArr[1]);
                        } else if (diagnoseTypeFeeArr[0].equals("实验室诊断费")) {
                            homePage.setLabFee(diagnoseTypeFeeArr[1]);
                        } else if (diagnoseTypeFeeArr[0].equals("影像学诊断费")) {
                            homePage.setPacsFee(diagnoseTypeFeeArr[1]);
                        } else if (diagnoseTypeFeeArr[0].equals("临床诊断项目费")) {
                            homePage.setClinicDiagnoseFee(diagnoseTypeFeeArr[1]);
                        }
                    }
                }

                // 拆分治疗类
                if(StringUtil.isNotBlank(s.getTreatFee())){
                    List<String> treatFeeList = SplitUtil.splitFees(s.getTreatFee());
                    for (String treatFee : treatFeeList) {
                        String[] treatFeeArr = treatFee.split(",");
                        if (treatFeeArr.length != 2) continue;
                        if (treatFeeArr[0].equals("非手术治疗项目费")) {
                            homePage.setNotOperationFee(treatFeeArr[1]);
                        } else if (treatFeeArr[0].equals("临床物理治疗费")) {
                            homePage.setClinicPhysicFee(treatFeeArr[1]);
                        } else if (treatFeeArr[0].equals("手术治疗费")) {
                            homePage.setOperationTreatFee(treatFeeArr[1]);
                        } else if (treatFeeArr[0].equals("麻醉费")) {
                            homePage.setAnaesthesiaFee(treatFeeArr[1]);
                        } else if (treatFeeArr[0].equals("手术费")) {
                            homePage.setOperationFee(treatFeeArr[1]);
                        }
                    }
                }

                // 拆分康复类
                if(StringUtil.isNotBlank(s.getHealthFee())){
                    List<String> healthFeeList = SplitUtil.splitFees(s.getHealthFee());
                    for (String healthFee : healthFeeList) {
                        String[] healthFeeArr = healthFee.split(",");
                        if (healthFeeArr.length != 2) continue;
                        if (healthFeeArr[0].equals("康复费")) {
                            homePage.setHealthTypeFee(healthFeeArr[1]);
                        }
                    }
                }

                // 拆分中医类
                if(StringUtil.isNotBlank(s.getChnFee())) {
                    List<String> chnFeeList = SplitUtil.splitFees(s.getChnFee());
                    for (String chnFee : chnFeeList) {
                        String[] chnFeeArr = chnFee.split(",");
                        if (chnFeeArr.length != 2) continue;
                        if (chnFeeArr[0].equals("中医治疗费")) {
                            homePage.setChnTreatFee(chnFeeArr[1]);
                        }
                    }
                }

                // 拆分西药类
                if (StringUtil.isNotBlank(s.getWesternFee())){
                    List<String> westernFeeList = SplitUtil.splitFees(s.getWesternFee());
                    for (String westernFee : westernFeeList) {
                        String[] westernFeeArr = westernFee.split(",");
                        if (westernFeeArr.length != 2) continue;
                        if (westernFeeArr[0].equals("西药费")) {
                            homePage.setWesternMedFee(westernFeeArr[1]);
                        } else if (westernFeeArr[0].equals("抗菌药物费用")) {
                            homePage.setAntibiosisFee(westernFeeArr[1]);
                        }
                    }
                }

                // 拆分中药类
                if(StringUtil.isNotBlank(s.getChnMedicineFee())) {
                    List<String> chnMedicineFeeList = SplitUtil.splitFees(s.getChnMedicineFee());
                    for (String chnMedicineFee : chnMedicineFeeList) {
                        String[] chnMedicineFeeArr = chnMedicineFee.split(",");
                        if (chnMedicineFeeArr.length != 2) continue;
                        if (chnMedicineFeeArr[0].equals("中成药费")) {
                            homePage.setChnMedFee(chnMedicineFeeArr[1]);
                        } else if (chnMedicineFeeArr[0].equals("中草药费")) {
                            homePage.setChnHerbFee(chnMedicineFeeArr[1]);
                        }
                    }
                }

                // 拆分血液类
                if(StringUtil.isNotBlank(s.getBloodTypeFee())){
                    List<String> bloodTypeFeeList = SplitUtil.splitFees(s.getBloodTypeFee());
                    for (String bloodTypeFee : bloodTypeFeeList) {
                        String[] bloodTypeFeeArr = bloodTypeFee.split(",");
                        if (bloodTypeFeeArr.length != 2) continue;
                        if (bloodTypeFeeArr[0].equals("血费")) {
                            homePage.setBloodFee(bloodTypeFeeArr[1]);
                        } else if (bloodTypeFeeArr[0].equals("白蛋白类制品费")) {
                            homePage.setAlbumenFee(bloodTypeFeeArr[1]);
                        } else if (bloodTypeFeeArr[0].equals("球蛋白类制品费")) {
                            homePage.setGlobulinFee(bloodTypeFeeArr[1]);
                        } else if (bloodTypeFeeArr[0].equals("凝血因子类制品费")) {
                            homePage.setBloodFactorFee(bloodTypeFeeArr[1]);
                        } else if (bloodTypeFeeArr[0].equals("细胞因子类制品费")) {
                            homePage.setCellFactorFee(bloodTypeFeeArr[1]);
                        }
                    }
                }

                // 拆分检查类
                if(StringUtil.isNotBlank(s.getMaterialFee())) {
                    List<String> materialFeeList = SplitUtil.splitFees(s.getMaterialFee());
                    for (String materialFee : materialFeeList) {
                        String[] materialFeeArr = materialFee.split(",");
                        if (materialFeeArr.length != 2) continue;
                        if (materialFeeArr[0].equals("检查用一次性医用材料费")) {
                            homePage.setCheckMaterialFee(materialFeeArr[1]);
                        } else if (materialFeeArr[0].equals("治疗用一次性医用材料费")) {
                            homePage.setTreatMaterialFee(materialFeeArr[1]);
                        } else if (materialFeeArr[0].equals("手术用一次性医用材料费")) {
                            homePage.setOperationMaterialFee(materialFeeArr[1]);
                        }
                    }
                }

                // 拆分治疗类
                if(StringUtil.isNotBlank(s.getOtherLeftFee())) {
                    List<String> otherLeftFeeList = SplitUtil.splitFees(s.getOtherLeftFee());
                    for (String otherLeftFee : otherLeftFeeList) {
                        String[] otherLeftFeeArr = otherLeftFee.split(",");
                        if (otherLeftFeeArr.length != 2) continue;
                        if (otherLeftFeeArr[0].equals("其他费")) {
                            homePage.setOtherTypeFee(otherLeftFeeArr[1]);
                        }
                    }
                }

                // 拆分其他类
                if(StringUtil.isNotBlank(s.getIsDiagnoseFit())) {
                    List<String> isDiagnoseFitList = SplitUtil.checkDiagnosis(s.getIsDiagnoseFit());
                    for (String isDiagnoseFit : isDiagnoseFitList) {
                        String[] isDiagnoseFitArr = isDiagnoseFit.split(",");
                        if (isDiagnoseFitArr.length != 2) continue;
                        if (isDiagnoseFitArr[0].equals("门诊与出院")) {
                            homePage.setIsOutpatientBehospital(isDiagnoseFitArr[1]);
                        }else if(isDiagnoseFitArr[0].equals("入院与出院")) {
                            homePage.setIsLeaveBehospital(isDiagnoseFitArr[1]);
                        }else if(isDiagnoseFitArr[0].equals("术前与术后")) {
                            homePage.setIsOperationBeforeAfter(isDiagnoseFitArr[1]);
                        }else if(isDiagnoseFitArr[0].equals("临床与病理")) {
                            homePage.setIsClinicPathology(isDiagnoseFitArr[1]);
                        }else if(isDiagnoseFitArr[0].equals("放射与病理")) {
                            homePage.setIsRadiatePathology(isDiagnoseFitArr[1]);
                        }
                    }
                }

                // 拆分抢救次数
                if(StringUtil.isNotBlank(s.getRescueOverview())){
                    List<String> rescueOverviewList = SplitUtil.splitRescueTimes(s.getRescueOverview());
                    // 第一个是抢救次数，第二个是成功次数
                    if(rescueOverviewList.size() == 2){
                        homePage.setRescueNum(rescueOverviewList.get(0));
                        homePage.setRescueSuccessNum(rescueOverviewList.get(1));
                    }
                }

//                sendDataDealFacade.sendInfo(s.getBehospitalCode());

                homePageList.add(homePage);

                //初始化诊断和手术，并同步到数据库
                aHomeDiagnoseInfoFacade.executeHomeDiagnose(s.getLeaveDiags());//首页诊断
                aHomeOperationInfoFacade.executeHomeOperation(s.getOperations());//首页手术

                try {
                    //从病案首页同步入院登记表中的住院医生behospitalDoctor，主治医生attendingDoctor和主任医生directorDoctor和ID
                    String behospitalDoctor = StringUtils.isEmpty(homePage.getBehospitalDoctor()) ? "" : homePage.getBehospitalDoctor();//获取住院医师姓名
                    String attendingDoctor = StringUtils.isEmpty(homePage.getAttendingDoctor()) ? "" : homePage.getAttendingDoctor();//获取主治医师姓名
                    String directorDoctor = StringUtils.isEmpty(homePage.getDirectorDoctor()) ? "" : homePage.getDirectorDoctor();//获取主任医师姓名
                    String behospitalDoctorID = this.getDoctorId(behospitalDoctor);//获取住院医师id
                    String attendingDoctorID = this.getDoctorId(attendingDoctor);//获取主治医师id
                    String directorDoctorID = this.getDoctorId(directorDoctor);//获取主任医师id

                    UpdateWrapper<BehospitalInfo> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("behospital_code", homePage.getBehospitalCode())
                            .eq("hospital_id", homePage.getHospitalId())
                            .eq("is_deleted", IsDeleteEnum.N)
                            .set("beh_doctor_name", behospitalDoctor)
                            .set("doctor_name", attendingDoctor)
                            .set("director_doctor_name", directorDoctor)
                            .set("beh_doctor_id", behospitalDoctorID)
                            .set("doctor_id", attendingDoctorID)
                            .set("director_doctor_id", directorDoctorID);
                    behospitalInfoFacade.update(updateWrapper);
                }catch (Exception e){
                    aMedAbnormalInfoFacade.saveAbnormalInfo("反查主治id异常","", JSON.toJSONString(homePage),"",e.getMessage());
                }
            });
            execute(homePageList);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页更新异常","", JSON.toJSONString(aHomePageIngVO),"",e.getMessage());
        }
    }

    /**
     * 根据docktorName获取docktorID
     * @param doctorName
     * @return
     */
    public String getDoctorId(String doctorName){
        QueryWrapper<BasDoctorInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("name",doctorName);
        BasDoctorInfo doctorInfo =aBasDoctorInfoFacade.getOne(queryWrapper);
        if (doctorInfo !=null && StringUtils.isNotEmpty(doctorInfo.getDoctorId())){
            return doctorInfo.getDoctorId();
        }else {
            return "-";
        }
    }

    /**
     * 评分后返回结构体
     * @param aHomePageIngVO
     * @return
     */
    private RespDTO<Map<String, Object>> homePageIng(AHomePageIngVO aHomePageIngVO){
        String behospitalCode =aHomePageIngVO.getHomePages().get(0).getBehospitalCode();
        Long hospitalId=aHomePageIngVO.getHomePages().get(0).getHospitalId();
        if(aHomePageIngVO.getDockModeType().equals("0")){
            Map<String,Object> map=new HashMap<String,Object>();
            List<AHomePageDTO> homePageDtoList=BeanUtil.listCopyTo(aHomePageIngVO.getHomePages(),AHomePageDTO.class);
            map.put("homePages",homePageDtoList);
            return RespDTO.onSuc(map);
        }else if(aHomePageIngVO.getDockModeType().equals("1")){
            //页面模式
            String url=readProperties.getProcessQcUrl()+"?behospitalCode="+behospitalCode+"&hospitalId="+hospitalId;
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("url",url);
            aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页页面推送模式验证1","", JSON.toJSONString(aHomePageIngVO),url,"");
            return RespDTO.onSuc(map);
        }else if(aHomePageIngVO.getDockModeType().equals("2")){
            AnalyzeRunVO analyzeRunVO=new AnalyzeRunVO();
            analyzeRunVO.setBehospitalCode(behospitalCode);
            analyzeRunVO.setHospitalId(hospitalId);
            AnalyzeRunDTO analyzeRunDTO=behospitalInfoFacade.analyzeRun(analyzeRunVO);
            Map<String,Object> map=new HashMap<String,Object>();
//            if(analyzeRunDTO.getMsgDTOList().size()>0){
//                map.put("analyze",analyzeRunDTO.getMsgDTOList());
//            }
            return RespDTO.onSuc(map);
        }else{
            //页面模式+接口引擎模式
            String url=readProperties.getProcessQcUrl()+"?behospitalCode="+behospitalCode+"&hospitalId="+hospitalId;

            AnalyzeRunVO analyzeRunVO=new AnalyzeRunVO();
            analyzeRunVO.setBehospitalCode(behospitalCode);
            analyzeRunVO.setHospitalId(hospitalId);
            AnalyzeRunDTO analyzeRunDTO=behospitalInfoFacade.analyzeRun(analyzeRunVO);
            Map<String,Object> map=new HashMap<String,Object>();
//            if(analyzeRunDTO.getMsgDTOList().size()>0){
//                map.put("url",url);
//                map.put("analyze",analyzeRunDTO.getMsgDTOList());
//            }
            aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页页面模式+接口引擎模式","", JSON.toJSONString(aHomePageIngVO),url,"");
            return RespDTO.onSuc(map);
        }
    }


    /**
     * 通过接口更新病案首页-不包含医嘱和手术
     * @param list
     * @return
     */
    public RespDTO<List<AHomePageDTO>> executeHomePage(List<AHomePageVO> list) {
        if(list!=null && list.size()>0){
            //循环验证数据有效性
            for (AHomePageVO aHomePageVO:list) {
                /*if("".equals(aHomePageVO.getHomePageId())) {
                    return RespDTO.onError("请输入病案首页编号!");
                }else */if(aHomePageVO.getHospitalId()==null){
                    return RespDTO.onError("请输入医院编码!");
                }else if("".equals(aHomePageVO.getBehospitalCode())){
                    return RespDTO.onError("请输入病人住院编码!");
                }
            }
            //装载数据
            List<HomePage> homePageList=Lists.newArrayList();
            list.stream().forEach(s->{
                //初始化入参
                HomePage homePage=new HomePage();
                BeanUtil.copyProperties(s,homePage);
                homePage.setBirthday(DateUtil.parseDate(s.getBirthday()));
                homePage.setBehospitalDate(DateUtil.parseDateTime(s.getBehospitalDate()));
                homePage.setLeaveHospitalDate(DateUtil.parseDateTime(s.getLeaveHospitalDate()));
                homePage.setQcDate(DateUtil.parseDateTime(s.getQcDate()));
                homePageList.add(homePage);
            });
            execute(homePageList);
            List<AHomePageDTO> homePageDtoList=BeanUtil.listCopyTo(list,AHomePageDTO.class);
            return RespDTO.onSuc(homePageDtoList);
        }else{
            return RespDTO.onError("未接收到数据!");
        }
    }

    /**
     * 病案首页
     * @param homePageList
     */
    public void execute(List<HomePage> homePageList){
        try {
            List<HomePage> addE = Lists.newLinkedList();
            List<HomePage> updateE = Lists.newLinkedList();
            if (homePageList != null && homePageList.size() > 0) {
                homePageList.stream().forEach(s -> {

                    HomePage homePage = this.getOne(new QueryWrapper<HomePage>()
                            /*.eq("home_page_id", s.getHomePageId())*/
                            .eq("hospital_id", s.getHospitalId())
                            .eq("behospital_code", s.getBehospitalCode()), false);
                    if (homePage != null) {
                        s.setGmtModified(new Date());
                        updateE.add(s);
                    } else {
                        s.setGmtCreate(new Date());
                        addE.add(s);
                    }
                });
            }
            if(addE.size()>0){
                homePageService.saveBatch(addE);
            }
            if(updateE.size()>0){
                homePageService.updateBatchByKey(updateE);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页","", JSON.toJSONString(homePageList),"",e.getMessage());
        }
    }

    public RespDTO deleteFlag(ADeleteFlagVO aDeleteFlagVO){
        try {
            //验证数据是否存在
            /*if(StringUtil.isEmpty(aDeleteFlagVO.getHomePageId())) {
                return RespDTO.onError("请输入病案首页编号!");
            }else */if(aDeleteFlagVO.getHospitalId()==null){
                return RespDTO.onError("请输入医院编码!");
            }else if(StringUtil.isEmpty(aDeleteFlagVO.getBehospitalCode())){
                return RespDTO.onError("请输入病人住院编码!");
            }else {
                UpdateWrapper<HomePage> updateWrapper=new UpdateWrapper<>();
                updateWrapper/*.eq("home_page_id", aDeleteFlagVO.getHomePageId())*/
                        .eq("hospital_id", aDeleteFlagVO.getHospitalId())
                        .eq("behospital_code", aDeleteFlagVO.getBehospitalCode())
                        .eq("is_deleted", IsDeleteEnum.N)
                        .set("is_deleted",IsDeleteEnum.Y)
                        .set("gmt_modified", DateUtil.now());
                Boolean flag=update(new HomePage(),updateWrapper);
                //aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页-删除",JSON.toJSONString(aDeleteFlagVO),JSON.toJSONString(RespDTO.onSuc(flag)),"操作成功!");
                return RespDTO.onSuc(flag);
            }
        }catch (Exception e){
            aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页-删除","",JSON.toJSONString(aDeleteFlagVO),"",e.getMessage());
            return RespDTO.onError(e.getMessage());
        }
    }
}
