From daa2cec25875276f3462e09d102f9d2fd52a96e1 Mon Sep 17 00:00:00 2001
From: L <L@132>
Date: 星期三, 18 三月 2026 16:03:43 +0800
Subject: [PATCH] *

---
 src/main/java/com/zy/asrs/utils/TimePriorityUtil.java             |   64 +++++
 src/main/java/com/zy/asrs/service/impl/MainServiceImpl.java       |  330 +++++++++++++++++++++++++--
 src/main/java/com/zy/asrs/utils/TaskDispatchPriorityUtil.java     |  209 +++++++++++++++++
 src/main/java/com/zy/asrs/utils/DistancePriorityUtil.java         |   41 +++
 src/main/java/com/zy/asrs/utils/PriorityWeightCalculatorUtil.java |   41 +++
 src/main/resources/application.yml                                |   13 +
 6 files changed, 669 insertions(+), 29 deletions(-)

diff --git a/src/main/java/com/zy/asrs/service/impl/MainServiceImpl.java b/src/main/java/com/zy/asrs/service/impl/MainServiceImpl.java
index ccaa0ff..fd7d991 100644
--- a/src/main/java/com/zy/asrs/service/impl/MainServiceImpl.java
+++ b/src/main/java/com/zy/asrs/service/impl/MainServiceImpl.java
@@ -14,6 +14,7 @@
 import com.zy.asrs.task.escalationParam.RgvTaskReportingParam;
 import com.zy.asrs.utils.PostMesDataUtils;
 import com.zy.asrs.utils.SortTheExecutionOfTheCarUtil;
+import com.zy.asrs.utils.TaskDispatchPriorityUtil;
 import com.zy.asrs.utils.TimeCalculatorUtils;
 import com.zy.common.CodeRes;
 import com.zy.common.service.CommonService;
@@ -78,6 +79,18 @@
     private boolean reportSwitch;
     @Value("${wms.reportSwitchAuto}")
     private boolean reportSwitchAuto;
+    @Value("${constant-parameters.priority.distance-threshold:10000}")
+    private Long priorityDistanceThreshold;
+    @Value("${constant-parameters.priority.weight.time:0.4}")
+    private Double priorityTimeWeight;
+    @Value("${constant-parameters.priority.weight.distance:0.4}")
+    private Double priorityDistanceWeight;
+    @Value("${constant-parameters.priority.weight.region:0.2}")
+    private Double priorityRegionWeight;
+    @Value("${constant-parameters.priority.region-values:}")
+    private String regionPriorityValues;
+    private volatile String cachedRegionPriorityRaw = "";
+    private volatile Map<Integer, Double> cachedRegionPriorityMap = new HashMap<>();
 
     /*
     * 楠岃瘉璁稿彲璇佹槸鍚︽湁鏁�
@@ -207,38 +220,299 @@
      * 绔欑偣浠诲姟妫�娴�  涓嬪彂灏忚溅鍙栨斁浠诲姟
      */
     public synchronized void DevpTaskNoRun() {
-
         try {
-            List<WrkMast> wrkMasts = wrkMastService.selectList(new EntityWrapper<WrkMast>().eq("wrk_sts", 1L).orderBy("modi_time", true));
-            if (wrkMasts.isEmpty()) {
-                return;
-            }
-            long differenceInSeconds = TimeCalculatorUtils.differenceInMilliseconds(wrkMasts.get(0).getModiTime(), new Date());
-            if (differenceInSeconds <= 1000) {
-                return;
-            }
-
-            BasCircularShuttle basCircularShuttle = basCircularShuttleService.selectOne(new EntityWrapper<BasCircularShuttle>().eq("rgv_id", 1));
-            RgvThread rgvThread = (RgvThread) SlaveConnection.get(SlaveType.Rgv, basCircularShuttle.getRgvNo());
-            RgvProtocol rgvProtocol = rgvThread.getRgvProtocol();
-            if (rgvProtocol == null) {
-                return;
-            }
-            List<BasDevpPosition> basDevpPositions = basDevpPositionService.selectList(new EntityWrapper<BasDevpPosition>().orderBy("plc_position", true));
-            List<BasDevpPosition> basDevpPositionDevRegion = basDevpPositionService.selectList(new EntityWrapper<BasDevpPosition>().orderBy("dev_region", true));
-            Integer devNo = SortTheExecutionOfTheCarUtil.LatelyAndLessThan(basDevpPositions, rgvProtocol.getRgvPos(), perimeter);
-            BasDevpPosition[] basDevpPositionsList = SortTheExecutionOfTheCarUtil.devpNoSort(basDevpPositions, devNo);
-            BasDevpPosition[] basDevpPositionsListUN = SortTheExecutionOfTheCarUtil.devpNoSortUN(basDevpPositionsList);
-            List<List<Integer>> siteListAll = SortTheExecutionOfTheCarUtil.siteListAll(basDevpPositionDevRegion);
-//            List<List<WrkMast>> wrkMastLists = getWrkMastLists(basDevpPositionsListUN);
-            List<List<List<WrkMast>>> wrkMastListAll = getWrkMastListAll(siteListAll, basDevpPositionsListUN);
-            //涓嬪彂浠诲姟
-//            taskDown(wrkMastLists);
-            taskDown(wrkMastListAll);
+            dispatchTaskByFlow();
         } catch (Exception e) {
-            log.error("鑷姩涓嬪彂灏忚溅浠诲姟澶辫触锛屽紓甯革細" + e);
+            log.error("鑷姩涓嬪彂灏忚溅浠诲姟澶辫触锛屽紓甯革細{}", e.getMessage(), e);
+        }
+    }
+
+    /**
+     * 娴佺▼鍥剧増: 浠诲姟姹犳寫浠诲姟骞朵笅鍙慠GV
+     * 鏃堕棿/璺濈/鍖哄煙鎸夋潈閲嶈绠楁渶缁堜紭鍏堢骇锛屽啀鎵ц涓嬪彂銆�
+     */
+    private void dispatchTaskByFlow() {
+        Date now = new Date();
+        List<WrkMast> taskPool = wrkMastService.selectList(
+                new EntityWrapper<WrkMast>().eq("wrk_sts", 1L).orderBy("modi_time", true)
+        );
+        if (taskPool.isEmpty()) {
+            return;
         }
 
+        Date firstTaskTime = taskPool.get(0).getAppeTime() == null ? taskPool.get(0).getModiTime() : taskPool.get(0).getAppeTime();
+        if (firstTaskTime == null) {
+            return;
+        }
+        long oldestWaitMs = TimeCalculatorUtils.differenceInMilliseconds(firstTaskTime, now);
+        if (oldestWaitMs <= 1000) {
+            return;
+        }
+
+        List<BasDevpPosition> sitePositions = basDevpPositionService.selectList(
+                new EntityWrapper<BasDevpPosition>().orderBy("plc_position", true)
+        );
+        if (sitePositions == null || sitePositions.isEmpty()) {
+            return;
+        }
+
+        Map<Integer, BasDevpPosition> siteMap = new HashMap<>();
+        for (BasDevpPosition site : sitePositions) {
+            siteMap.put(site.getDevNo(), site);
+        }
+
+        List<RgvRuntimeState> availableRgvs = loadAvailableRgvs();
+        if (availableRgvs.isEmpty()) {
+            return;
+        }
+        Map<Integer, RgvRuntimeState> rgvStateMap = new HashMap<>();
+        List<TaskDispatchPriorityUtil.RgvSnapshot> snapshots = new ArrayList<>();
+        for (RgvRuntimeState rgv : availableRgvs) {
+            if (rgv.protocol == null || rgv.protocol.getRgvPos() == null) {
+                continue;
+            }
+            rgvStateMap.put(rgv.shuttle.getRgvNo(), rgv);
+            snapshots.add(new TaskDispatchPriorityUtil.RgvSnapshot(rgv.shuttle.getRgvNo(), rgv.protocol.getRgvPos()));
+        }
+        if (snapshots.isEmpty()) {
+            return;
+        }
+
+        double[] weights = resolveWeights(taskPool.size(), snapshots.size());
+        List<TaskDispatchPriorityUtil.DispatchPlan> plans = TaskDispatchPriorityUtil.rankDispatchPlans(
+                taskPool,
+                siteMap,
+                snapshots,
+                parseRegionPriorityMap(),
+                now,
+                Math.max(1L, priorityDistanceThreshold == null ? 10000L : priorityDistanceThreshold),
+                Math.max(1L, perimeter == null ? 1L : perimeter),
+                weights[0],
+                weights[1],
+                weights[2]
+        );
+        if (plans.isEmpty()) {
+            return;
+        }
+
+        TaskDispatchPriorityUtil.DispatchPlan topPlan = plans.get(0);
+        WrkMast task = topPlan.getTask();
+        if (task == null || task.getSourceStaNo() == null) {
+            return;
+        }
+        BasDevpPosition source = siteMap.get(task.getSourceStaNo());
+        if (source == null) {
+            return;
+        }
+        RgvRuntimeState chosenRgv = rgvStateMap.get(topPlan.getRgvNo());
+        if (chosenRgv == null) {
+            return;
+        }
+
+        log.info("浠诲姟浼樺厛绾ц绠�: wrkNo={} rgvNo={} final={} (time={} distance={} region={}) distance={} inRange={}",
+                task.getWrkNo(),
+                topPlan.getRgvNo(),
+                topPlan.getFinalPriority(),
+                topPlan.getTimePriority(),
+                topPlan.getDistancePriority(),
+                topPlan.getRegionPriority(),
+                topPlan.getDistance(),
+                topPlan.isInRange());
+
+        if (topPlan.isInRange() && canFetchFromRoam(chosenRgv.protocol, source.getPlcPosition())) {
+            if (issueFetchTask(task, chosenRgv)) {
+                updateStePosition();
+            }
+            return;
+        }
+        issueRoamTask(chosenRgv, source.getPlcPosition());
+    }
+
+    private List<RgvRuntimeState> loadAvailableRgvs() {
+        List<RgvRuntimeState> result = new ArrayList<>();
+        List<BasCircularShuttle> shuttles = basCircularShuttleService.selectList(
+                new EntityWrapper<BasCircularShuttle>().orderBy("rgv_id", true)
+        );
+        if (shuttles == null || shuttles.isEmpty()) {
+            return result;
+        }
+
+        for (BasCircularShuttle shuttle : shuttles) {
+            try {
+                if (shuttle.getStatus() != 0) {
+                    continue;
+                }
+                RgvThread rgvThread = (RgvThread) SlaveConnection.get(SlaveType.Rgv, shuttle.getRgvNo());
+                if (rgvThread == null) {
+                    continue;
+                }
+                RgvProtocol protocol = rgvThread.getRgvProtocol();
+                if (!isAvailableRgv(protocol)) {
+                    continue;
+                }
+                if (isRgvRunningTask(shuttle.getRgvNo())) {
+                    continue;
+                }
+                result.add(new RgvRuntimeState(shuttle, protocol));
+            } catch (Exception ignore) {
+            }
+        }
+        return result;
+    }
+
+    private boolean isAvailableRgv(RgvProtocol protocol) {
+        return protocol != null
+                && protocol.getModeType() == RgvModeType.AUTO
+                && (protocol.getStatusType() == RgvStatusType.IDLE || protocol.getStatusType() == RgvStatusType.ROAM)
+                && protocol.getTaskNo1() == 0
+                && protocol.getRgvPosInt() != 0
+                && protocol.getAlarm() == 0;
+    }
+
+    private boolean isRgvRunningTask(Integer rgvNo) {
+        List<WrkMast> running = wrkMastService.selectList(
+                new EntityWrapper<WrkMast>().eq("rgv_no", rgvNo).eq("wrk_sts", 2L)
+        );
+        return running != null && !running.isEmpty();
+    }
+
+    private boolean canFetchFromRoam(RgvProtocol protocol, long sourcePos) {
+        if (protocol.getStatusType() != RgvStatusType.ROAM) {
+            return true;
+        }
+        if (protocol.getInstantaneousSpeed() == null || acceleration == null || acceleration == 0) {
+            return true;
+        }
+        double finalVelocity = 0.0;
+        double distance = (Math.pow(finalVelocity, 2) - Math.pow(protocol.getInstantaneousSpeed() / 60, 2)) / (2 * acceleration);
+        double threshold = distance * proportion + (protocol.getInstantaneousSpeed() / 60) * proportion * rgvDate;
+        double sourceDistance = SortTheExecutionOfTheCarUtil.LatelyAndLessThan(sourcePos, protocol.getRgvPos(), perimeter);
+        return !(threshold > sourceDistance);
+    }
+
+    private boolean issueFetchTask(WrkMast task, RgvRuntimeState rgv) {
+        RgvCommand command = new RgvCommand();
+        command.setRgvNo(rgv.shuttle.getRgvNo());
+        command.setAckFinish1((short) 0);
+        command.setTaskNo1(task.getWrkNo().shortValue());
+        command.setTaskMode1(RgvTaskModeType.FETCH_PUT);
+        command.setSourceStaNo1(task.getSourceStaNo().shortValue());
+        command.setDestinationStaNo1(task.getStaNo().shortValue());
+        command.setCommand((short) 1);
+        command.setRgvSome(rgv.shuttle.getRgvSome() == 1 ? (short) 1 : (short) 0);
+
+        if (!MessageQueue.offer(SlaveType.Rgv, rgv.shuttle.getRgvNo(), new Task(2, command))) {
+            task.setLogErrTime(new Date());
+            task.setLogErrMemo("RGV鍛戒护涓嬪彂澶辫触锛孯GV鍙�={" + rgv.shuttle.getRgvNo() + "}===>璺宠繃");
+            wrkMastService.updateById(task);
+            log.error("RGV鍛戒护涓嬪彂澶辫触锛孯GV鍙�={}锛屼换鍔℃暟鎹�={}", rgv.shuttle.getRgvNo(), JSON.toJSON(command));
+            return false;
+        }
+
+        Date now = new Date();
+        task.setWrkSts(2L);
+        task.setRgvNo(rgv.shuttle.getRgvNo());
+        task.setAppeTime(now);
+        task.setCrnStrTime(now);
+        wrkMastService.updateById(task);
+        log.info("RGV鍛戒护涓嬪彂鎴愬姛锛孯GV鍙�={}锛屼换鍔″彿={}锛宻ource={}锛宼arget={}",
+                rgv.shuttle.getRgvNo(), task.getWrkNo(), task.getSourceStaNo(), task.getStaNo());
+        return true;
+    }
+
+    private void issueRoamTask(RgvRuntimeState rgv, long sourcePos) {
+        if (rgv == null || rgv.protocol == null) {
+            return;
+        }
+        if (rgv.protocol.getStatusType() != RgvStatusType.IDLE) {
+            return;
+        }
+        long destination = getRoamDestination(sourcePos);
+        if (!MessageQueue.offer(SlaveType.Rgv, rgv.shuttle.getRgvNo(), new Task(5, destination))) {
+            log.error("RGV婕父浠诲姟涓嬪彂澶辫触锛孯GV鍙�={}锛岀洰鐨勫湴={}", rgv.shuttle.getRgvNo(), destination);
+            return;
+        }
+        log.info("RGV婕父浠诲姟涓嬪彂鎴愬姛锛孯GV鍙�={}锛岀洰鐨勫湴={}", rgv.shuttle.getRgvNo(), destination);
+    }
+
+    private long getRoamDestination(long sourcePos) {
+        long destination = sourcePos - taskRunPerimeter + 10000;
+        if (destination > perimeter) {
+            return 10000L;
+        }
+        if (destination <= 0) {
+            destination = perimeter + destination;
+        }
+        return destination;
+    }
+
+    private Map<Integer, Double> parseRegionPriorityMap() {
+        String raw = regionPriorityValues == null ? "" : regionPriorityValues.trim();
+        if (raw.equals(cachedRegionPriorityRaw)) {
+            return cachedRegionPriorityMap;
+        }
+        Map<Integer, Double> regionMap = new HashMap<>();
+        if (raw.isEmpty()) {
+            cachedRegionPriorityRaw = raw;
+            cachedRegionPriorityMap = regionMap;
+            return regionMap;
+        }
+        String[] items = raw.split(",");
+        for (String item : items) {
+            if (item == null || item.trim().isEmpty()) {
+                continue;
+            }
+            String[] pair = item.split(":");
+            if (pair.length != 2) {
+                continue;
+            }
+            try {
+                Integer region = Integer.valueOf(pair[0].trim());
+                Double priority = Double.valueOf(pair[1].trim());
+                if (priority > 1D) {
+                    priority = 1D;
+                } else if (priority < -1D) {
+                    priority = -1D;
+                }
+                regionMap.put(region, priority);
+            } catch (Exception ignore) {
+            }
+        }
+        cachedRegionPriorityRaw = raw;
+        cachedRegionPriorityMap = regionMap;
+        return regionMap;
+    }
+
+    private double[] resolveWeights(int pendingTaskCount, int availableRgvCount) {
+        double timeW = priorityTimeWeight == null ? 0.4D : priorityTimeWeight;
+        double distanceW = priorityDistanceWeight == null ? 0.4D : priorityDistanceWeight;
+        double regionW = priorityRegionWeight == null ? 0.2D : priorityRegionWeight;
+
+        double capacity = Math.max(1D, availableRgvCount * 2D);
+        double loadFactor = Math.min(1D, pendingTaskCount / capacity);
+        if (loadFactor > 0.7D) {
+            timeW = Math.min(0.55D, timeW + 0.10D);
+            distanceW = Math.max(0.10D, distanceW - 0.05D);
+        } else if (loadFactor < 0.4D) {
+            timeW = Math.max(0.25D, timeW - 0.05D);
+            distanceW = Math.min(0.55D, distanceW + 0.05D);
+        }
+
+        double sum = Math.abs(timeW) + Math.abs(distanceW) + Math.abs(regionW);
+        if (sum <= 0D) {
+            return new double[]{0.4D, 0.4D, 0.2D};
+        }
+        return new double[]{timeW / sum, distanceW / sum, regionW / sum};
+    }
+
+    private static class RgvRuntimeState {
+        private final BasCircularShuttle shuttle;
+        private final RgvProtocol protocol;
+
+        private RgvRuntimeState(BasCircularShuttle shuttle, RgvProtocol protocol) {
+            this.shuttle = shuttle;
+            this.protocol = protocol;
+        }
     }
 
     //鑾峰彇灏忚溅鍙栨斁浠诲姟鍒楄〃澶辫触
diff --git a/src/main/java/com/zy/asrs/utils/DistancePriorityUtil.java b/src/main/java/com/zy/asrs/utils/DistancePriorityUtil.java
new file mode 100644
index 0000000..8341373
--- /dev/null
+++ b/src/main/java/com/zy/asrs/utils/DistancePriorityUtil.java
@@ -0,0 +1,41 @@
+package com.zy.asrs.utils;
+
+/**
+ * 璺濈浼樺厛绾у伐鍏�:
+ * 1) 璺濈 <= 闃堝��: 浼樺厛绾� [0,1], 瓒婅繎瓒婇珮
+ * 2) 璺濈 > 闃堝��: 浼樺厛绾� [0,-1], 瓒婅繙瓒婁綆
+ */
+public final class DistancePriorityUtil {
+
+    private DistancePriorityUtil() {
+    }
+
+    public static double calculate(long distance, long threshold, long perimeter) {
+        if (threshold <= 0L || perimeter <= 0L) {
+            return 0D;
+        }
+        long d = Math.max(0L, distance);
+        if (d <= threshold) {
+            double score = 1D - ((double) d / (double) threshold);
+            return clamp(score, 0D, 1D);
+        }
+        long outside = d - threshold;
+        long outsideMax = Math.max(1L, perimeter - threshold);
+        double score = -((double) outside / (double) outsideMax);
+        return clamp(score, -1D, 0D);
+    }
+
+    public static boolean isInRange(long distance, long threshold) {
+        return threshold > 0L && distance <= threshold;
+    }
+
+    private static double clamp(double value, double min, double max) {
+        if (value < min) {
+            return min;
+        }
+        if (value > max) {
+            return max;
+        }
+        return value;
+    }
+}
diff --git a/src/main/java/com/zy/asrs/utils/PriorityWeightCalculatorUtil.java b/src/main/java/com/zy/asrs/utils/PriorityWeightCalculatorUtil.java
new file mode 100644
index 0000000..68eada3
--- /dev/null
+++ b/src/main/java/com/zy/asrs/utils/PriorityWeightCalculatorUtil.java
@@ -0,0 +1,41 @@
+package com.zy.asrs.utils;
+
+/**
+ * 鏉冮噸浼樺厛绾ц绠楀伐鍏�:
+ * 鎸夋潈閲嶈绠楁椂闂�/璺濈/鍖哄煙鎬讳紭鍏堢骇锛屽苟闄愬埗鍒� [-1, 1]
+ */
+public final class PriorityWeightCalculatorUtil {
+
+    private PriorityWeightCalculatorUtil() {
+    }
+
+    public static double calculate(double timePriority,
+                                   double distancePriority,
+                                   double regionPriority,
+                                   double timeWeight,
+                                   double distanceWeight,
+                                   double regionWeight) {
+        double sum = Math.abs(timeWeight) + Math.abs(distanceWeight) + Math.abs(regionWeight);
+        if (sum <= 0D) {
+            timeWeight = 1D;
+            distanceWeight = 1D;
+            regionWeight = 1D;
+            sum = 3D;
+        }
+        double t = timeWeight / sum;
+        double d = distanceWeight / sum;
+        double r = regionWeight / sum;
+        double score = timePriority * t + distancePriority * d + regionPriority * r;
+        return clamp(score, -1D, 1D);
+    }
+
+    private static double clamp(double value, double min, double max) {
+        if (value < min) {
+            return min;
+        }
+        if (value > max) {
+            return max;
+        }
+        return value;
+    }
+}
diff --git a/src/main/java/com/zy/asrs/utils/TaskDispatchPriorityUtil.java b/src/main/java/com/zy/asrs/utils/TaskDispatchPriorityUtil.java
new file mode 100644
index 0000000..1bb4875
--- /dev/null
+++ b/src/main/java/com/zy/asrs/utils/TaskDispatchPriorityUtil.java
@@ -0,0 +1,209 @@
+package com.zy.asrs.utils;
+
+import com.zy.asrs.entity.BasDevpPosition;
+import com.zy.asrs.entity.WrkMast;
+
+import java.util.*;
+
+/**
+ * 浠诲姟涓嬪彂浼樺厛绾у伐鍏�:
+ * 鍩轰簬鏃堕棿銆佽窛绂汇�佸尯鍩熻绠楁渶缁堜紭鍏堢骇锛屽苟杩斿洖鎺掑簭鍚庣殑浠诲姟鍒嗛厤寤鸿銆�
+ */
+public final class TaskDispatchPriorityUtil {
+
+    private TaskDispatchPriorityUtil() {
+    }
+
+    public static List<DispatchPlan> rankDispatchPlans(List<WrkMast> taskPool,
+                                                       Map<Integer, BasDevpPosition> siteMap,
+                                                       List<RgvSnapshot> rgvSnapshots,
+                                                       Map<Integer, Double> regionPriorityMap,
+                                                       Date now,
+                                                       long distanceThreshold,
+                                                       long perimeter,
+                                                       double timeWeight,
+                                                       double distanceWeight,
+                                                       double regionWeight) {
+        if (taskPool == null || taskPool.isEmpty() || siteMap == null || rgvSnapshots == null || rgvSnapshots.isEmpty()) {
+            return Collections.emptyList();
+        }
+
+        Date calcNow = now == null ? new Date() : now;
+        long maxWaitMs = 0L;
+        for (WrkMast task : taskPool) {
+            Date createTime = getTaskCreateTime(task);
+            if (task == null || createTime == null) {
+                continue;
+            }
+            long waitMs = Math.max(0L, calcNow.getTime() - createTime.getTime());
+            if (waitMs > maxWaitMs) {
+                maxWaitMs = waitMs;
+            }
+        }
+
+        Set<Integer> usedSource = new HashSet<>();
+        List<DispatchPlan> plans = new ArrayList<>();
+        for (WrkMast task : taskPool) {
+            if (task == null || task.getSourceStaNo() == null || task.getStaNo() == null) {
+                continue;
+            }
+            if (usedSource.contains(task.getSourceStaNo())) {
+                continue;
+            }
+            BasDevpPosition source = siteMap.get(task.getSourceStaNo());
+            if (source == null) {
+                continue;
+            }
+
+            RgvChoice choice = chooseBestRgv(source.getPlcPosition(), rgvSnapshots, distanceThreshold, perimeter);
+            if (choice == null) {
+                continue;
+            }
+
+            double timePriorityByWindow = TimePriorityUtil.calculate(getTaskCreateTime(task), calcNow, maxWaitMs);
+            double timePriorityByCurve = TimePriorityUtil.calculateDynamic(getTaskCreateTime(task), calcNow, 120D, 300D, 0.0083D);
+            double timePriority = Math.max(timePriorityByWindow, timePriorityByCurve);
+            double distancePriority = DistancePriorityUtil.calculate(choice.distance, distanceThreshold, perimeter);
+            double regionPriority = resolveRegionPriority(source.getDevRegion(), regionPriorityMap);
+            double finalPriority = PriorityWeightCalculatorUtil.calculate(
+                    timePriority, distancePriority, regionPriority, timeWeight, distanceWeight, regionWeight
+            );
+            plans.add(new DispatchPlan(task, choice.rgvNo, choice.distance, DistancePriorityUtil.isInRange(choice.distance, distanceThreshold),
+                    timePriority, distancePriority, regionPriority, finalPriority));
+            usedSource.add(task.getSourceStaNo());
+        }
+
+        plans.sort(
+                Comparator.comparingDouble(DispatchPlan::getFinalPriority).reversed()
+                        .thenComparingDouble(DispatchPlan::getDistancePriority).reversed()
+                        .thenComparingDouble(DispatchPlan::getTimePriority).reversed()
+                        .thenComparingLong(DispatchPlan::getDistance)
+                        .thenComparingLong(p -> p.task.getWrkNo() == null ? Long.MAX_VALUE : p.task.getWrkNo())
+        );
+        return plans;
+    }
+
+    private static RgvChoice chooseBestRgv(long sourcePos, List<RgvSnapshot> rgvSnapshots, long distanceThreshold, long perimeter) {
+        RgvChoice best = null;
+        for (RgvSnapshot snapshot : rgvSnapshots) {
+            if (snapshot == null || snapshot.rgvNo == null || snapshot.position == null) {
+                continue;
+            }
+            long distance = ringDistance(sourcePos, snapshot.position, perimeter);
+            double distancePriority = DistancePriorityUtil.calculate(distance, distanceThreshold, perimeter);
+            if (best == null || distancePriority > best.distancePriority ||
+                    (distancePriority == best.distancePriority && distance < best.distance)) {
+                best = new RgvChoice(snapshot.rgvNo, distance, distancePriority);
+            }
+        }
+        return best;
+    }
+
+    private static long ringDistance(long sourcePos, long rgvPos, long perimeter) {
+        return SortTheExecutionOfTheCarUtil.LatelyAndLessThan(sourcePos, rgvPos, Math.max(1L, perimeter)).longValue();
+    }
+
+    private static Date getTaskCreateTime(WrkMast task) {
+        if (task == null) {
+            return null;
+        }
+        if (task.getAppeTime() != null) {
+            return task.getAppeTime();
+        }
+        return task.getModiTime();
+    }
+
+    private static double resolveRegionPriority(Integer region, Map<Integer, Double> regionPriorityMap) {
+        if (region == null || regionPriorityMap == null || regionPriorityMap.isEmpty()) {
+            return 0D;
+        }
+        Double score = regionPriorityMap.get(region);
+        if (score == null) {
+            return 0D;
+        }
+        if (score > 1D) {
+            return 1D;
+        }
+        if (score < -1D) {
+            return -1D;
+        }
+        return score;
+    }
+
+    public static class RgvSnapshot {
+        private final Integer rgvNo;
+        private final Long position;
+
+        public RgvSnapshot(Integer rgvNo, Long position) {
+            this.rgvNo = rgvNo;
+            this.position = position;
+        }
+    }
+
+    public static class DispatchPlan {
+        private final WrkMast task;
+        private final Integer rgvNo;
+        private final long distance;
+        private final boolean inRange;
+        private final double timePriority;
+        private final double distancePriority;
+        private final double regionPriority;
+        private final double finalPriority;
+
+        public DispatchPlan(WrkMast task, Integer rgvNo, long distance, boolean inRange,
+                            double timePriority, double distancePriority, double regionPriority, double finalPriority) {
+            this.task = task;
+            this.rgvNo = rgvNo;
+            this.distance = distance;
+            this.inRange = inRange;
+            this.timePriority = timePriority;
+            this.distancePriority = distancePriority;
+            this.regionPriority = regionPriority;
+            this.finalPriority = finalPriority;
+        }
+
+        public WrkMast getTask() {
+            return task;
+        }
+
+        public Integer getRgvNo() {
+            return rgvNo;
+        }
+
+        public long getDistance() {
+            return distance;
+        }
+
+        public boolean isInRange() {
+            return inRange;
+        }
+
+        public double getTimePriority() {
+            return timePriority;
+        }
+
+        public double getDistancePriority() {
+            return distancePriority;
+        }
+
+        public double getRegionPriority() {
+            return regionPriority;
+        }
+
+        public double getFinalPriority() {
+            return finalPriority;
+        }
+    }
+
+    private static class RgvChoice {
+        private final Integer rgvNo;
+        private final long distance;
+        private final double distancePriority;
+
+        private RgvChoice(Integer rgvNo, long distance, double distancePriority) {
+            this.rgvNo = rgvNo;
+            this.distance = distance;
+            this.distancePriority = distancePriority;
+        }
+    }
+}
diff --git a/src/main/java/com/zy/asrs/utils/TimePriorityUtil.java b/src/main/java/com/zy/asrs/utils/TimePriorityUtil.java
new file mode 100644
index 0000000..9098419
--- /dev/null
+++ b/src/main/java/com/zy/asrs/utils/TimePriorityUtil.java
@@ -0,0 +1,64 @@
+package com.zy.asrs.utils;
+
+import java.util.Date;
+
+/**
+ * 鏃堕棿浼樺厛绾у伐鍏�:
+ * 鍙傝�僑chedulingCarUtil浼樺寲:
+ * 闃堝�煎墠鍩虹鍊硷紝闃堝�煎悗鎸囨暟澧為暱锛岃秴闀跨瓑寰呯嚎鎬цˉ鍋匡紝鏈�缁堝綊涓�鍖栧埌 [0, 1]
+ */
+public final class TimePriorityUtil {
+
+    private static final double BASE_PRIORITY = 0.2D;
+    private static final int CACHE_SIZE = 1800;
+    private static final double[] EXP_CACHE = new double[CACHE_SIZE];
+
+    static {
+        for (int i = 0; i < CACHE_SIZE; i++) {
+            EXP_CACHE[i] = 0.8D * (1D - Math.exp(-0.02D * i));
+        }
+    }
+
+    private TimePriorityUtil() {
+    }
+
+    public static double calculate(Date createTime, Date now, long maxWaitMs) {
+        if (createTime == null || now == null || maxWaitMs <= 0L) {
+            return 0D;
+        }
+        long waitMs = Math.max(0L, now.getTime() - createTime.getTime());
+        return clamp01((double) waitMs / (double) maxWaitMs);
+    }
+
+    public static double calculateDynamic(Date createTime,
+                                          Date now,
+                                          double waitThresholdSeconds,
+                                          double linearThresholdSeconds,
+                                          double linearFactor) {
+        if (createTime == null || now == null) {
+            return 0D;
+        }
+        double waitSeconds = Math.max(0D, (now.getTime() - createTime.getTime()) / 1000D);
+        if (waitSeconds <= waitThresholdSeconds) {
+            return BASE_PRIORITY;
+        }
+        double exceedSeconds = waitSeconds - waitThresholdSeconds;
+        double expPart = exceedSeconds < CACHE_SIZE
+                ? EXP_CACHE[(int) exceedSeconds]
+                : 0.8D * (1D - Math.exp(-0.02D * exceedSeconds));
+        double linearPart = exceedSeconds > linearThresholdSeconds
+                ? linearFactor * (exceedSeconds - linearThresholdSeconds)
+                : 0D;
+        return clamp01(BASE_PRIORITY + expPart + linearPart);
+    }
+
+    private static double clamp01(double value) {
+        if (value < 0D) {
+            return 0D;
+        }
+        if (value > 1D) {
+            return 1D;
+        }
+        return value;
+    }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index a0544d1..a0f11be 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -59,6 +59,17 @@
   rgvCount: 10
   # 寤惰繜鏃堕棿
   rgvDate: 0.5
+  # 浠诲姟浼樺厛绾у弬鏁�
+  priority:
+    # 璺濈闃堝��(杞ㄩ亾鍗曚綅)锛�<=璇ュ�艰窛绂讳紭鍏堢骇涓篬0,1]锛�>璇ュ�间负[0,-1]
+    distance-threshold: 10000
+    # 鏉冮噸閰嶇疆(浼氬仛褰掍竴鍖栵紝寤鸿鍜岀害绛変簬1)
+    weight:
+      time: 0.4
+      distance: 0.4
+      region: 0.2
+    # 鍖哄煙浼樺厛绾�: region:priority锛屽涓敤閫楀彿鍒嗛殧锛宲riority鑼冨洿[-1,1]
+    region-values: "1:1,2:0.6,3:0.2,4:-0.2"
 
 # 涓嬩綅鏈洪厤缃�
 wcs-slave:
@@ -141,4 +152,4 @@
     port: 502
     rack: 0
     slot: 0
-    demo: false
\ No newline at end of file
+    demo: false

--
Gitblit v1.9.1