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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
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.infrastructure.web.api.ResultCode;
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.converters.NkWsRecordSubmitMessageConvert;
import com.docus.server.message.dto.*;
import com.docus.server.message.entity.CqcPushConfig;
import com.docus.server.message.entity.TBasic;
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.feign.vo.ArchiveAndRecallPushVo;
import com.docus.server.message.mapper.CqcPushConfigMapper;
import com.docus.server.message.mapper.TBasicMapper;
import com.docus.server.message.validate.NkRecordSubmitValidate;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @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);

            String submitDate = dto.getSubmitDate();
            tBasicMapper.insertOrUpdateDoctorSubmitTime(patientIds.get(0), Func.parseDate(submitDate, "yyyy/M/d HH:mm:ss"));

            compensateTask("电子病历提交",patientIds, taskConfig.getCollectorIds());
            tBasicMapper.updateEmrSubmitState(patientIds.get(0), 1);

            // 添加提交记录
            HospitalSubmitNodeLogAddDTO nodeLogAddDTO = new HospitalSubmitNodeLogAddDTO();
            nodeLogAddDTO.setPatientId(patientIds.get(0));
            nodeLogAddDTO.setContent(new String[]{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("系统无此患者！");
        }
        if (patientIds.size() > 1) {
            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);

            String submitDate = dto.getSubmitDate();
            tBasicMapper.insertOrUpdateNurseSubmitTime(patientIds.get(0), Func.parseDate(submitDate, DateUtil.PATTERN_DATETIME));

            compensateTask("护理提交",patientIds, taskConfig.getCollectorIds());

            // 添加提交记录
            HospitalSubmitNodeLogAddDTO nodeLogAddDTO = new HospitalSubmitNodeLogAddDTO();
            nodeLogAddDTO.setPatientId(patientIds.get(0));
            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));
    }


}
