package com.docus.server.mzsy.job;

import cn.hutool.core.collection.CollUtil;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.utils.TableJsonRead;
import com.docus.server.archive.job.PatientInfoSyncJob;
import com.docus.server.archive.mapper.TBasicMapper;
import com.docus.server.mzsy.entity.MzsyPatientInfoView;
import com.docus.server.mzsy.mapper.MzsyPatientInfoViewMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author YongBin Wen
 * @date 2026/2/27 10:38
 */
@Component
@Slf4j
public class BasicCheckJob {
    @Resource
    private MzsyPatientInfoViewMapper mzsyPatientInfoViewMapper;

    @Resource
    private TBasicMapper tBasicMapper;

    @XxlJob("MzsyBasicSyncCheckJob")
    public void basicSyncCheckJob() {
        log.info("梅州三院基础数据检查任务开始了");
        try {
            String jobConfigPath = "data-config\\job-config";
            String jobConfigName = "ViewPatientInfoSyncJob.json";
            TableJsonRead jsonReader = new TableJsonRead();
            PatientInfoSyncJob.PatientInfoSyncJobConfig syncJobConfig = jsonReader.Read(jobConfigPath, jobConfigName, PatientInfoSyncJob.PatientInfoSyncJobConfig.class);
            syncJobConfig = PatientInfoSyncJob.PatientInfoSyncJobConfig.checkAndInit(syncJobConfig);
            String cyrqStart = syncJobConfig.getCyrqStart();
            int offset = 0;
            int size = 2000;
            while (true) {
                List<String> jzhs = tBasicMapper.getJzhByDisDate(cyrqStart, offset, size);
                if (CollUtil.isEmpty(jzhs)) {
                    break;
                }
                List<MzsyPatientInfoView> views = mzsyPatientInfoViewMapper.getByJzh(cyrqStart, jzhs);
                List<String> viewJzhs = views.stream().map(MzsyPatientInfoView::getJZH).collect(Collectors.toList());
                List<String> cancelJzhs = new ArrayList<>();
                for (String jzh : jzhs) {
                    if (viewJzhs.contains(jzh)) {
                        continue;
                    }
                    cancelJzhs.add(jzh);
                }
                if(CollUtil.isNotEmpty(cancelJzhs)){
                    tBasicMapper.cancenlByJzhs(cancelJzhs);
                    log.info("jzhs:{} 视图数据为无需同步数据或者不存在，作废基础数据！", Func.toJson(cancelJzhs));
                }
                offset = offset + size;
            }
            log.info("梅州三院基础数据检查任务结束了");
        } catch (Exception e) {
            log.error("梅州三院基础数据检查出错了，" + e.getMessage(), e);
        }
    }

}
