package com.ximai.mes.pro.schedule.strategy;

import cn.hutool.core.util.NumberUtil;
import com.ximai.mes.pro.schedule.Equipment;
import com.ximai.mes.pro.schedule.IOperationTimeCalculator;
import com.ximai.mes.pro.schedule.TaskSchedulingContext;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 排产时间评估设备
 * 交期内生产=5、交期外生产=0
 * 开始时间先后=5
 * NumberUtil.max(6-排名*1,0)
 *
 */
public class EvaluateEquipmentDeliveryTime implements EvaluateEquipment{
    @Override
    public double evaluate(TaskSchedulingContext context, IOperationTimeCalculator.OperationTimePlan operationTimePlan
            , List<TaskSchedulingContext.TaskSchedulingResultContext> scheduleResult) {
        double rst = 0;
        List<IOperationTimeCalculator.OperationTimePlanItem> operationTimePlanItemList = operationTimePlan.getPlan();
        if(operationTimePlanItemList.isEmpty()){
            return rst;
        }
        Duration lastEndTime = operationTimePlanItemList.get(operationTimePlanItemList.size()-1).getEndedTime();
        //时间评分
        int rank = this.getRank(context.getEquipment(), scheduleResult);
        rst += NumberUtil.max(6-rank*1.0,0);
        // 在交期范围内，5
        // 在交期范围外，0
        if(context.getJob().getProducedDeliveryTime().compareTo(lastEndTime)>=0){
            rst += 5;
        }
        return rst;
    }


    private int getRank(Equipment equipment, List<TaskSchedulingContext.TaskSchedulingResultContext> scheduleResult){
        if(scheduleResult.size()==1){
            return 1;
        }
        List<TaskSchedulingContext.TaskSchedulingResultContext> list = scheduleResult.stream().sorted(Comparator.comparing(s1->{
            return s1.getOpertionTimePlan().getPlan().get(0).getStartedTime();
        })).collect(Collectors.toList());
        int i=1;
        TaskSchedulingContext.TaskSchedulingResultContext temp = null;
        for(TaskSchedulingContext.TaskSchedulingResultContext l : list){
            if(temp!=null&&
                    !temp.getOpertionTimePlan().getPlan().get(0).getStartedTime()
                            .equals(l.getOpertionTimePlan().getPlan().get(0).getStartedTime())){
                i++;
            }
            if(equipment.getId().equals(l.getEquipment().getId())){
                return i;
            }
            temp = l;
        }
        return i;
    }


    @Override
    public int weight() {
        return 5;
    }

}
