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.dto.data.AHomeDiagnoseDTO;
import com.diagbot.entity.HomeDiagnoseInfo;
import com.diagbot.entity.HomePage;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.service.impl.HomeDiagnoseInfoServiceImpl;
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.AHomeDiagnoseVO;
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 AHomeDiagnoseInfoFacade extends HomeDiagnoseInfoServiceImpl{

    @Autowired
    @Qualifier("homeDiagnoseInfoServiceImpl")
    private HomeDiagnoseInfoServiceImpl homeDiagnoseInfoService;
    @Autowired
    private AMedAbnormalInfoFacade aMedAbnormalInfoFacade;
    @Autowired
    private AHomePageFacade aHomePageFacade;
    @Value("${log_switch.enable}")
    private boolean logSwitch;

    private TZDBConn tzDBConn = new TZDBConn();

    /**
     * 终末质控-定时同步病案首页诊断
     */
    public void executeHomeDiagnose() {
        //String sql="select * from br_recdiagnose where BASYID in (select BASYID from br_rechome where cjcxrq>=dateadd(day,-2,getdate()) and cjcxrq<=getdate())";//今年的数据
        //前一天的数据
        String sql="select * from br_recdiagnose where BASYID in (select BASYID from br_rechome where cjcxrq>=(select CONVERT(varchar,GETDATE()-1,23)) and cjcxrq<(select CONVERT(varchar,GETDATE(),23)))";
        List<HomeDiagnoseInfo> homeDiagnoseList = tzDBConn.getHomeDiagnose(sql);
        execute(homeDiagnoseList);
    }

    /**
     * 数据引擎-通过接口更新病案首页诊断
     * @param list
     * @return
     */
    public RespDTO<List<AHomeDiagnoseDTO>> executeHomeDiagnose(List<AHomeDiagnoseVO> list) {
        try{
            if(list!=null && list.size()>0){
                List<HomeDiagnoseInfo> homeDiagnoseList=Lists.newArrayList();
                list.forEach(s->{
                    HomePage homePage = aHomePageFacade.getOne(new QueryWrapper<HomePage>()
                            .eq("behospital_code", s.getBehospitalCode()), false);
                    if(homePage != null){
                        s.setHomePageId(homePage.getHomePageId());
                    }
                });
                homeDiagnoseList=BeanUtil.listCopyTo(list,HomeDiagnoseInfo.class);
                execute(homeDiagnoseList);
                if(logSwitch){
                    homeDiagnoseList.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<HomeDiagnoseInfo> homeDiagnoseList){
        List<HomeDiagnoseInfo> addE = Lists.newLinkedList();
        List<HomeDiagnoseInfo> updateE = Lists.newLinkedList();
        List<HomeDiagnoseInfo> deleteE = Lists.newLinkedList();
        if (homeDiagnoseList != null && homeDiagnoseList.size() > 0) {
            homeDiagnoseList.stream().forEach(s -> {
                if(s.getHomePageId()!=null && !"".equals(s.getDiagnoseOrderNo())){
                    HomeDiagnoseInfo diagnoseInfo = this.getOne(new QueryWrapper<HomeDiagnoseInfo>()
                            .eq("home_page_id", s.getHomePageId())
                            .eq("hospital_id", s.getHospitalId())
                            .eq("diagnose_order_no", s.getDiagnoseOrderNo()), false);
                    if (diagnoseInfo != null) {
                        s.setGmtModified(new Date());
                        updateE.add(s);
                    } else {
                        s.setGmtCreate(new Date());
                        addE.add(s);
                    }
                }
            });
        }
        if(addE.size()>0){
            homeDiagnoseInfoService.saveBatch(addE);
        }
        if(updateE.size()>0){
            homeDiagnoseInfoService.updateBatchByKey(updateE);
        }
    }

    public RespDTO deleteFlag(ADeleteFlagVO aDeleteFlagVO){
        try {
            //验证数据是否存在
            if(StringUtil.isEmpty(aDeleteFlagVO.getHomePageId())) {
                return RespDTO.onError("出院诊断未输入病案首页编号!");
            }else if(aDeleteFlagVO.getHospitalId()==null){
                return RespDTO.onError("出院诊断未输入医院编码!");
            }else if(StringUtil.isEmpty(aDeleteFlagVO.getDiagnoseOrderNo())){
                return RespDTO.onError("出院诊断未输入顺序号!");
            }else {
                UpdateWrapper<HomeDiagnoseInfo> updateWrapper=new UpdateWrapper<>();
                updateWrapper.eq("home_page_id", aDeleteFlagVO.getHomePageId())
                        .eq("hospital_id", aDeleteFlagVO.getHospitalId())
                        .eq("diagnose_order_no", aDeleteFlagVO.getDiagnoseOrderNo())
                        .eq("is_deleted", IsDeleteEnum.N)
                        .set("is_deleted",IsDeleteEnum.Y)
                        .set("gmt_modified", DateUtil.now());

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