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.diagbot.dto.RespDTO;
import com.diagbot.entity.DoctorAdvice;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.service.impl.DoctorAdviceServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.TZDBConn;
import com.diagbot.vo.data.ADeleteFlagVO;
import com.diagbot.vo.data.ADoctorAdviceVO;
import com.google.common.collect.Lists;
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.List;

@Component
public class ADoctorAdviceFacade extends DoctorAdviceServiceImpl{

    @Autowired
    @Qualifier("doctorAdviceServiceImpl")
    private DoctorAdviceServiceImpl doctorAdviceService;
    @Autowired
    private AMedAbnormalInfoFacade aMedAbnormalInfoFacade;
    @Value("${log_switch.enable}")
    private boolean logSwitch;

    private TZDBConn tzDBConn = new TZDBConn();

    /**
     * 终末质控-同步前一天的入院病人医嘱信息
     */
    public void executeDoctorAdvice() {
        //String sql="select * from br_doctadvice where cjcxrq>=dateadd(day,-2,getdate()) and cjcxrq<=getdate()";
        String sql="select * from br_doctadvice where BRZYID in (select BRZYID from br_inpatientinfo where cjcxrq>=(select CONVERT(varchar,GETDATE()-2,23)) and cjcxrq<(select CONVERT(varchar,GETDATE(),23)) and requestflag='1')";
        List<DoctorAdvice> doctorAdviceList = tzDBConn.getDoctorAdvice(sql);
        execute(doctorAdviceList);
    }

    public void executeDoctorAdvicePast() {
        String sql="select * from br_doctadvice where cjcxrq>=dateadd(day,-2,getdate()) and cjcxrq<=getdate()";
        List<DoctorAdvice> doctorAdviceList = tzDBConn.getDoctorAdvice(sql);
        execute(doctorAdviceList);
    }
    /**
     * 数据引擎-通过接口更新医生医嘱信息
     * @param list
     * @return
     */
    public RespDTO executeDoctorAdvice(List<ADoctorAdviceVO> list) {
        try {
            if(list!=null && list.size()>0){
                //循环验证数据有效性
                for (ADoctorAdviceVO doctorAdvice:list) {
                    if("".equals(doctorAdvice.getDoctorAdviceId())) {
                        return RespDTO.onError("请输入病人医嘱编码!");
                    }else if(doctorAdvice.getHospitalId()==null){
                        return RespDTO.onError("请输入医院编码!");
                    }else if("".equals(doctorAdvice.getBehospitalCode())){
                        return RespDTO.onError("请输入病人住院编码!");
                    }
                }
                //初始、格式化数据
                List<DoctorAdvice> doctorAdviceList=Lists.newArrayList();
                list.stream().forEach(s->{
                    DoctorAdvice doctorAdvice=new DoctorAdvice();
                    BeanUtil.copyProperties(s,doctorAdvice);
                    if(StringUtil.isNotBlank(s.getDaStartDate())){
                        doctorAdvice.setDaStartDate(DateUtil.parseDateTime(s.getDaStartDate()));
                    }
                    if(StringUtil.isNotBlank(s.getDaStopDate())){
                        doctorAdvice.setDaStopDate(DateUtil.parseDateTime(s.getDaStopDate()));
                    }
                    doctorAdviceList.add(doctorAdvice);
                });
                execute(doctorAdviceList);
                if(logSwitch){
                    doctorAdviceList.forEach(s->{
                        aMedAbnormalInfoFacade.saveAbnormalInfo("病人住院医嘱-正常","", JSON.toJSONString(list),"","");
                    });
                }
                return RespDTO.onSuc("操作正常！");
            }else{
                return RespDTO.onError("未接收到数据!");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("病人住院医嘱-异常","", JSON.toJSONString(list),"",e.getMessage());
            return RespDTO.onError("数据处理异常，详情查看日志表");
        }
    }

    public void execute(List<DoctorAdvice> doctorAdviceList){
        List<DoctorAdvice> addE = Lists.newLinkedList();
        List<DoctorAdvice> updateE = Lists.newLinkedList();
        if (doctorAdviceList != null && doctorAdviceList.size() > 0) {
            doctorAdviceList.stream().forEach(s -> {
                DoctorAdvice doctorAdvice = this.getOne(new QueryWrapper<DoctorAdvice>()
                        .eq("doctor_advice_id", s.getDoctorAdviceId())
                        .eq("hospital_id", s.getHospitalId())
                        .eq("behospital_code",s.getBehospitalCode()), false);
                if (doctorAdvice != null) {
                    s.setGmtModified(new Date());
                    updateE.add(s);
                } else {
                    s.setGmtCreate(new Date());
                    addE.add(s);
                }
            });
        }
        if(addE.size()>0){
            doctorAdviceService.saveBatch(addE);
        }
        if(updateE.size()>0){
            doctorAdviceService.updateBatchByKey(updateE);
        }
    }

    public RespDTO deleteFlag(ADeleteFlagVO aDeleteFlagVO){
        try {
            //验证数据是否存在
            if(StringUtil.isEmpty(aDeleteFlagVO.getDoctorAdviceId())) {
                return RespDTO.onError("请输入病人医嘱编码!");
            }else if(aDeleteFlagVO.getHospitalId()==null){
                return RespDTO.onError("请输入医院编码!");
            }else if(StringUtil.isEmpty(aDeleteFlagVO.getBehospitalCode())){
                return RespDTO.onError("请输入病人住院编码!");
            }else {
                UpdateWrapper<DoctorAdvice> updateWrapper=new UpdateWrapper<>();
                updateWrapper.eq("doctor_advice_id", aDeleteFlagVO.getDoctorAdviceId())
                        .eq("behospital_code", aDeleteFlagVO.getBehospitalCode())
                        .eq("hospital_id", aDeleteFlagVO.getHospitalId())
                        .eq("is_deleted", IsDeleteEnum.N)
                        .set("is_deleted",IsDeleteEnum.Y)
                        .set("gmt_modified", DateUtil.now());

                Boolean flag=update(new DoctorAdvice(),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());
        }
    }
}
