package com.docus.server.collect.job.basic;

import com.docus.core.util.Func;
import com.docus.server.collect.domain.TaskConfig;
import com.docus.server.collect.service.ITaskConfigService;
import com.docus.server.record.pojo.dto.TBasicDTO;
import com.docus.server.record.service.ITBasicService;
import com.docus.server.tool.PeriodTime;
import com.xxl.job.core.context.XxlJobHelper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

public abstract class AbstractTBasicCollectJob {
    @Autowired
    private final ITBasicService basicService;
    @Resource
    private final ITaskConfigService taskConfigService;

    protected AbstractTBasicCollectJob(ITBasicService deptService, ITaskConfigService taskConfigService) {
        this.basicService = deptService;
        this.taskConfigService = taskConfigService;
    }

    /**
     * 启动全量收集任务，时间从数据库读取，全量一般都用手工指定
     */
    public void startCollectAll(String taskConfigId) {
        TaskConfig taskConfig = taskConfigService.getTaskConfig(taskConfigId);

        List<PeriodTime> periodTimes = taskConfig.getAllPeriodTimes();
        for (PeriodTime periodTime : periodTimes) {
            getTBasic(periodTime, taskConfig);
            taskConfigService.updateAllPointerDate(taskConfigId, periodTime.getPeriodEndDate());
        }
    }

    /**
     * 启动增量收集任务，时间从数据库读取，增量任务用定时的方式
     */
    public void startCollectIncrement(String taskConfigId) {
        TaskConfig taskConfig = taskConfigService.getTaskConfig(taskConfigId);

        List<PeriodTime> periodTimes = taskConfig.getIncPeriodTimes();
        periodTimes.forEach(periodTime -> {
            getTBasic(periodTime, taskConfig);
            taskConfigService.updateIncPointerDate(taskConfigId, periodTime.getPeriodEndDate());
        });

    }

    protected String getJobParam() {
        return XxlJobHelper.getJobParam();
    }

    /**
     * 具体操作
     *
     * @param periodTime
     * @param taskConfig
     */
    private void getTBasic(PeriodTime periodTime, TaskConfig taskConfig) {
        //考虑到性能，应该把起始时间和结束时间进行切割拆分到每天。按段查询。
        List<TBasicDTO> basics;
        int pageNum = 1;
        for (; true; pageNum++) {
            basics = this.getTBasics(
                periodTime.getPeriodStartDate(),
                periodTime.getPeriodEndDate(),
                pageNum,
                taskConfig.getPageSize()
            );
            if (Func.isEmpty(basics)) {
                break;
            }
            //保存
            basicService.batchSaveBasics(basics);
        }
    }

    /**
     * 需要去适配获取病患信息
     *
     * @param startDate
     * @param endDate
     * @param pageNum
     * @param pageSize
     * @return
     */
    public abstract List<TBasicDTO> getTBasics(Date startDate, Date endDate, long pageNum, long pageSize);


}
