package com.tax.token.job;

import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.dataflow.DataflowJob;
import com.google.common.base.Stopwatch;
import com.tax.token.job.dto.TokenAdjustPriorityDto;
import com.tax.token.model.TkToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author caosongqing
 * @date 2022/7/27
 * @description
 */
@Slf4j
@Component
public class AdjustPriorityTokenJob implements DataflowJob<TkToken> {

    @Autowired
    private SynGetTokenTask synGetTokenTask;

    /**
     * delay hours
     */
    public static final int DELAY_HOURS_DEFAULT = 2;

    public static final int VALID_HOURS_DEFAULT = 36;

    public static final int LIMIT_DFAULT = 200;

    @Override
    public List<TkToken> fetchData(ShardingContext shardingContext) {
        TokenAdjustPriorityDto tokenAdjustPriorityDto = this.getAdjustParameters(shardingContext);
        Stopwatch stopwatch = Stopwatch.createStarted();
        List<TkToken> tokenList = synGetTokenTask.getBehindTokenList(tokenAdjustPriorityDto);
        stopwatch.stop();
        log.info("behind token list size:{} elapsed: {} ms", tokenList.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
        return tokenList;
    }

    @Override
    public void processData(ShardingContext shardingContext, List<TkToken> list) {
        log.info("adjust priority size:{}", list.size());
        Stopwatch stopwatch = Stopwatch.createStarted();
        synGetTokenTask.adjustPriorityToken(list);
        stopwatch.stop();
        log.info("token adjust priority elapsed: {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));

    }

    private TokenAdjustPriorityDto getAdjustParameters(ShardingContext shardingContext) {
        String jobParameter = shardingContext.getJobParameter();
        log.info("token adjust priority job parameters:{}", jobParameter);
        TokenAdjustPriorityDto tokenAdjustPriorityDto = null;
        if (StringUtils.isNotBlank(jobParameter)) {
            tokenAdjustPriorityDto = JSONObject.parseObject(jobParameter, TokenAdjustPriorityDto.class);
        }
        if (tokenAdjustPriorityDto == null) {
            tokenAdjustPriorityDto = new TokenAdjustPriorityDto();
            tokenAdjustPriorityDto.setDelayHours(DELAY_HOURS_DEFAULT);
            tokenAdjustPriorityDto.setValidHours(VALID_HOURS_DEFAULT);
            tokenAdjustPriorityDto.setLimit(LIMIT_DFAULT);
        }

        return tokenAdjustPriorityDto;
    }
}
