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

import com.docus.core.util.Func;
import com.docus.server.collect.domain.TaskConfig;
import com.docus.server.collect.service.ITaskConfigService;
import com.docus.server.sys.common.pojo.dto.UserDTO;
import com.docus.server.sys.service.IPowerUserService;
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 AbstractUserCollectJob {
    @Autowired
    private IPowerUserService userService;
    @Resource
    private ITaskConfigService taskConfigService;

    protected AbstractUserCollectJob(IPowerUserService userService, ITaskConfigService taskConfigService) {
        this.userService = userService;
        this.taskConfigService = taskConfigService;
    }

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

        List<PeriodTime> periodTimes = taskConfig.getAllPeriodTimes();
        for (PeriodTime periodTime : periodTimes) {
            getUsers(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 -> {
            getUsers(periodTime, taskConfig);
            taskConfigService.updateIncPointerDate(taskConfigId, periodTime.getPeriodEndDate());
        });

    }

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

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

    /**
     * 需要去适配获取用户信息
     *
     * @param startDate
     * @param endDate
     * @param pageNum
     * @param pageSize
     * @return
     */
    public abstract List<UserDTO> getUsers(Date startDate, Date endDate, long pageNum, long pageSize);


}
