package com.diagbot.facade;

import com.diagbot.dto.AnalyzeRunDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.MedicalRecord;
import com.diagbot.entity.StrPeriodConclusion;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.StrPeriodConclusionServiceImpl;
import com.diagbot.vo.AnalyzeRunVO;
import com.diagbot.vo.str.StrPeriodConclusionVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @author: cy
 * @time: 2020/9/23 11:39
 */
@Component
public class StrPeriodConclusionFacade extends StrPeriodConclusionServiceImpl {

    @Autowired
    private MedicalRecordFacade medicalRecordFacade;

    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;

    public RespDTO<StrPeriodConclusionVO> sendPeriodConclusionInfos(StrPeriodConclusion strPeriodConclusion) {

        try {
            //根据病历id、病历模版id和记录时间查询文书记录id
            MedicalRecord medicalRecord = medicalRecordFacade.lambdaQuery()
                    .like(MedicalRecord::getBehospitalCode, strPeriodConclusion.getBehospitalCode())
                    .eq(MedicalRecord::getModeId, 28)//阶段小结的病历模版id为28，写死
                    .eq(MedicalRecord::getRecDate, strPeriodConclusion.getRecDate())
                    .one();
            //病历id合法性校验
            if (medicalRecord == null) {
                throw new CommonException(CommonErrorCode.NOT_EXISTS);
            }
            strPeriodConclusion.setRecId(medicalRecord.getRecId());
            //将实体类字段转json
            ObjectMapper objectWriter = new ObjectMapper();
            String strResult = objectWriter.writeValueAsString(strPeriodConclusion);
            strPeriodConclusion.setWholeData(strResult);
            //修改或更新表中记录
            boolean saveOrUpdate = this.saveOrUpdate(strPeriodConclusion);
            //修改评分数据,并进行质控评分
            if(saveOrUpdate){
                AnalyzeRunVO analyzeRunVO=new AnalyzeRunVO();
                analyzeRunVO.setBehospitalCode(medicalRecord.getBehospitalCode());
                analyzeRunVO.setHospitalId(medicalRecord.getHospitalId());
                analyzeRunVO.setModeId(medicalRecord.getModeId());
                AnalyzeRunDTO analyzeRunDTO=behospitalInfoFacade.analyzeRun(analyzeRunVO);
            }
            return saveOrUpdate == true ? RespDTO.onSuc("操作正常！") : RespDTO.onError("保存记录失败！");
        } catch (JsonProcessingException e) {
            throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED);
        }
    }
}
