package com.sifang.modules.taskdispatch.service.autod;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.sys.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;

import static com.sifang.modules.taskdispatch.service.autod.ItemTaskEventBus.TASK_DISPATCHED;

public class StarveDispatchOrders implements DispatchOrders {

    @Override
    public List<Record> order(List<Record> workers) {
        if (CollectionUtils.isEmpty(workers)) {
            return workers;
        }

        List<String> times = SpringUtils.getBean(SfCacheService.class).mget(workers.stream().map(e -> TASK_DISPATCHED + e.getStr("id")).toArray(String[]::new));
        int i = 0;
        for (Record worker : workers) {
            String lastDispatchTime = times.get(i);
            if (StringUtils.isNotBlank(lastDispatchTime)) {
                worker.set("last_dispatch_time", Long.valueOf(lastDispatchTime));
            } else {
                worker.set("last_dispatch_time", -1L);
            }
            i++;
        }
        workers.sort(new Comparator<Record>() {
            @Override
            public int compare(Record o1, Record o2) {
                return Long.compare(o1.get("last_dispatch_time"), o2.get("last_dispatch_time"));
            }
        });
        return workers;
    }
}
