package com.docus.server.message.busservice.impl;

import com.docus.core.util.DateUtil;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.exception.BaseException;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.server.message.busservice.FsBusinessService;
import com.docus.server.message.config.CollectTaskConfig;
import com.docus.server.message.controller.vo.PushInfoVo;
import com.docus.server.message.converters.FsWsRecordSubmitMessageConvert;
import com.docus.server.message.dto.FsRecordSubmitDTO;
import com.docus.server.message.dto.TbasicQrPreciseCondition;
import com.docus.server.message.feign.dto.CompensateTasRequest;
import com.docus.server.message.feign.dto.HospitalSubmitNodeLogAddDTO;
import com.docus.server.message.feign.enums.HospitalSubmitNodeEnum;
import com.docus.server.message.feign.service.CollectTaskService;
import com.docus.server.message.feign.service.HospitalSubmitNodeServiceApi;
import com.docus.server.message.mapper.TBasicMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: docus-unified-message
 * @BelongsPackage: com.docus.server.message.busservice.impl
 * @Author: chierhao
 * @CreateTime: 2024-03-20  08:57
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class FsBusinessServiceImpl implements FsBusinessService {

    @Resource
    private TBasicMapper tBasicMapper;

    @Autowired
    private HospitalSubmitNodeServiceApi hospitalSubmitNodeServiceApi;

    @Resource
    private CollectTaskService collectTaskService;
    @Override
    public  Boolean pushInfoEmr(PushInfoVo pushInfoVo) {
        try {
            CollectTaskConfig.TaskConfig taskConfig = CollectTaskConfig.getTaskConfig("WS_RECORD_SUBMIT");
            if (taskConfig == null || Func.isEmpty(taskConfig.getCollectorIds())) {
                throw new RuntimeException("任务配置未配置采集器id,WS_RECORD_SUBMIT");
            }
            FsRecordSubmitDTO dto = FsWsRecordSubmitMessageConvert.convert(pushInfoVo);
            if (Func.isBlank(dto.getJzh())
                    && Func.isBlank(dto.getInpatientNo())
                    && Func.isBlank(dto.getName())) {
                throw new BaseException("住院流水号、住院号、患者姓名 不可全部为空！");
            }
            TbasicQrPreciseCondition condition = FsWsRecordSubmitMessageConvert.convert(dto);
            List<String> patientIds = tBasicMapper.getPatientIdByPreciseConditions(condition);

            verifyPatientIds(patientIds);
            // 有多个患者，多个患者都插入数据。
            for (String patientId : patientIds) {
                String submitDateStr = dto.getSubmitDate();
                Date submitDate = Func.parseDate(submitDateStr, "yyyy/M/d HH:mm:ss");
                tBasicMapper.insertOrUpdateDoctorSubmitTime(patientId ,submitDate);

                compensateTask("电子病历提交", Collections.singletonList(patientId), taskConfig.getCollectorIds());
                tBasicMapper.updateEmrSubmitState(patientId, 1);

                // 添加提交记录
                HospitalSubmitNodeLogAddDTO nodeLogAddDTO = new HospitalSubmitNodeLogAddDTO();
                nodeLogAddDTO.setPatientId(patientId);
                nodeLogAddDTO.setContent(new String[]{Func.formatDateTime(submitDate)});
                nodeLogAddDTO.setSubmitNodeEnum(HospitalSubmitNodeEnum.EMR);
                nodeLogAddDTO.setCreater("电子病历提交");
                nodeLogAddDTO.setCreaterName("电子病历提交");
                hospitalSubmitNodeServiceApi.addLog(nodeLogAddDTO);
            }


            return true;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            // 不可知的错误
            return false;
        }
    }
    private void verifyPatientIds(List<String> patientIds) {
        if (Func.isEmpty(patientIds)) {
            throw new BaseException("系统无此患者！");
        }
    }

    @Override
    public  Boolean pushInfoNurs(PushInfoVo pushInfoVo) {
        try {
            CollectTaskConfig.TaskConfig taskConfig = CollectTaskConfig.getTaskConfig("WS_NURS_SUBMIT");
            if (taskConfig == null || Func.isEmpty(taskConfig.getCollectorIds())) {
                throw new RuntimeException("任务配置未配置采集器id,WS_NURS_SUBMIT");
            }
            FsRecordSubmitDTO dto = FsWsRecordSubmitMessageConvert.convert(pushInfoVo);
            if (Func.isBlank(dto.getJzh())
                    && Func.isBlank(dto.getInpatientNo())
                    && Func.isBlank(dto.getName())) {
                throw new BaseException("住院流水号、住院号、患者姓名 不可全部为空！");
            }
            TbasicQrPreciseCondition condition = FsWsRecordSubmitMessageConvert.convert(dto);
            List<String> patientIds = tBasicMapper.getPatientIdByPreciseConditions(condition);
            verifyPatientIds(patientIds);

            for (String patientId : patientIds) {
                String submitDate = dto.getSubmitDate();
                tBasicMapper.insertOrUpdateNurseSubmitTime(patientId, Func.parseDate(submitDate, DateUtil.PATTERN_DATETIME));
                compensateTask("护理提交",Collections.singletonList(patientId), taskConfig.getCollectorIds());
                // 添加提交记录
                HospitalSubmitNodeLogAddDTO nodeLogAddDTO = new HospitalSubmitNodeLogAddDTO();
                nodeLogAddDTO.setPatientId(patientId);
                nodeLogAddDTO.setContent(new String[]{submitDate});
                nodeLogAddDTO.setSubmitNodeEnum(HospitalSubmitNodeEnum.NURSE);
                nodeLogAddDTO.setCreater("护理提交");
                nodeLogAddDTO.setCreaterName("护理提交");
                hospitalSubmitNodeServiceApi.addLog(nodeLogAddDTO);
            }
            return true;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            // 不可知的错误
            return false;
        }
    }

    private void compensateTask(String source,List<String> patientIds, List<String> collectorIds) {
        log.info("{},补偿任务 patientIds:{} collectId:{}",source, patientIds, collectorIds);
        CompensateTasRequest dto = new CompensateTasRequest();
        dto.setPatientIds(patientIds);
        dto.setCollectorIds(collectorIds);
        dto.setPriority(3);
        CommonResult<String> result = collectTaskService.compensateTask(dto);
        log.info("{}，补偿任务结果：{}", source,Func.toJson(result));
    }


}
