package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.entity.BehospitalInfo;
import com.diagbot.entity.MedicalRecord;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.data.AMedAbnormalInfoFacade;
import com.diagbot.facade.data.AMedicalRecordFacade;
import com.diagbot.facade.data.SendDataDealFacade;
import com.diagbot.util.DateUtil;
import com.diagbot.util.TZDBConn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
public class OldDataFacade {

    @Autowired
    private AMedicalRecordFacade aMedicalRecordFacade;

    @Autowired
    private SendDataDealFacade sendDataDealFacade;
    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;
    @Autowired
    private AMedAbnormalInfoFacade aMedAbnormalInfoFacade;

    private TZDBConn tzDBConn = new TZDBConn();

    public static void main(String[] args) {
        OldDataFacade oldDataFacade = new OldDataFacade();
        oldDataFacade.execute();
    }

    /**
     * 病历文书一致性
     */
    public void execute(){
        LocalDateTime now = LocalDateTime.now();
        now = now.minus(30, ChronoUnit.DAYS);
        List<BehospitalInfo> list = behospitalInfoFacade.list(new QueryWrapper<BehospitalInfo>()
        .le("leave_hospital_date", DateUtil.now())
        .ge("leave_hospital_date",now));
        if (list.size()>0){
            list.forEach(behospitalInfo->{
                IfCoincide(behospitalInfo.getBehospitalCode());
            });
        }
    }

    /**
     * 判断本地文书数量跟视图文书数量是否一致
     * @param code
     */
    public void IfCoincide(String code){
        try {
            Integer myCount=0;
            String codes="";
            myCount =aMedicalRecordFacade.count(new QueryWrapper<MedicalRecord>()
                    .eq("behospital_code",code)
                    .eq("hospital_id",Long.valueOf("14"))
                    .eq("is_deleted",IsDeleteEnum.N.getKey()));
            String sql ="select count(*) as count from v_jkcdss_bl_bingli where behospitalCode = "+code;
            Integer count =tzDBConn.getCount(sql);
            if (count!=0){
                if (count != myCount){
                    aMedicalRecordFacade.remove(new QueryWrapper<MedicalRecord>()
                                    .eq("behospital_code",code)
                                    .eq("hospital_id",Long.valueOf("14")));
                    sendDataDealFacade.sendDateDealOne(code);
                    aMedAbnormalInfoFacade.saveAbnormalInfo("补传数据成功", code,"视图文书数量为"+count, "本地数量为"+myCount, "");
                }
            }
        }catch (Exception e){
            aMedAbnormalInfoFacade.saveAbnormalInfo("补传数据失败", code,"", "", e.getMessage());

        }

    }
    /**
     * 每天同步医生信息
     */
    public void DoctorExecute(){

    }
}
