package com.brilliance.isc.common.taskdistributor.comparator;

import com.brilliance.isc.bo.TaskDistConfig;
import com.brilliance.isc.bo.TaskDistUser;
import com.brilliance.isc.common.taskdistributor.consts.TaskDistConstants;
import com.brilliance.isc.common.taskdistributor.enums.OverFlowMode;
import com.brilliance.isc.common.taskdistributor.enums.UserPosition;

import java.util.Comparator;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

public class GeneralUserOverFlowCompartor implements Comparator<TaskDistUser> {

    private static final Date MIN_DATE = new Date(0L);
    @Override
    public int compare(TaskDistUser u1, TaskDistUser u2) {

         String bizGrp = ((TaskDistConfig)TaskDistConstants.sortflg.get().get(u1.getBranchinr())).getGrp();

         String overFlowMode = ((TaskDistConfig)TaskDistConstants.sortflg.get().get(u1.getBranchinr())).getOverflowMode();

         String usrPositionSwitch = ((TaskDistConfig)TaskDistConstants.sortflg.get().get(u1.getBranchinr())).getPositionPrioritySwitch();
        //按组别
        //当前组别优先，其它组别在后
        if(Objects.equals(OverFlowMode.BYGROUP.getValue(),overFlowMode)){
            String bizGrp1 = u1.getBizGroup();
            String bizGrp2 = u2.getBizGroup();
            if(!Objects.equals(bizGrp1,bizGrp2)){
                if(Objects.equals(bizGrp1,bizGrp)){
                    return -1;
                }else if (Objects.equals(bizGrp2,bizGrp)){
                    return 1;
                }
            }
        }

        //岗位优先模式
        if(Objects.equals(TaskDistConstants.SWITCH_ON,usrPositionSwitch)) {
            String u1Priority = UserPosition.getValuePriority(u1.getBizPosition());
            String u2Priority = UserPosition.getValuePriority(u2.getBizPosition());
            //优先级数值越小，优先级越靠前
            if (u1Priority.compareTo(u2Priority) != 0) {
                return u1Priority.compareTo(u2Priority);
            }
        }

        // 先比较阈值占用（手头上任务数，越少优先级越高）
        if (u1.getAssignedTaskCount().compareTo(u2.getAssignedTaskCount()) != 0) {
            return u1.getAssignedTaskCount().compareTo(u2.getAssignedTaskCount());
        } else {
            // 再比较上笔提交时间
            // 时间越靠前，优先级越高
            Date t1 = Optional.ofNullable(u1.getLastCommitTime()).orElse(MIN_DATE);
            Date t2 = Optional.ofNullable(u2.getLastCommitTime()).orElse(MIN_DATE);
            return t1.compareTo(t2);
        }
    }
}
