package com.diagbot.facade;

import com.diagbot.dto.AnalyzeRunDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.MedicalRecord;
import com.diagbot.entity.StrFirstRecord;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.StrFirstRecordServiceImpl;
import com.diagbot.vo.AnalyzeRunVO;
import com.diagbot.vo.str.StrFirstRecordVO;
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 StrFirstRecordFacade extends StrFirstRecordServiceImpl {

    @Autowired
    private MedicalRecordFacade medicalRecordFacade;

    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;

    /**
     * 新增或修改首次病程录基本信息
     * @param strFirstRecord
     * @return
     */
    public RespDTO<StrFirstRecordVO> sendFirstRecordInfos(StrFirstRecord strFirstRecord){
        try {
            //根据病历id和病历模版id查询文书记录id
            MedicalRecord medicalRecord = medicalRecordFacade.lambdaQuery()
                    .like(MedicalRecord::getBehospitalCode, strFirstRecord.getBehospitalCode())
                    .eq(MedicalRecord::getModeId, 2)//首次病程录的病历模版id为2，写死
                    .one();
            //病历id合法性校验
            if(medicalRecord == null){
                throw new CommonException(CommonErrorCode.NOT_EXISTS);
            }
            strFirstRecord.setRecId(medicalRecord.getRecId());
            //将实体类字段转json
            ObjectMapper objectWriter = new ObjectMapper();
            String strResult = objectWriter.writeValueAsString(strFirstRecord);
            strFirstRecord.setWholeData(strResult);
            //修改或更新表中记录
            boolean saveOrUpdate = this.saveOrUpdate(strFirstRecord);
            //修改评分数据,并进行质控评分
            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);
        }
    }
}
