package com.bailuntec.support;

import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.JobPointLogExample;
import com.bailuntec.mapper.JobPointLogMapper;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

@Slf4j
public class PointJob implements SimpleJob {
    @Override
    public void execute(ShardingContext shardingContext) {
        JobPointLog jobPointLog = jobInit(shardingContext);
        executeJob(shardingContext, jobPointLog);
        jobRefresh(shardingContext, jobPointLog);
    }

    private void jobRefresh(ShardingContext shardingContext, JobPointLog jobPointLog) {
        try {
            JobPointLogMapper mapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
            jobPointLog.setGmtModified(LocalDateTime.now());
            mapper.upsertSelective(jobPointLog);
            SessionUtil.getSession().commit();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行" + shardingContext.getJobName() + "Job失败, " + jobPointLog, e);
            throw new RuntimeException(e);
        } finally {
            SessionUtil.closeSession();
        }
    }

    private JobPointLog jobInit(ShardingContext shardingContext) {
        JobPointLog jobPointLog = null;
        try {
            JobPointLogMapper mapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
            jobPointLog = mapper.selectOneByExample(JobPointLogExample.newAndCreateCriteria().andJobNameEqualTo(shardingContext.getJobName()).example());
            if (jobPointLog == null) {
                jobPointLog = new JobPointLog(shardingContext.getJobName(), 1, 100, 0, 1, LocalDateTime.now().minusDays(1), LocalDateTime.now());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("新建" + shardingContext.getJobName() + "Job并插入DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
        return jobPointLog;
    }

    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {

    }

}
