package com.hivekion.room.bean;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hivekion.Global;
import com.hivekion.baseData.entity.Scenario;
import com.hivekion.baseData.service.ScenarioService;
import com.hivekion.common.MultiPointGeoPosition;
import com.hivekion.common.entity.ResponseCmdInfo;
import com.hivekion.common.redis.RedisUtil;
import com.hivekion.common.uuid.IdUtils;
import com.hivekion.enums.WsCmdTypeEnum;
import com.hivekion.room.RoomManager;
import com.hivekion.room.func.TaskAction;
import com.hivekion.scenario.entity.ScenarioResource;
import com.hivekion.scenario.entity.ScenarioTask;
import com.hivekion.scenario.service.impl.BattleSupplierServiceImpl;
import com.hivekion.scenario.service.impl.ScenarioResourceServiceImpl;
import com.hivekion.scenario.service.impl.ScenarioTaskServiceImpl;
import com.hivekion.statistic.bean.EditScenarioInfo;
import com.hivekion.statistic.bean.ScenarioInfo;
import com.hivekion.statistic.bean.StatisticBean;
import com.hivekion.statistic.service.impl.StatisticServiceImpl;
import com.hivekion.supplier.entity.SupplierRequest;
import com.hivekion.supplier.service.impl.SupplierRequestServiceImpl;
import com.hivekion.team.entity.Teaminfo;
import com.hivekion.team.service.impl.TeaminfoServiceImpl;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.reactive.function.client.WebClient;
/**
* [类的简要说明]
*
* [详细描述,可选]
*
*
* @author LiDongYU
* @since 2025/7/22
*/
@Slf4j
public abstract class AbtParentTask implements TaskAction {
protected final AtomicBoolean taskFinishedStatus = new AtomicBoolean(false);
/**
* 油料消耗速率
*/
protected double fuelConsumption = 0;
protected double fuelThreshold = 98;
/**
* 开始点坐标
*/
private final AtomicReference startPoint = new AtomicReference<>();
/**
* 距离和坐标的对应关系
*/
protected final TreeMap distanceInfoMap = new TreeMap<>();
//任务数据
protected final ScenarioTask scenarioTask;
//房间ID
protected final String roomId;
//http请求
protected WebClient webClient = WebClient.create();
protected final AtomicReference coordinateReference = new AtomicReference<>();
/**
* 需求产生标志
*/
protected final AtomicBoolean requestFlag = new AtomicBoolean(false);
private StatisticBean statisticBean;
public AbtParentTask(ScenarioTask scenarioTask, String roomId) {
this.scenarioTask = scenarioTask;
this.roomId = roomId;
Scenario scenario = SpringUtil.getBean(ScenarioService.class)
.getScenarioById(scenarioTask.getScenarioId());
statisticBean = SpringUtil.getBean(StatisticServiceImpl.class)
.statistic(scenarioTask.getResourceId());
initEnv();
}
public void addScheduledExecutorServiceRefenceToRoom(
ScheduledExecutorService scheduledExecutorService) {
RoomManager.addFuture(scheduledExecutorService, this.roomId);
}
@Override
public void doSomeThing() {
}
@Override
public String getId() {
return scenarioTask.getId();
}
@Override
public String getType() {
return scenarioTask.getTaskType();
}
//获取房间的持续时间
public long getDuringTime() {
return RoomManager.getRoomDuringTime(this.roomId);
}
//获取房间状态
public boolean getRoomStatus() {
return RoomManager.isRunning(roomId);
}
public void createBattleTaskOnTimingHandle(BizTaskOnTiming bizTaskOnTiming) {
ScheduledExecutorService schedule = Executors.newScheduledThreadPool(
1);
schedule.scheduleWithFixedDelay(() -> {
bizTaskOnTiming.execTask();
}, 0, 1, TimeUnit.SECONDS);
//房间统一管理定时器;房间关闭后,定时器销毁
addScheduledExecutorServiceRefenceToRoom(schedule);
}
/**
* 初始化环境
*/
private void initEnv() {
try {
//获取油品消耗规则
String fuelConsumptionStr = SpringUtil.getBean(Environment.class)
.getProperty("fuel.spreed");
fuelConsumption = Double.parseDouble(fuelConsumptionStr == null ? "0" : fuelConsumptionStr);
fuelThreshold = Double.parseDouble(SpringUtil.getBean(Environment.class)
.getProperty("fuel.warn", "0"));
log.info("初始化::{}-油料消耗速度::{},油料最低阈值::{},当前油料::{}",
this.scenarioTask.getResourceId(),
fuelConsumptionStr, fuelThreshold, getCurrentFuel());
} catch (Exception e) {
log.error("init env exception", e);
}
}
protected void initPath() {
try {
log.info("init path");
String url = SpringUtil.getBean(Environment.class).getProperty("path.planning.url");
String params = url + "?"
+ "profile=car"
+ "&point=" + scenarioTask.getFromLat() + ","
+ scenarioTask.getFromLng()
+ "&point=" + scenarioTask.getToLat() + ","
+ scenarioTask.getToLng()
+ "&points_encoded=false"
+ "&algorithm=alternative_route&alternative_route.max_paths=3";
log.info("params:;{}", params);
Room room = RoomManager.getRoom(this.roomId);
Map resourceMap = room.getScenarioResourceMap();
//获取路线信息
String result = webClient.get().uri(params)
.retrieve()
.bodyToMono(String.class)
.block();
log.info("init path finished ::{}", result);
JSONObject pointJson = JSON.parseObject(result);
//获取路径点
if (pointJson != null) {
JSONObject pointsObj = pointJson.getJSONArray("paths").getJSONObject(0)
.getJSONObject("points");
JSONArray coordinates = pointsObj.getJSONArray("coordinates");
//组装信息
Map dataMap = new HashMap<>();
dataMap.put("resourceId", scenarioTask.getResourceId());
dataMap.put("points", coordinates);
dataMap.put("teamType", resourceMap.get(this.scenarioTask.getResourceId()).getType());
if (RoomManager.getRoom(roomId) != null) {
RoomManager.getRoom(roomId)
.addResourcePath(this.scenarioTask.getResourceId(), coordinates);
}
//推送路径任务
Global.sendCmdInfoQueue.add(
ResponseCmdInfo.create(WsCmdTypeEnum.PATH_INIT.getCode(), roomId,
scenarioTask.getScenarioId(), dataMap));
SpringUtil.getBean(RedisUtil.class).hset(
scenarioTask.getScenarioId() + "-" + roomId + "-" + scenarioTask.getResourceId(),
"init_path", JSON.toJSONString(coordinates));
//计算各个点的累计距离和坐标的对应关系
double beforeLng = Double.parseDouble(scenarioTask.getFromLng());
double beforeLat = Double.parseDouble(scenarioTask.getFromLat());
double total = 0;
for (int i = 0; i < coordinates.size(); i++) {
JSONArray coordinate = coordinates.getJSONArray(i);
Double lng = coordinate.getDouble(0);
Double lat = coordinate.getDouble(1);
double distance = MultiPointGeoPosition.haversine(beforeLat, beforeLng, lat, lng);
//当前总距离
total = total + distance;
//定义坐标对象
Coordinate coordinateInfo = new Coordinate();
coordinateInfo.setLat(lat);
coordinateInfo.setLng(lng);
//记录距离和数组列表直接的索引关系
distanceInfoMap.put(total, coordinateInfo);
beforeLng = lng;
beforeLat = lat;
}
log.info("路线节点个数::{},总距离::{}",distanceInfoMap.size(),distanceInfoMap.lastKey());
//设置第一个开始位置
startPoint.set(distanceInfoMap.firstKey());
}
} catch (Exception e) {
log.error("error::", e);
}
}
protected void updatePath(double speed, TaskAction duringAction, TaskAction finishedAction) {
AtomicLong duringTime = new AtomicLong(0);
ScheduledExecutorService schedule = Executors.newScheduledThreadPool(
1);
schedule.scheduleWithFixedDelay(() -> {
try {
Room room = RoomManager.getRoom(this.roomId);
if (room == null || room.isTimeExpired()) {
log.error("房间不存在或者已经到达想定结束时间");
return;
}
if (this.getRoomStatus()) {
//自动生成的任务不需要判断油量;不要在生成新的任务
if (!"general".equals(scenarioTask.getFromSource())) {
double currentFuel = getCurrentFuel();
double totalFuel = statisticBean.getFuel().getTotal();
if (currentFuel <= 0 || totalFuel <= 0) {
log.error("{}:油量为零停止移动", this.scenarioTask.getResourceId());
return;
}
if (currentFuel * 100 / totalFuel < fuelThreshold && !requestFlag.get()) {
log.error("{}-油料不足,需要补充,新建需求和任务", scenarioTask.getResourceId());
requestFlag.set(true);
//需要产生需求
produceFuelRequest();
//产生任务
produceTask(currentFuel);
return;
}else{
log.info("======油料充足====={}=={}==={}===={}=======",currentFuel,totalFuel,fuelThreshold,requestFlag.get());
}
if (currentFuel * 100 / totalFuel < fuelThreshold) {
return;
}
}
if (distanceInfoMap.isEmpty()) {
return;
}
if (duringAction != null) {
duringAction.doSomeThing();
}
//跑动距离
double distance = duringTime.getAndAdd(RoomManager.getMag(roomId)) * speed;
//获取大与此距离的第一个路线点key
Entry endPoint = distanceInfoMap.ceilingEntry(distance);
if (endPoint == null) {
endPoint = distanceInfoMap.lastEntry();
}
log.info("当前距离{}",distance);
//ws数据
List dataList = new ArrayList<>();
HashMap