feat: 1:二维码统计明细 2:航线规划

This commit is contained in:
2026-01-08 23:12:25 +08:00
parent a9f1e1f4d4
commit 2b61492b15
61 changed files with 7639 additions and 1065 deletions
@@ -3,6 +3,7 @@ package com.central.device.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.model.Result;
import com.central.device.model.dto.BoatRouteCreateDTO;
import com.central.device.model.dto.BoatRouteDisplayUpdateDTO;
import com.central.device.model.dto.BoatRouteUpdateDTO;
import com.central.device.model.vo.BoatRouteDetailVO;
import com.central.device.model.vo.BoatRouteListVO;
@@ -130,4 +131,13 @@ public class BoatRouteController {
boatRouteService.publishRoute(routeId);
return Result.succeed(null, "发布成功");
}
@Operation(summary = "按设备批量更新航线模型显示状态")
@PutMapping("/display/device/{deviceSn}")
public Result<Void> updateShowInModelByDeviceSn(
@Parameter(description = "设备SN") @PathVariable String deviceSn,
@RequestBody @Validated BoatRouteDisplayUpdateDTO dto) {
boatRouteService.updateShowInModelByDeviceSn(deviceSn, dto.getRouteIds());
return Result.succeed(null, "航线模型显示状态更新成功");
}
}
@@ -1,8 +1,10 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.WaterBoundary;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.dto.WaterBoundaryCreateDTO;
import com.central.device.model.dto.WaterBoundaryDisplayUpdateDTO;
import com.central.device.model.vo.BoundaryCheckResultVO;
import com.central.device.model.vo.WaterBoundaryVO;
import com.central.device.service.IWaterBoundaryService;
@@ -40,16 +42,18 @@ public class WaterBoundaryController {
@GetMapping("/{boundaryId}")
public Result<WaterBoundaryVO> getBoundaryDetail(
@Parameter(description = "边界ID") @PathVariable String boundaryId) {
var boundary = waterBoundaryService.getByBoundaryId(boundaryId);
WaterBoundary boundary = waterBoundaryService.getByBoundaryId(boundaryId);
if (boundary == null) {
return Result.failed("边界不存在");
}
WaterBoundaryVO vo = new WaterBoundaryVO();
vo.setBoundaryId(boundary.getBoundaryId());
vo.setBoundaryName(boundary.getBoundaryName());
vo.setDeviceSn(boundary.getDeviceSn());
vo.setScenicId(boundary.getScenicId());
vo.setBoundaryType(boundary.getBoundaryType());
vo.setPolygonData(boundary.getPolygonData());
vo.setShowInModel(boundary.getShowInModel());
vo.setStatus(boundary.getStatus());
vo.setCreateTime(boundary.getCreateTime());
return Result.succeed(vo);
@@ -63,6 +67,14 @@ public class WaterBoundaryController {
return Result.succeed(list);
}
@Operation(summary = "获取设备边界列表")
@GetMapping("/list/device/{deviceSn}")
public Result<List<WaterBoundaryVO>> listByDeviceSn(
@Parameter(description = "设备SN") @PathVariable String deviceSn) {
List<WaterBoundaryVO> list = waterBoundaryService.listByDeviceSn(deviceSn);
return Result.succeed(list);
}
@Operation(summary = "检测点是否在边界内")
@GetMapping("/check/point")
public Result<Boolean> checkPoint(
@@ -107,4 +119,13 @@ public class WaterBoundaryController {
waterBoundaryService.deleteBoundary(boundaryId);
return Result.succeed(null, "删除成功");
}
@Operation(summary = "按设备批量更新标绘显示状态")
@PutMapping("/display/device/{deviceSn}")
public Result<Void> updateShowInModelByDeviceSn(
@Parameter(description = "设备SN") @PathVariable String deviceSn,
@RequestBody @Validated WaterBoundaryDisplayUpdateDTO dto) {
waterBoundaryService.updateShowInModelByDeviceSn(deviceSn, dto.getBoundaryIds());
return Result.succeed(null, "标绘显示状态更新成功");
}
}
@@ -97,6 +97,12 @@ public class BoatRoute implements Serializable {
@TableField("boundary_polygon")
private String boundaryPolygon;
/**
* 规划水域边界ID
*/
@TableField("boundary_id")
private String boundaryId;
/**
* 起点坐标(lng,lat)
*/
@@ -149,6 +155,12 @@ public class BoatRoute implements Serializable {
@TableField("is_template")
private Boolean isTemplate;
/**
* 是否在模型中显示航线:0-否,1-是
*/
@TableField("show_in_model")
private Integer showInModel;
/**
* 备注
*/
@@ -39,6 +39,12 @@ public class WaterBoundary implements Serializable {
@TableField("boundary_name")
private String boundaryName;
/**
* 绑定设备SN
*/
@TableField("device_sn")
private String deviceSn;
/**
* 所属景区ID
*/
@@ -91,6 +97,12 @@ public class WaterBoundary implements Serializable {
@TableField("model_id")
private String modelId;
/**
* 是否在模型中显示标绘:0-否,1-是
*/
@TableField("show_in_model")
private Integer showInModel;
// ========== 状态 ==========
/**
@@ -101,4 +101,25 @@ public interface BoatRouteMapper extends BaseMapper<BoatRoute> {
* @return 影响行数
*/
int setTemplate(@Param("routeId") String routeId, @Param("isTemplate") Boolean isTemplate);
/**
* 根据设备SN重置“模型中显示航线”状态(全部不显示)
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
* @return 影响行数
*/
int resetShowInModelByDeviceSn(@Param("deviceSn") String deviceSn, @Param("tenantId") String tenantId);
/**
* 根据设备SN批量设置“模型中显示航线”状态(指定ID集合显示)
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
* @param routeIds 需要显示的航线ID列表
* @return 影响行数
*/
int setShowInModelByRouteIds(@Param("deviceSn") String deviceSn,
@Param("tenantId") String tenantId,
@Param("routeIds") List<String> routeIds);
}
@@ -24,6 +24,15 @@ public interface WaterBoundaryMapper extends BaseMapper<WaterBoundary> {
*/
WaterBoundary selectByBoundaryId(@Param("boundaryId") String boundaryId);
/**
* 根据设备SN查询边界列表
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
* @return 边界列表
*/
List<WaterBoundary> selectByDeviceSn(@Param("deviceSn") String deviceSn, @Param("tenantId") String tenantId);
/**
* 根据景区ID查询边界列表
*
@@ -54,6 +63,27 @@ public interface WaterBoundaryMapper extends BaseMapper<WaterBoundary> {
*/
int updateStatus(@Param("boundaryId") String boundaryId, @Param("status") Integer status);
/**
* 根据设备SN重置显示标绘状态(全部不显示)
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
* @return 影响行数
*/
int resetShowInModelByDeviceSn(@Param("deviceSn") String deviceSn, @Param("tenantId") String tenantId);
/**
* 根据设备SN批量设置显示标绘状态(指定ID集合显示)
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
* @param boundaryIds 需要显示的边界ID列表
* @return 影响行数
*/
int setShowInModelByBoundaryIds(@Param("deviceSn") String deviceSn,
@Param("tenantId") String tenantId,
@Param("boundaryIds") List<String> boundaryIds);
/**
* 根据3D模型ID查询关联边界
*
@@ -49,6 +49,9 @@ public class BoatRouteCreateDTO {
@Schema(description = "备注")
private String remark;
@Schema(description = "是否在模型中显示航线:0-否,1-是(可选,默认0)", example = "0")
private Integer showInModel = 0;
@Schema(description = "航点列表", required = true)
@NotEmpty(message = "航点不能为空")
private List<BoatWaypointDTO> waypoints;
@@ -0,0 +1,23 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.util.List;
/**
* 无人船航线“模型中显示”状态更新DTO
*
* @author dzc
* @date 2026-01-08
*/
@Data
@Schema(description = "无人船航线模型显示状态更新请求")
public class BoatRouteDisplayUpdateDTO {
@Schema(description = "需要在模型中显示的航线ID列表(传空数组表示全隐)")
@NotNull(message = "routeIds不能为空(可传空数组)")
private List<String> routeIds;
}
@@ -37,6 +37,12 @@ public class BoatRouteUpdateDTO {
@Schema(description = "备注")
private String remark;
@Schema(description = "是否在模型中显示航线:0-否,1-是(可选)", example = "1")
private Integer showInModel;
@Schema(description = "规划水域边界ID(可选,修改规划水域时传)")
private String boundaryId;
@Schema(description = "航点列表(如果提供则更新所有航点)")
private List<BoatWaypointDTO> waypoints;
}
@@ -2,7 +2,6 @@ package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
@@ -21,8 +20,11 @@ public class WaterBoundaryCreateDTO {
@NotBlank(message = "边界名称不能为空")
private String boundaryName;
@Schema(description = "所属景区ID", required = true)
@NotNull(message = "景区ID不能为空")
@Schema(description = "绑定设备SN", required = true)
@NotBlank(message = "设备SN不能为空")
private String deviceSn;
@Schema(description = "所属景区ID(可选)")
private Long scenicId;
@Schema(description = "边界类型:navigable-可航行,obstacle-障碍物,restricted-禁行区")
@@ -43,4 +45,7 @@ public class WaterBoundaryCreateDTO {
@Schema(description = "关联3D模型ID")
private String modelId;
@Schema(description = "是否在模型中显示标绘:0-否,1-是(可选,默认1)")
private Integer showInModel = 1;
}
@@ -0,0 +1,23 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.util.List;
/**
* 水域边界标绘显示状态更新DTO
*
* @author dzc
* @date 2026-01-07
*/
@Data
@Schema(description = "水域边界标绘显示状态更新请求")
public class WaterBoundaryDisplayUpdateDTO {
@Schema(description = "需要在模型中显示的边界ID列表(传空数组表示全隐)")
@NotNull(message = "boundaryIds不能为空(可传空数组)")
private List<String> boundaryIds;
}
@@ -74,6 +74,12 @@ public class BoatRouteDetailVO {
@Schema(description = "是否为模板")
private Boolean isTemplate;
@Schema(description = "是否在模型中显示航线:0-否,1-是")
private Integer showInModel;
@Schema(description = "规划水域边界ID")
private String boundaryId;
@Schema(description = "备注")
private String remark;
@@ -49,6 +49,12 @@ public class BoatRouteListVO {
@Schema(description = "是否为模板")
private Boolean isTemplate;
@Schema(description = "是否在模型中显示航线:0-否,1-是")
private Integer showInModel;
@Schema(description = "规划水域边界ID")
private String boundaryId;
@Schema(description = "创建时间")
private LocalDateTime createTime;
}
@@ -22,6 +22,9 @@ public class WaterBoundaryVO {
@Schema(description = "边界名称")
private String boundaryName;
@Schema(description = "绑定设备SN")
private String deviceSn;
@Schema(description = "所属景区ID")
private Long scenicId;
@@ -43,6 +46,9 @@ public class WaterBoundaryVO {
@Schema(description = "来源类型")
private String sourceType;
@Schema(description = "是否在模型中显示标绘:0-否,1-是")
private Integer showInModel;
@Schema(description = "状态:0-禁用,1-启用")
private Integer status;
@@ -130,4 +130,12 @@ public interface IBoatRouteService extends IService<BoatRoute> {
* @param routeId 航线ID
*/
void publishRoute(String routeId);
/**
* 按设备批量更新“模型中显示航线”状态(未包含的航线会被置为不显示)
*
* @param deviceSn 设备SN
* @param routeIds 需要显示的航线ID列表
*/
void updateShowInModelByDeviceSn(String deviceSn, List<String> routeIds);
}
@@ -33,6 +33,14 @@ public interface IWaterBoundaryService extends IService<WaterBoundary> {
*/
WaterBoundary getByBoundaryId(String boundaryId);
/**
* 获取设备水域边界列表
*
* @param deviceSn 设备SN
* @return 边界列表
*/
List<WaterBoundaryVO> listByDeviceSn(String deviceSn);
/**
* 获取景区水域边界列表
*
@@ -83,4 +91,12 @@ public interface IWaterBoundaryService extends IService<WaterBoundary> {
* @param boundaryId 边界ID
*/
void deleteBoundary(String boundaryId);
/**
* 按设备维度批量更新“模型中显示标绘”状态:未包含的边界会被置为不显示
*
* @param deviceSn 设备SN
* @param boundaryIds 需要显示的边界ID列表(空列表表示全隐)
*/
void updateShowInModelByDeviceSn(String deviceSn, List<String> boundaryIds);
}
@@ -26,6 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -58,10 +59,12 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
route.setLoopCount(dto.getLoopCount());
route.setReturnMode(dto.getReturnMode());
route.setSafeDistance(dto.getSafeDistance());
route.setBoundaryId(dto.getBoundaryId());
route.setRemark(dto.getRemark());
route.setTenantId(LoginUserContextHolder.getCurrentTenantId());
route.setStatus(BoatRoute.RouteStatus.DRAFT.getCode());
route.setIsTemplate(false);
route.setShowInModel(dto.getShowInModel() != null ? dto.getShowInModel() : 0);
// 2. 计算航线统计信息
List<BoatWaypointDTO> waypoints = dto.getWaypoints();
@@ -167,6 +170,12 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
if (dto.getRemark() != null) {
route.setRemark(dto.getRemark());
}
if (dto.getShowInModel() != null) {
route.setShowInModel(dto.getShowInModel());
}
if (StrUtil.isNotBlank(dto.getBoundaryId())) {
route.setBoundaryId(StrUtil.trim(dto.getBoundaryId()));
}
// 如果提供了航点则更新航点
if (dto.getWaypoints() != null && !dto.getWaypoints().isEmpty()) {
@@ -193,6 +202,29 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
log.info("航线更新成功: routeId={}", routeId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateShowInModelByDeviceSn(String deviceSn, List<String> routeIds) {
String sn = StrUtil.trimToEmpty(deviceSn);
if (StrUtil.isBlank(sn)) {
throw new BusinessException("设备SN不能为空");
}
String tenantId = LoginUserContextHolder.getCurrentTenantId();
List<String> ids = routeIds == null ? Collections.emptyList() : routeIds.stream()
.filter(StrUtil::isNotBlank)
.map(StrUtil::trim)
.distinct()
.collect(Collectors.toList());
baseMapper.resetShowInModelByDeviceSn(sn, tenantId);
if (!ids.isEmpty()) {
baseMapper.setShowInModelByRouteIds(sn, tenantId, ids);
}
log.info("更新无人船航线模型显示状态成功: deviceSn={}, showCount={}", sn, ids.size());
}
@Override
public BoatRouteDetailVO getRouteDetail(String routeId) {
BoatRoute route = getByRouteId(routeId);
@@ -335,9 +367,11 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
throw new BusinessException("执行中的航线不能删除");
}
// 逻辑删除航线
route.setDeleted(1);
this.updateById(route);
// 逻辑删除航线:使用 MyBatis-Plus @TableLogic,避免手动更新字段在拦截器/策略下不生效
boolean removed = this.removeById(route.getId());
if (!removed) {
throw new BusinessException("删除失败(未找到可删除的航线记录)");
}
// 删除航点
waypointMapper.deleteByRouteId(routeId);
@@ -23,6 +23,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -45,6 +46,7 @@ public class WaterBoundaryServiceImpl extends ServiceImpl<WaterBoundaryMapper, W
WaterBoundary boundary = new WaterBoundary();
boundary.setBoundaryId(UUID.randomUUID().toString().replace("-", ""));
boundary.setBoundaryName(dto.getBoundaryName());
boundary.setDeviceSn(dto.getDeviceSn());
boundary.setScenicId(dto.getScenicId());
boundary.setBoundaryType(dto.getBoundaryType());
boundary.setPolygonData(dto.getPolygonData());
@@ -52,6 +54,7 @@ public class WaterBoundaryServiceImpl extends ServiceImpl<WaterBoundaryMapper, W
boundary.setArea(dto.getArea());
boundary.setSourceType(dto.getSourceType() != null ? dto.getSourceType() : WaterBoundary.SourceType.MANUAL.getCode());
boundary.setModelId(dto.getModelId());
boundary.setShowInModel(dto.getShowInModel() != null ? dto.getShowInModel() : 1);
boundary.setTenantId(LoginUserContextHolder.getCurrentTenantId());
boundary.setStatus(1); // 启用状态
@@ -66,6 +69,20 @@ public class WaterBoundaryServiceImpl extends ServiceImpl<WaterBoundaryMapper, W
return baseMapper.selectByBoundaryId(boundaryId);
}
@Override
public List<WaterBoundaryVO> listByDeviceSn(String deviceSn) {
String tenantId = LoginUserContextHolder.getCurrentTenantId();
List<WaterBoundary> boundaries = baseMapper.selectByDeviceSn(deviceSn, tenantId);
return boundaries.stream()
.map(b -> {
WaterBoundaryVO vo = BeanUtil.copyProperties(b, WaterBoundaryVO.class);
vo.setStatusDesc(b.getStatus() == 1 ? "启用" : "禁用");
vo.setBoundaryTypeDesc(WaterBoundary.BoundaryType.fromCode(b.getBoundaryType()).getDesc());
return vo;
})
.collect(Collectors.toList());
}
@Override
public List<WaterBoundaryVO> listByScenicId(Long scenicId) {
String tenantId = LoginUserContextHolder.getCurrentTenantId();
@@ -173,6 +190,30 @@ public class WaterBoundaryServiceImpl extends ServiceImpl<WaterBoundaryMapper, W
log.info("水域边界删除成功: boundaryId={}", boundaryId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateShowInModelByDeviceSn(String deviceSn, List<String> boundaryIds) {
String sn = StrUtil.trimToEmpty(deviceSn);
if (StrUtil.isBlank(sn)) {
throw new BusinessException("设备SN不能为空");
}
String tenantId = LoginUserContextHolder.getCurrentTenantId();
List<String> ids = boundaryIds == null ? Collections.emptyList() : boundaryIds.stream()
.filter(StrUtil::isNotBlank)
.map(StrUtil::trim)
.distinct()
.collect(Collectors.toList());
// 先全量重置为不显示,再批量置为显示(保证“选择几个就保存几个”)
baseMapper.resetShowInModelByDeviceSn(sn, tenantId);
if (!ids.isEmpty()) {
baseMapper.setShowInModelByBoundaryIds(sn, tenantId, ids);
}
log.info("更新水域边界标绘显示状态成功: deviceSn={}, showCount={}", sn, ids.size());
}
// ========== 私有方法 ==========
/**
@@ -16,6 +16,7 @@
<result column="total_duration" property="totalDuration" />
<result column="cruise_speed" property="cruiseSpeed" />
<result column="boundary_polygon" property="boundaryPolygon" />
<result column="boundary_id" property="boundaryId" />
<result column="start_point" property="startPoint" />
<result column="end_point" property="endPoint" />
<result column="loop_enabled" property="loopEnabled" />
@@ -24,6 +25,7 @@
<result column="safe_distance" property="safeDistance" />
<result column="status" property="status" />
<result column="is_template" property="isTemplate" />
<result column="show_in_model" property="showInModel" />
<result column="remark" property="remark" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
@@ -108,4 +110,28 @@
WHERE route_id = #{routeId}
</update>
<!-- 根据设备SN重置“模型中显示航线”状态(全部不显示) -->
<update id="resetShowInModelByDeviceSn">
UPDATE boat_route
SET show_in_model = 0,
update_time = NOW()
WHERE device_sn = #{deviceSn}
AND tenant_id = #{tenantId}
AND deleted = 0
</update>
<!-- 根据设备SN批量设置“模型中显示航线”状态(指定ID集合显示) -->
<update id="setShowInModelByRouteIds">
UPDATE boat_route
SET show_in_model = 1,
update_time = NOW()
WHERE device_sn = #{deviceSn}
AND tenant_id = #{tenantId}
AND deleted = 0
AND route_id IN
<foreach collection="routeIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
</mapper>
@@ -7,6 +7,7 @@
<id column="id" property="id" />
<result column="boundary_id" property="boundaryId" />
<result column="boundary_name" property="boundaryName" />
<result column="device_sn" property="deviceSn" />
<result column="scenic_id" property="scenicId" />
<result column="tenant_id" property="tenantId" />
<result column="boundary_type" property="boundaryType" />
@@ -15,6 +16,7 @@
<result column="area" property="area" />
<result column="source_type" property="sourceType" />
<result column="model_id" property="modelId" />
<result column="show_in_model" property="showInModel" />
<result column="status" property="status" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
@@ -28,6 +30,16 @@
AND deleted = 0
</select>
<!-- 根据设备SN查询边界列表 -->
<select id="selectByDeviceSn" resultMap="BaseResultMap">
SELECT * FROM water_boundary
WHERE device_sn = #{deviceSn}
AND tenant_id = #{tenantId}
AND deleted = 0
AND status = 1
ORDER BY create_time DESC
</select>
<!-- 根据景区ID查询边界列表 -->
<select id="selectByScenicId" resultMap="BaseResultMap">
SELECT * FROM water_boundary
@@ -57,6 +69,30 @@
WHERE boundary_id = #{boundaryId}
</update>
<!-- 根据设备SN重置显示标绘状态(全部不显示) -->
<update id="resetShowInModelByDeviceSn">
UPDATE water_boundary
SET show_in_model = 0,
update_time = NOW()
WHERE device_sn = #{deviceSn}
AND tenant_id = #{tenantId}
AND deleted = 0
</update>
<!-- 根据设备SN批量设置显示标绘状态(指定ID集合显示) -->
<update id="setShowInModelByBoundaryIds">
UPDATE water_boundary
SET show_in_model = 1,
update_time = NOW()
WHERE device_sn = #{deviceSn}
AND tenant_id = #{tenantId}
AND deleted = 0
AND boundary_id IN
<foreach collection="boundaryIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
<!-- 根据3D模型ID查询关联边界 -->
<select id="selectByModelId" resultMap="BaseResultMap">
SELECT * FROM water_boundary
@@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS `boat_route` (
-- 航线边界
`boundary_polygon` text COMMENT '水域边界多边形(GeoJSON)',
`boundary_id` varchar(64) DEFAULT NULL COMMENT '规划水域边界ID',
`start_point` varchar(128) COMMENT '起点坐标(lng,lat)',
`end_point` varchar(128) COMMENT '终点坐标(lng,lat)',
@@ -34,6 +35,7 @@ CREATE TABLE IF NOT EXISTS `boat_route` (
-- 状态字段
`status` tinyint DEFAULT 0 COMMENT '状态:0-草稿,1-已发布,2-执行中,3-已完成',
`is_template` tinyint DEFAULT 0 COMMENT '是否为模板:0-否,1-是',
`show_in_model` tinyint DEFAULT 0 COMMENT '是否在模型中显示航线:0-否,1-是',
`remark` varchar(512) DEFAULT NULL COMMENT '备注',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
@@ -49,6 +51,14 @@ CREATE TABLE IF NOT EXISTS `boat_route` (
KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='无人船航线表';
-- 兼容已存在表:补充“模型中显示航线”字段(若已存在可忽略)
-- ALTER TABLE `boat_route`
-- ADD COLUMN `show_in_model` tinyint DEFAULT 0 COMMENT '是否在模型中显示航线:0-否,1-是' AFTER `is_template`;
-- 兼容已存在表:补充“规划水域边界ID”字段(若已存在可忽略)
-- ALTER TABLE `boat_route`
-- ADD COLUMN `boundary_id` varchar(64) DEFAULT NULL COMMENT '规划水域边界ID' AFTER `boundary_polygon`;
-- 2. 无人船航点表
CREATE TABLE IF NOT EXISTS `boat_waypoint` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
@@ -121,7 +131,8 @@ CREATE TABLE IF NOT EXISTS `water_boundary` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`boundary_id` varchar(64) NOT NULL COMMENT '边界唯一标识',
`boundary_name` varchar(128) NOT NULL COMMENT '边界名称',
`scenic_id` bigint NOT NULL COMMENT '所属景区ID',
`device_sn` varchar(64) DEFAULT NULL COMMENT '绑定设备SN',
`scenic_id` bigint DEFAULT NULL COMMENT '所属景区ID(可选)',
`tenant_id` varchar(64) NOT NULL COMMENT '租户ID',
-- 边界数据
@@ -133,6 +144,7 @@ CREATE TABLE IF NOT EXISTS `water_boundary` (
-- 来源
`source_type` varchar(32) DEFAULT 'manual' COMMENT '来源:manual-手动绘制,model-模型识别,import-导入',
`model_id` varchar(64) DEFAULT NULL COMMENT '关联3D模型ID',
`show_in_model` tinyint DEFAULT 0 COMMENT '是否在模型中显示标绘:0-否,1-是',
`status` tinyint DEFAULT 1 COMMENT '状态:0-禁用,1-启用',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
@@ -141,6 +153,7 @@ CREATE TABLE IF NOT EXISTS `water_boundary` (
PRIMARY KEY (`id`),
UNIQUE KEY `uk_boundary_id` (`boundary_id`),
KEY `idx_device_sn` (`device_sn`),
KEY `idx_scenic_id` (`scenic_id`),
KEY `idx_tenant_id` (`tenant_id`),
KEY `idx_boundary_type` (`boundary_type`)
@@ -0,0 +1,17 @@
-- ====================================================================
-- 水域边界表结构升级:增加 device_sn,并放宽 scenic_id 非空约束
-- 创建日期: 2026-01-06
-- 说明:用于已有环境的增量升级(请按需执行)
-- ====================================================================
-- 1) 增加 device_sn 字段(如已存在可忽略报错或自行判断)
ALTER TABLE `water_boundary`
ADD COLUMN `device_sn` varchar(64) DEFAULT NULL COMMENT '绑定设备SN' AFTER `boundary_name`;
-- 2) scenic_id 改为可空(如后续不再使用 scenic_id)
ALTER TABLE `water_boundary`
MODIFY COLUMN `scenic_id` bigint DEFAULT NULL COMMENT '所属景区ID(可选)';
-- 3) 增加索引
CREATE INDEX `idx_device_sn` ON `water_boundary` (`device_sn`);
@@ -0,0 +1,5 @@
-- 为水域边界增加“是否在模型中显示标绘”字段(用于图层管理持久化)
ALTER TABLE `water_boundary`
ADD COLUMN `show_in_model` tinyint DEFAULT 0 COMMENT '是否在模型中显示标绘:0-否,1-是' AFTER `model_id`;
CREATE INDEX `idx_show_in_model` ON `water_boundary` (`show_in_model`);
@@ -1,6 +1,8 @@
package com.central.order.controller;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantContextHolder;
@@ -10,7 +12,6 @@ import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.log.annotation.AuditLog;
import com.central.order.constants.OrderStatusConstants;
import com.central.order.enums.CommonStatus;
import com.central.order.enums.OrderStatus;
import com.central.order.feign.DeviceCenterService;
@@ -1515,4 +1516,99 @@ public class OrderController {
return Result.failed("获取订单信息异常: " + e.getMessage());
}
}
@Operation(summary = "二维码订单统计查询")
@Parameters({
@Parameter(name = "tenantId", description = "租户ID", in = ParameterIn.QUERY),
@Parameter(name = "includeChildren", description = "是否包含下级租户", in = ParameterIn.QUERY),
@Parameter(name = "qrcodeName", description = "二维码名称", in = ParameterIn.QUERY),
@Parameter(name = "codeId", description = "二维码Code", in = ParameterIn.QUERY),
@Parameter(name = "tourismId", description = "景区ID", in = ParameterIn.QUERY)
})
@GetMapping("/qrcode/order/statistics")
public Result getQrcodeOrderStatistics(@RequestParam Map<String, Object> params) {
log.info("查询二维码订单统计,params: {}", params);
try {
Map<String, Object> result = orderService.getQrcodeOrderStatistics(params);
return Result.succeed(result);
} catch (Exception e) {
log.error("查询二维码订单统计异常", e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "根据二维码ID查询订单列表")
@Parameters({
@Parameter(name = "page", description = "分页起始位置", required = true, in = ParameterIn.QUERY),
@Parameter(name = "limit", description = "分页结束位置", required = true, in = ParameterIn.QUERY),
@Parameter(name = "codeId", description = "二维码ID", required = true, in = ParameterIn.PATH)
})
@GetMapping("/qrcode/{codeId}/orders")
public PageResult getOrdersByCodeId(
@PathVariable("codeId") String codeId,
@RequestParam Map<String, Object> params) {
log.info("=== 根据二维码ID查询订单列表 ===");
log.info("codeId: {}, params: {}", codeId, params);
try {
// 直接用QueryWrapper查询,不走findList(避免tourismIds过滤)
Integer pageNum = Integer.parseInt(params.getOrDefault("page", "1").toString());
Integer pageSize = Integer.parseInt(params.getOrDefault("limit", "10").toString());
Page<Order> page = new Page<>(pageNum, pageSize);
QueryWrapper<Order> wrapper = new QueryWrapper<>();
wrapper.eq("code_id", codeId);
wrapper.eq("is_del", 0);
wrapper.eq("order_status", 3);
// 时间过滤 - 时间戳转Date
Object payTimeStartObj = params.get("payTimeStart");
Object payTimeEndObj = params.get("payTimeEnd");
log.info("时间参数: payTimeStart={}, payTimeEnd={}", payTimeStartObj, payTimeEndObj);
if (payTimeStartObj != null && !payTimeStartObj.toString().isEmpty()) {
long ts = Long.parseLong(payTimeStartObj.toString());
Date startDate = new Date(ts);
log.info("开始时间转换: timestamp={} -> date={}", ts, startDate);
wrapper.ge("pay_time", startDate);
}
if (payTimeEndObj != null && !payTimeEndObj.toString().isEmpty()) {
long ts = Long.parseLong(payTimeEndObj.toString());
Date endDate = new Date(ts);
log.info("结束时间转换: timestamp={} -> date={}", ts, endDate);
wrapper.le("pay_time", endDate);
}
wrapper.orderByDesc("create_time");
// 先查询不带时间条件的总数,用于调试
QueryWrapper<Order> debugWrapper = new QueryWrapper<>();
debugWrapper.eq("code_id", codeId);
debugWrapper.eq("is_del", 0);
debugWrapper.eq("order_status", 3);
long totalWithoutTime = orderService.count(debugWrapper);
log.info("不带时间条件的订单总数: {}", totalWithoutTime);
Page<Order> result = orderService.page(page, wrapper);
log.info("查询结果: 总数={}, 当前页数量={}", result.getTotal(), result.getRecords().size());
// 打印前几条订单的pay_time,用于调试
if (!result.getRecords().isEmpty()) {
for (int i = 0; i < Math.min(3, result.getRecords().size()); i++) {
Order o = result.getRecords().get(i);
log.info("订单[{}]: orderNo={}, pay_time={}", i, o.getOrderNo(), o.getPayTime());
}
}
return PageResult.<Order>builder()
.data(result.getRecords())
.resp_code(0)
.count(result.getTotal())
.build();
} catch (Exception e) {
log.error("根据二维码ID查询订单列表异常", e);
return new PageResult();
}
}
}
@@ -96,5 +96,12 @@ public interface IOrderService extends ISuperService<Order> {
Long getUnCompleteOrderCount(String deviceSn);
Order getNextQueueOrder(Long tourismId, Long currentOrderId);
/**
* 二维码订单统计查询
* @param params 查询参数(tenantId, includeChildren, qrcodeName, codeId, tourismId)
* @return 统计结果(tourismList: 景区列表,每个景区包含qrcodeList: 二维码统计列表)
*/
Map<String, Object> getQrcodeOrderStatistics(Map<String, Object> params);
}
@@ -28,10 +28,7 @@ import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@@ -425,4 +422,283 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
return baseMapper.selectOne(wrapper);
}
@Override
public Map<String, Object> getQrcodeOrderStatistics(Map<String, Object> params) {
String qrcodeName = MapUtils.getString(params, "qrcodeName");
String codeId = MapUtils.getString(params, "codeId");
Long tourismId = MapUtils.getLong(params, "tourismId");
// 分页参数
Integer page = MapUtils.getInteger(params, "page", 1);
Integer limit = MapUtils.getInteger(params, "limit", 10);
// 支付时间查询条件 - 处理可能是字符串的情况
Date payTimeStart = null;
Date payTimeEnd = null;
Object payTimeStartObj = params.get("payTimeStart");
Object payTimeEndObj = params.get("payTimeEnd");
try {
if (payTimeStartObj instanceof Date) {
payTimeStart = (Date) payTimeStartObj;
} else if (payTimeStartObj instanceof Long) {
payTimeStart = new Date((Long) payTimeStartObj);
} else if (payTimeStartObj instanceof Integer) {
payTimeStart = new Date(((Integer) payTimeStartObj).longValue());
} else if (payTimeStartObj instanceof String) {
String timeStr = (String) payTimeStartObj;
// 尝试解析为时间戳
try {
long timestamp = Long.parseLong(timeStr);
payTimeStart = new Date(timestamp);
} catch (NumberFormatException e) {
// 如果不是时间戳,尝试按日期格式解析
payTimeStart = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(timeStr);
}
}
if (payTimeEndObj instanceof Date) {
payTimeEnd = (Date) payTimeEndObj;
} else if (payTimeEndObj instanceof Long) {
payTimeEnd = new Date((Long) payTimeEndObj);
} else if (payTimeEndObj instanceof Integer) {
payTimeEnd = new Date(((Integer) payTimeEndObj).longValue());
} else if (payTimeEndObj instanceof String) {
String timeStr = (String) payTimeEndObj;
// 尝试解析为时间戳
try {
long timestamp = Long.parseLong(timeStr);
payTimeEnd = new Date(timestamp);
} catch (NumberFormatException e) {
// 如果不是时间戳,尝试按日期格式解析
payTimeEnd = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(timeStr);
}
}
} catch (Exception e) {
log.error("解析支付时间失败", e);
}
// 如果没有传支付时间,默认查询当天
if (payTimeStart == null) {
payTimeStart = DateUtils.getStartOfDay(new Date());
}
if (payTimeEnd == null) {
payTimeEnd = DateUtils.getEndOfDay(new Date());
}
// 1. 获取租户ID(参考景区管理的查询逻辑)
String anchor = MapUtils.getString(params, "tenantId");
try {
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
}
}
} catch (Exception ignored) {
log.error("获取当前登录用户租户失败");
}
// 2. 获取当前租户及所有子租户ID列表
List<String> tenantIds = userCenterService.getSonTenantIds(anchor);
// 3. 统计总数(不受时间和其他筛选条件影响)
Date startOfToday = DateUtils.getStartOfDay(new Date());
Date endOfToday = DateUtils.getEndOfDay(new Date());
// 3.1 统计景区总数(不受tourismId等筛选条件影响)
QueryWrapper<Tourism> totalTourismWrapper = new QueryWrapper<>();
if (tenantIds != null && !tenantIds.isEmpty()) {
totalTourismWrapper.in("tenant_id", tenantIds);
}
totalTourismWrapper.eq("is_del", 0);
long totalTourismCount = tourismMapper.selectCount(totalTourismWrapper);
// 3.2 查询该租户下所有景区ID
List<Long> allTourismIds = tourismMapper.selectList(totalTourismWrapper)
.stream().map(Tourism::getId).collect(java.util.stream.Collectors.toList());
// 3.3 统计二维码总数(不受qrcodeName、codeId筛选条件影响)
int totalQrcodeCount = 0;
if (!allTourismIds.isEmpty()) {
QueryWrapper<QrCode> totalQrcodeWrapper = new QueryWrapper<>();
totalQrcodeWrapper.in("tourism_id", allTourismIds);
totalQrcodeWrapper.eq("is_del", 0);
totalQrcodeCount = qrCodeMapper.selectCount(totalQrcodeWrapper).intValue();
}
// 3.4 统计订单总数(不受时间限制,只统计完成状态的订单)
long totalOrderCount = 0;
long todayOrderCount = 0;
if (!allTourismIds.isEmpty()) {
// 查询该租户下所有二维码的codeId
QueryWrapper<QrCode> allQrcodeWrapper = new QueryWrapper<>();
allQrcodeWrapper.in("tourism_id", allTourismIds);
allQrcodeWrapper.eq("is_del", 0);
List<String> allCodeIds = qrCodeMapper.selectList(allQrcodeWrapper)
.stream().map(QrCode::getCodeId).collect(java.util.stream.Collectors.toList());
log.info("二维码codeId列表: {}", allCodeIds);
if (!allCodeIds.isEmpty()) {
// 统计所有完成订单数(状态3,不受时间限制)
QueryWrapper<Order> totalOrderWrapper = new QueryWrapper<>();
totalOrderWrapper.in("code_id", allCodeIds);
totalOrderWrapper.eq("is_del", 0);
totalOrderWrapper.eq("order_status", 3);
totalOrderCount = baseMapper.selectCount(totalOrderWrapper);
// 统计今日完成订单数(状态3,按pay_time统计)
QueryWrapper<Order> todayOrderWrapper = new QueryWrapper<>();
todayOrderWrapper.in("code_id", allCodeIds);
todayOrderWrapper.eq("is_del", 0);
todayOrderWrapper.eq("order_status", 3);
todayOrderWrapper.between("pay_time", startOfToday, endOfToday);
todayOrderCount = baseMapper.selectCount(todayOrderWrapper);
} else {
log.warn("二维码codeId列表为空,无法统计订单");
}
} else {
log.warn("景区ID列表为空,无法统计二维码和订单");
}
// 4. 如果有二维码筛选条件,先找到匹配的二维码所属的景区ID
Set<Long> filteredTourismIds = null;
if ((codeId != null && !codeId.isEmpty()) || (qrcodeName != null && !qrcodeName.isEmpty())) {
QueryWrapper<QrCode> filterQrCodeWrapper = new QueryWrapper<>();
filterQrCodeWrapper.in("tourism_id", allTourismIds);
filterQrCodeWrapper.eq("is_del", 0);
if (qrcodeName != null && !qrcodeName.isEmpty()) {
filterQrCodeWrapper.like("name", qrcodeName);
}
if (codeId != null && !codeId.isEmpty()) {
filterQrCodeWrapper.like("code_id", codeId);
}
List<QrCode> filteredQrCodes = qrCodeMapper.selectList(filterQrCodeWrapper);
filteredTourismIds = filteredQrCodes.stream()
.map(QrCode::getTourismId)
.collect(java.util.stream.Collectors.toSet());
}
// 5. 根据租户ID列表查询景区列表(带分页,用于展示)
Page<Tourism> tourismPage = new Page<>(page, limit);
QueryWrapper<Tourism> tourismWrapper = new QueryWrapper<>();
if (tenantIds != null && !tenantIds.isEmpty()) {
tourismWrapper.in("tenant_id", tenantIds);
}
if (tourismId != null) {
tourismWrapper.eq("id", tourismId);
}
// 如果有二维码筛选条件,只查这些景区
if (filteredTourismIds != null) {
if (filteredTourismIds.isEmpty()) {
// 没有匹配的二维码,直接返回空结果
Map<String, Object> result = new java.util.HashMap<>();
result.put("tourismList", new java.util.ArrayList<>());
result.put("totalTourismCount", totalTourismCount);
result.put("totalQrcodeCount", totalQrcodeCount);
result.put("totalOrderCount", totalOrderCount);
result.put("todayOrderCount", todayOrderCount);
result.put("payTimeStart", payTimeStart);
result.put("payTimeEnd", payTimeEnd);
result.put("page", page);
result.put("limit", limit);
result.put("hasMore", false);
return result;
}
tourismWrapper.in("id", filteredTourismIds);
}
tourismWrapper.eq("is_del", 0);
// 景区倒序排列
tourismWrapper.orderByDesc("id");
tourismPage = tourismMapper.selectPage(tourismPage, tourismWrapper);
List<Tourism> tourismList = tourismPage.getRecords();
// 6. 遍历景区,查询二维码和订单统计(用于展示详细列表)
List<Map<String, Object>> tourismDataList = new java.util.ArrayList<>();
for (Tourism tourism : tourismList) {
// 查询该景区的二维码列表
QueryWrapper<QrCode> qrCodeWrapper = new QueryWrapper<>();
qrCodeWrapper.eq("tourism_id", tourism.getId());
qrCodeWrapper.eq("is_del", 0);
// 根据条件筛选二维码
if (qrcodeName != null && !qrcodeName.isEmpty()) {
qrCodeWrapper.like("name", qrcodeName);
}
if (codeId != null && !codeId.isEmpty()) {
qrCodeWrapper.like("code_id", codeId);
}
List<QrCode> qrCodeList = qrCodeMapper.selectList(qrCodeWrapper);
if (qrCodeList.isEmpty()) {
continue; // 如果该景区没有符合条件的二维码,跳过
}
List<Map<String, Object>> qrcodeDataList = new java.util.ArrayList<>();
long tourismOrderCount = 0;
for (QrCode qrCode : qrCodeList) {
// 统计该二维码的订单数量(状态为3,pay_time在时间范围内)
QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
orderWrapper.eq("code_id", qrCode.getCodeId());
orderWrapper.eq("is_del", 0);
orderWrapper.eq("order_status", 3);
orderWrapper.between("pay_time", payTimeStart, payTimeEnd);
Long orderCount = baseMapper.selectCount(orderWrapper);
// 统计该二维码今日订单数量(状态为3)
QueryWrapper<Order> todayOrderWrapper = new QueryWrapper<>();
todayOrderWrapper.eq("code_id", qrCode.getCodeId());
todayOrderWrapper.eq("is_del", 0);
todayOrderWrapper.eq("order_status", 3);
todayOrderWrapper.between("pay_time", startOfToday, endOfToday);
Long todayCount = baseMapper.selectCount(todayOrderWrapper);
Map<String, Object> qrcodeData = new java.util.HashMap<>();
qrcodeData.put("id", qrCode.getId());
qrcodeData.put("qrcodeId", qrCode.getCodeId());
qrcodeData.put("qrcodeName", qrCode.getName());
qrcodeData.put("qrcodeCode", qrCode.getCodeId());
qrcodeData.put("orderCount", orderCount);
qrcodeData.put("todayOrderCount", todayCount);
qrcodeData.put("viewUrl", fileCenterService.getViewUrlByPath(qrCode.getFilePath()));
qrcodeData.put("status", qrCode.getStatus());
qrcodeData.put("price", qrCode.getPrice());
qrcodeData.put("deviceSn", qrCode.getDeviceSn());
qrcodeDataList.add(qrcodeData);
tourismOrderCount += orderCount;
}
Map<String, Object> tourismData = new java.util.HashMap<>();
tourismData.put("tourismId", tourism.getId());
tourismData.put("tourismName", tourism.getTourismName());
tourismData.put("tourismAddress", tourism.getTourismAddress());
tourismData.put("orderCount", tourismOrderCount);
tourismData.put("qrcodeCount", qrCodeList.size());
tourismData.put("qrcodeList", qrcodeDataList);
tourismDataList.add(tourismData);
}
// 6. 组装返回结果
Map<String, Object> result = new java.util.HashMap<>();
result.put("tourismList", tourismDataList);
result.put("totalTourismCount", totalTourismCount);
result.put("totalQrcodeCount", totalQrcodeCount);
result.put("totalOrderCount", totalOrderCount);
result.put("todayOrderCount", todayOrderCount);
result.put("payTimeStart", payTimeStart);
result.put("payTimeEnd", payTimeEnd);
result.put("page", page);
result.put("limit", limit);
result.put("hasMore", tourismPage.getCurrent() < tourismPage.getPages()); // 是否还有更多数据
return result;
}
}
@@ -38,12 +38,12 @@
AND o.mobile LIKE CONCAT('%', #{p.mobile}, '%')
</if>
<!-- 时间范围(与仪表盘统计口径一致) -->
<!-- 时间范围(统计和列表统一用pay_time) -->
<if test="p.startTime != null and p.startTime != ''">
AND o.create_time &gt;= #{p.startTime}
AND o.pay_time &gt;= #{p.startTime}
</if>
<if test="p.endTime != null and p.endTime != ''">
AND o.create_time &lt;= #{p.endTime}
AND o.pay_time &lt;= #{p.endTime}
</if>
<!-- 景区集合过滤(由租户+子孙→景区ID集合的去重结果提供) -->
+2
View File
@@ -34,6 +34,8 @@ export default [
{ path: '/orders/coupon.html', component: '@/pages/orders/Coupon' },
// 导游管理模块(包含导游列表、佣金明细、提现审核)
{ path: '/orders/guide.html', component: '@/pages/orders/Guide' },
// 二维码订单管理
{ path: '/orders/qrcodeOrder.html', component: '@/pages/orders/QrcodeOrder' },
],
},
{
@@ -0,0 +1,166 @@
import React, { useRef } from 'react';
import { Drawer, Tag } from 'antd';
import { ProTable, type ActionType } from '@ant-design/pro-components';
import { ordersApi, type OrderItem } from '@/services/orders';
interface QrcodeData {
id: number;
qrcodeId: string;
qrcodeName: string;
qrcodeCode: string;
orderCount: number;
todayOrderCount: number;
viewUrl: string;
status: number;
price: string;
deviceSn: string;
}
interface OrderListDrawerProps {
open: boolean;
onClose: () => void;
qrcode: QrcodeData | null;
queryParams?: Record<string, any>;
}
const OrderListDrawer: React.FC<OrderListDrawerProps> = ({ open, onClose, qrcode, queryParams }) => {
const actionRef = useRef<ActionType>();
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48, fixed: 'left' },
{
title: '订单号',
dataIndex: 'orderNo',
width: 180,
fixed: 'left',
ellipsis: true,
},
{
title: '用户手机',
dataIndex: 'userPhone',
width: 120,
render: (phone: string) => phone || '-',
},
{
title: '金额',
dataIndex: 'orderAmount',
width: 100,
render: (amount: string | number) => {
if (!amount && amount !== 0) return '-';
const amountNum = typeof amount === 'string' ? parseFloat(amount) : amount;
if (Number.isNaN(amountNum)) return '-';
return `¥${(amountNum / 100).toFixed(2)}`;
},
},
{
title: '支付方式',
dataIndex: 'payType',
width: 100,
render: (type: number) => {
const typeMap: Record<number, { text: string; color: string }> = {
1: { text: '微信支付', color: 'green' },
2: { text: '优惠券', color: 'blue' },
3: { text: '第三方', color: 'orange' },
};
const info = typeMap[type] || { text: '未知', color: 'default' };
return <Tag color={info.color}>{info.text}</Tag>;
},
},
{
title: '订单状态',
dataIndex: 'orderStatus',
width: 120,
render: (status: number) => {
const statusMap: Record<number, { text: string; color: string }> = {
0: { text: '未支付', color: 'default' },
1: { text: '已支付', color: 'blue' },
2: { text: '已取消', color: 'red' },
3: { text: '任务完成', color: 'success' },
4: { text: '执行中', color: 'processing' },
5: { text: '素材上传中', color: 'cyan' },
6: { text: '素材上传完成', color: 'success' },
7: { text: '退款中', color: 'orange' },
8: { text: '已退款', color: 'orange' },
9: { text: '退款失败', color: 'red' },
10: { text: '部分退款', color: 'orange' },
};
const info = statusMap[status] || { text: '未知', color: 'default' };
return <Tag color={info.color}>{info.text}</Tag>;
},
},
{
title: '支付时间',
dataIndex: 'payTime',
width: 160,
valueType: 'dateTime',
render: (time: string) => time || '-',
},
{
title: '创建时间',
dataIndex: 'createTime',
width: 160,
valueType: 'dateTime',
},
];
return (
<Drawer
title={`订单列表 - ${qrcode?.qrcodeName || '未命名'}`}
placement="right"
width={1200}
open={open}
onClose={onClose}
destroyOnClose
className="order-list-drawer"
>
{qrcode && (
<>
<div className="drawer-summary">
<div className="summary-item">
<span className="label">二维码名称:</span>
<span className="value">{qrcode.qrcodeName || '未命名'}</span>
</div>
<div className="summary-item">
<span className="label">二维码Code:</span>
<span className="value" style={{ fontSize: 14, fontFamily: 'Courier New' }}>
{qrcode.qrcodeCode}
</span>
</div>
<div className="summary-item">
<span className="label">订单总数:</span>
<span className="value">{qrcode.orderCount}</span>
</div>
<div className="summary-item">
<span className="label">今日订单:</span>
<span className="value" style={{ color: '#52c41a' }}>
{qrcode.todayOrderCount}
</span>
</div>
</div>
<ProTable<OrderItem>
rowKey="id"
actionRef={actionRef}
request={(p) => ordersApi.ordersByCodeId({
...(p as any),
codeId: qrcode.qrcodeId,
payTimeStart: queryParams?.payTimeStart,
payTimeEnd: queryParams?.payTimeEnd,
})}
columns={columns}
search={false}
pagination={{
showSizeChanger: true,
showQuickJumper: true,
defaultPageSize: 10,
}}
toolBarRender={false}
scroll={{ x: 1200 }}
/>
</>
)}
</Drawer>
);
};
export default OrderListDrawer;
@@ -0,0 +1,110 @@
import React from 'react';
import { Card, Row, Col, Tag } from 'antd';
import { ShoppingOutlined, QrcodeOutlined } from '@ant-design/icons';
interface QrcodeData {
id: number;
qrcodeId: string;
qrcodeName: string;
qrcodeCode: string;
orderCount: number;
todayOrderCount: number;
viewUrl: string;
status: number;
price: string;
deviceSn: string;
}
interface TourismData {
tourismId: number;
tourismName: string;
tourismAddress: string;
orderCount: number;
qrcodeCount: number;
qrcodeList: QrcodeData[];
}
interface TourismSectionProps {
tourism: TourismData;
onQrcodeClick: (qrcode: QrcodeData) => void;
}
const TourismSection: React.FC<TourismSectionProps> = ({ tourism, onQrcodeClick }) => {
return (
<div className="tourism-section">
<div className="tourism-header">
<h3 className="tourism-title">
{tourism.tourismName}
{tourism.tourismAddress && (
<span style={{ fontSize: 14, fontWeight: 400, marginLeft: 12, opacity: 0.9 }}>
{tourism.tourismAddress}
</span>
)}
</h3>
<div className="tourism-stats">
<div className="stat-item">
<QrcodeOutlined />
<span className="stat-label">二维码:</span>
<span className="stat-value">{tourism.qrcodeCount}</span>
</div>
<div className="stat-item">
<ShoppingOutlined />
<span className="stat-label">订单总数:</span>
<span className="stat-value">{tourism.orderCount}</span>
</div>
</div>
</div>
<div className="qrcode-grid">
<Row gutter={[16, 16]}>
{tourism.qrcodeList.map((qrcode) => (
<Col xs={24} sm={12} md={8} lg={6} xl={4} key={qrcode.id}>
<Card
className="qrcode-card"
onClick={() => onQrcodeClick(qrcode)}
hoverable
bodyStyle={{ padding: 0 }}
>
<div className="qrcode-image-wrapper">
<img
src={qrcode.viewUrl}
alt={qrcode.qrcodeName}
className="qrcode-image"
/>
<div className={`status-badge ${qrcode.status === 0 ? 'status-active' : 'status-inactive'}`}>
{qrcode.status === 0 ? '启用' : '禁用'}
</div>
</div>
<div className="qrcode-info">
<div className="qrcode-name" title={qrcode.qrcodeName}>
{qrcode.qrcodeName || '未命名'}
</div>
<div className="qrcode-stats">
<div className="stat-item">
<div className="stat-value">{qrcode.orderCount}</div>
<div className="stat-label">总订单</div>
</div>
<div className="stat-item">
<div className="stat-value" style={{ color: '#52c41a' }}>
{qrcode.todayOrderCount}
</div>
<div className="stat-label">今日</div>
</div>
</div>
<div className="qrcode-code" title={qrcode.qrcodeCode}>
Code: {qrcode.qrcodeCode}
</div>
</div>
</Card>
</Col>
))}
</Row>
</div>
</div>
);
};
export default TourismSection;
@@ -0,0 +1,247 @@
.qrcode-order-page {
.stat-card {
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
transition: all 0.3s ease;
border: none;
background: linear-gradient(135deg, #ffffff 0%, #f5f5f5 100%);
&:hover {
transform: translateY(-4px);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}
&.stat-card-blue {
background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
}
&.stat-card-purple {
background: linear-gradient(135deg, #f9f0ff 0%, #efdbff 100%);
}
&.stat-card-green {
background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
}
&.stat-card-orange {
background: linear-gradient(135deg, #fff7e6 0%, #ffd591 100%);
}
.ant-statistic-title {
font-size: 14px;
font-weight: 500;
color: rgba(0, 0, 0, 0.65);
}
.ant-statistic-content {
font-size: 28px;
font-weight: 600;
font-family: 'Roboto Mono', monospace;
}
}
}
.tourism-section {
margin-bottom: 24px;
.tourism-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 12px 12px 0 0;
color: white;
.tourism-title {
font-size: 18px;
font-weight: 600;
margin: 0;
}
.tourism-stats {
display: flex;
gap: 24px;
font-size: 14px;
.stat-item {
display: flex;
align-items: center;
gap: 6px;
.stat-label {
opacity: 0.9;
}
.stat-value {
font-weight: 600;
font-size: 16px;
}
}
}
}
.qrcode-grid {
padding: 24px;
background: white;
border-radius: 0 0 12px 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
}
.qrcode-card {
border-radius: 12px;
overflow: hidden;
transition: all 0.3s ease;
cursor: pointer;
border: 2px solid transparent;
background: white;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
&:hover {
transform: translateY(-8px) scale(1.02);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
border-color: #1890ff;
}
.qrcode-image-wrapper {
position: relative;
padding: 16px;
background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
display: flex;
justify-content: center;
align-items: center;
height: 180px;
.qrcode-image {
width: 140px;
height: 140px;
object-fit: contain;
border-radius: 8px;
background: white;
padding: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.status-badge {
position: absolute;
top: 12px;
right: 12px;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 500;
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(4px);
&.status-active {
color: #52c41a;
border: 1px solid #52c41a;
}
&.status-inactive {
color: #ff4d4f;
border: 1px solid #ff4d4f;
}
}
}
.qrcode-info {
padding: 16px;
.qrcode-name {
font-size: 16px;
font-weight: 600;
color: #262626;
margin-bottom: 12px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.qrcode-stats {
display: flex;
justify-content: space-between;
margin-bottom: 12px;
.stat-item {
text-align: center;
.stat-value {
font-size: 20px;
font-weight: 600;
color: #1890ff;
font-family: 'Roboto Mono', monospace;
}
.stat-label {
font-size: 12px;
color: #8c8c8c;
margin-top: 4px;
}
}
}
.qrcode-code {
font-size: 12px;
color: #8c8c8c;
padding: 8px;
background: #f5f5f5;
border-radius: 6px;
font-family: 'Courier New', monospace;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
}
.order-list-drawer {
.ant-drawer-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-bottom: none;
.ant-drawer-title {
color: white;
font-size: 18px;
font-weight: 600;
}
.ant-drawer-close {
color: white;
&:hover {
color: rgba(255, 255, 255, 0.8);
}
}
}
.drawer-summary {
padding: 16px;
background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
border-radius: 8px;
margin-bottom: 16px;
.summary-item {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
&:last-child {
margin-bottom: 0;
}
.label {
color: #595959;
font-size: 14px;
}
.value {
font-weight: 600;
font-size: 16px;
color: #1890ff;
font-family: 'Roboto Mono', monospace;
}
}
}
}
@@ -0,0 +1,285 @@
import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, Empty, Spin, Drawer, message } from 'antd';
import { QrcodeOutlined, ShopOutlined, ShoppingOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { ordersApi } from '@/services/orders';
import { tenantApi } from '@/services/tenant';
import { SearchBarPlus, GradientButton } from '@/components/ui';
import { ProFormText, ProFormDateRangePicker } from '@ant-design/pro-components';
import TourismSection from './components/TourismSection';
import OrderListDrawer from './components/OrderListDrawer';
import './index.less';
import moment from 'moment';
interface QrcodeData {
id: number;
qrcodeId: string;
qrcodeName: string;
qrcodeCode: string;
orderCount: number;
todayOrderCount: number;
viewUrl: string;
status: number;
price: string;
deviceSn: string;
}
interface TourismData {
tourismId: number;
tourismName: string;
tourismAddress: string;
orderCount: number;
qrcodeCount: number;
qrcodeList: QrcodeData[];
}
interface StatisticsData {
tourismList: TourismData[];
totalTourismCount: number;
totalQrcodeCount: number;
totalOrderCount: number;
todayOrderCount: number;
}
const QrcodeOrderPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [statistics, setStatistics] = useState<StatisticsData | null>(null);
const [params, setParams] = useState<Record<string, any>>({});
const [drawerOpen, setDrawerOpen] = useState(false);
const [selectedQrcode, setSelectedQrcode] = useState<QrcodeData | null>(null);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(false);
// 首次进入时,默认按"当前租户 + 包含下级租户 + 当天支付时间"查询
useEffect(() => {
(async () => {
try {
let tenantId: string | undefined;
const cur: any = await tenantApi.getCurrentTenant();
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
if (!tenantId) {
const stats: any = await tenantApi.getScopeStats();
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
}
if (tenantId) {
// 默认查询当天
const initialParams = {
tenantId,
includeChildren: true,
payTimeStart: moment().startOf('day').valueOf(), // 传时间戳
payTimeEnd: moment().endOf('day').valueOf(), // 传时间戳
};
setParams(initialParams);
setPage(1);
fetchStatistics(initialParams, 1, false);
}
} catch {
// 忽略错误,保留手动查询能力
}
})();
}, []);
const fetchStatistics = async (queryParams: Record<string, any>, currentPage: number, isLoadMore: boolean) => {
if (isLoadMore) {
setLoadingMore(true);
} else {
setLoading(true);
}
try {
const res = await ordersApi.qrcodeOrderStatistics({ ...queryParams, page: currentPage, limit: 10 });
console.log('二维码订单统计返回数据:', res);
// 确保返回的数据结构正确
const safeRes = {
...res,
tourismList: res?.tourismList || [],
totalTourismCount: res?.totalTourismCount || 0,
totalQrcodeCount: res?.totalQrcodeCount || 0,
totalOrderCount: res?.totalOrderCount || 0,
todayOrderCount: res?.todayOrderCount || 0,
hasMore: res?.hasMore || false,
};
if (isLoadMore) {
// 加载更多:追加数据
setStatistics((prev) => {
if (!prev) return safeRes;
return {
...safeRes,
tourismList: [...(prev.tourismList || []), ...(safeRes.tourismList || [])],
};
});
} else {
// 首次查询或重新查询:替换数据
setStatistics(safeRes);
}
setHasMore(safeRes.hasMore);
setPage(currentPage);
} catch (error) {
console.error('二维码订单统计查询失败:', error);
message.error('查询失败');
// 出错时设置空数据
setStatistics({
tourismList: [],
totalTourismCount: 0,
totalQrcodeCount: 0,
totalOrderCount: 0,
todayOrderCount: 0,
});
} finally {
if (isLoadMore) {
setLoadingMore(false);
} else {
setLoading(false);
}
}
};
const handleQrcodeClick = (qrcode: QrcodeData) => {
setSelectedQrcode(qrcode);
setDrawerOpen(true);
};
const handleLoadMore = () => {
const nextPage = page + 1;
fetchStatistics(params, nextPage, true);
};
return (
<PageContainer
header={{ title: '二维码统计管理' }}
className="qrcode-order-page"
>
{/* 顶部筛选栏 */}
<SearchBarPlus
defaultCollapsed={false}
split
span={8}
hideReset
onTenantChanged={(tenantId, includeChildren) => {
const newParams = { ...(params || {}), tenantId, includeChildren };
setParams(newParams);
setPage(1);
fetchStatistics(newParams, 1, false);
}}
onFinish={async (values) => {
// 处理支付时间范围 - 保留用户选择的具体时间点
let processedValues = { ...values };
if (values.payTimeRange && values.payTimeRange.length === 2) {
processedValues.payTimeStart = moment(values.payTimeRange[0]).valueOf();
processedValues.payTimeEnd = moment(values.payTimeRange[1]).valueOf();
delete processedValues.payTimeRange;
}
const newParams = { ...(params || {}), ...processedValues };
setParams(newParams);
setPage(1);
fetchStatistics(newParams, 1, false);
}}
>
<ProFormDateRangePicker
name="payTimeRange"
label="支付时间"
placeholder={['开始时间', '结束时间']}
initialValue={[moment().startOf('day'), moment().endOf('day')]}
fieldProps={{
showTime: { format: 'HH:mm:ss' },
format: 'YYYY-MM-DD HH:mm:ss',
}}
/>
<ProFormText name="qrcodeName" label="二维码名称" placeholder="请输入二维码名称" />
<ProFormText name="codeId" label="二维码Code" placeholder="请输入二维码Code" />
</SearchBarPlus>
{/* 统计概览卡片 */}
{statistics && (
<Row gutter={16} style={{ marginBottom: 24 }}>
<Col xs={24} sm={12} md={6}>
<Card className="stat-card stat-card-blue">
<Statistic
title="景区总数"
value={statistics.totalTourismCount}
prefix={<ShopOutlined />}
valueStyle={{ color: '#1890ff' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card className="stat-card stat-card-purple">
<Statistic
title="二维码总数"
value={statistics.totalQrcodeCount}
prefix={<QrcodeOutlined />}
valueStyle={{ color: '#722ed1' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card className="stat-card stat-card-green">
<Statistic
title="订单总数"
value={statistics.totalOrderCount}
prefix={<ShoppingOutlined />}
valueStyle={{ color: '#52c41a' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card className="stat-card stat-card-orange">
<Statistic
title="今日订单"
value={statistics.todayOrderCount}
prefix={<ClockCircleOutlined />}
valueStyle={{ color: '#fa8c16' }}
/>
</Card>
</Col>
</Row>
)}
{/* 景区二维码卡片网格 */}
<Spin spinning={loading}>
{statistics && statistics.tourismList.length > 0 ? (
<>
{statistics.tourismList.map((tourism) => (
<TourismSection
key={tourism.tourismId}
tourism={tourism}
onQrcodeClick={handleQrcodeClick}
/>
))}
{/* 加载更多按钮 */}
{hasMore && (
<div style={{ textAlign: 'center', marginTop: 24, marginBottom: 24 }}>
<GradientButton
size="large"
onClick={handleLoadMore}
loading={loadingMore}
style={{ minWidth: 200 }}
>
{loadingMore ? '加载中...' : '加载更多'}
</GradientButton>
</div>
)}
</>
) : (
<Card>
<Empty description="暂无数据" />
</Card>
)}
</Spin>
{/* 订单列表抽屉 */}
<OrderListDrawer
open={drawerOpen}
onClose={() => setDrawerOpen(false)}
qrcode={selectedQrcode}
queryParams={params}
/>
</PageContainer>
);
};
export default QrcodeOrderPage;
@@ -456,4 +456,17 @@ export const ordersApi = {
throw error;
}
},
// 二维码订单统计查询
qrcodeOrderStatistics: async (params?: { tenantId?: string; includeChildren?: boolean; qrcodeName?: string; codeId?: string; tourismId?: number; page?: number; limit?: number; payTimeStart?: number; payTimeEnd?: number }) => {
const res = await request('/api-order/qrcode/order/statistics', { method: 'GET', params });
return (res as any).data || res;
},
// 根据二维码ID查询订单列表
ordersByCodeId: async (params: { current?: number; pageSize?: number; codeId: string; [k: string]: any }) => {
const { current, pageSize, codeId, ...rest } = params || {};
const res = await request(`/api-order/qrcode/${codeId}/orders`, { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count } as { data: OrderItem[]; total: number };
},
};
@@ -1,7 +1,7 @@
/**
* 边界预览面板组件
* 显示边界的统计信息
* @author Claude
* @author dzc
* @date 2026-01-06
*/
import React, { useMemo } from 'react';
@@ -48,11 +48,11 @@ function calculatePolygonArea(vertices: { longitude: number; latitude: number }[
function getBoundaryTypeInfo(type: BoundaryType): { label: string; color: string } {
switch (type) {
case 'navigable':
return { label: '可通行区域', color: 'green' };
case 'forbidden':
return { label: '禁止通行', color: 'red' };
case 'warning':
return { label: '警告区域', color: 'orange' };
return { label: '可航行区域', color: 'green' };
case 'obstacle':
return { label: '障碍物', color: 'orange' };
case 'restricted':
return { label: '禁行区', color: 'red' };
default:
return { label: '未知', color: 'default' };
}
@@ -127,7 +127,7 @@ const BoundaryPreview: React.FC<BoundaryPreviewProps> = ({
fontSize: 12,
color: '#faad14',
}}>
⚠️ 至少需要3个顶点才能形成边界
提示:至少需要3个顶点才能形成边界
</div>
)}
@@ -141,7 +141,7 @@ const BoundaryPreview: React.FC<BoundaryPreviewProps> = ({
fontSize: 12,
color: '#52c41a',
}}>
✓ 边界已形成,可以保存
边界已形成,可以保存
</div>
)}
</Card>
@@ -1,6 +1,6 @@
/**
* 边界编辑器工具栏组件
* @author Claude
* @author dzc
* @date 2026-01-06
*/
import React from 'react';
@@ -22,9 +22,11 @@ const BoundaryToolbar: React.FC<BoundaryToolbarProps> = ({
hasVertices,
hasUnsavedChanges,
isDrawing,
canUndo,
onModeChange,
onStartDraw,
onFinishDraw,
onUndo,
onClear,
onSave,
onCancel,
@@ -50,8 +52,9 @@ const BoundaryToolbar: React.FC<BoundaryToolbarProps> = ({
icon={<PlusOutlined />}
onClick={onStartDraw}
style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
background: 'linear-gradient(135deg, rgba(0, 240, 255, 0.95) 0%, rgba(0, 153, 255, 0.85) 100%)',
border: 'none',
color: '#001019',
}}
>
开始绘制
@@ -115,6 +118,19 @@ const BoundaryToolbar: React.FC<BoundaryToolbarProps> = ({
</Tooltip>
)}
{/* 撤销按钮 */}
{onUndo && (
<Tooltip title="撤销(Ctrl+Z)">
<Button
icon={<UndoOutlined />}
onClick={onUndo}
disabled={!canUndo}
>
撤销
</Button>
</Tooltip>
)}
{/* 分隔线 */}
{hasVertices && (
<div style={{
@@ -27,13 +27,13 @@ interface UseBoundaryDrawingReturn {
/** 结束绘制 */
finishDrawing: () => void;
/** 添加顶点 */
addVertex: (point: { longitude: number; latitude: number }) => void;
addVertex: (point: { longitude: number; latitude: number; height?: number }) => void;
/** 更新顶点 */
updateVertex: (index: number, point: { longitude: number; latitude: number }) => void;
updateVertex: (index: number, point: { longitude: number; latitude: number; height?: number }) => void;
/** 删除顶点 */
deleteVertex: (index: number) => void;
/** 移动顶点 */
moveVertex: (index: number, point: { longitude: number; latitude: number }) => void;
moveVertex: (index: number, point: { longitude: number; latitude: number; height?: number }) => void;
/** 选择顶点 */
selectVertex: (index: number | null) => void;
/** 清空所有顶点 */
@@ -143,6 +143,7 @@ export function useBoundaryDrawing(options: UseBoundaryDrawingOptions = {}): Use
const newVertex: BoundaryVertex = {
longitude: point.longitude,
latitude: point.latitude,
height: point.height,
};
updateVertices([...vertices, newVertex]);
}, [vertices, updateVertices]);
@@ -150,7 +151,7 @@ export function useBoundaryDrawing(options: UseBoundaryDrawingOptions = {}): Use
/**
* 更新顶点
*/
const updateVertex = useCallback((index: number, point: { longitude: number; latitude: number }) => {
const updateVertex = useCallback((index: number, point: { longitude: number; latitude: number; height?: number }) => {
if (index < 0 || index >= vertices.length) {
console.warn(`Invalid vertex index: ${index}`);
return;
@@ -159,6 +160,7 @@ export function useBoundaryDrawing(options: UseBoundaryDrawingOptions = {}): Use
newVertices[index] = {
longitude: point.longitude,
latitude: point.latitude,
height: point.height,
};
updateVertices(newVertices);
}, [vertices, updateVertices]);
@@ -13,8 +13,8 @@ interface UseCesiumBoundaryRendererOptions {
selectedIndex: number | null;
mode: EditorMode;
boundaryType: BoundaryType;
onVertexAdd: (point: { longitude: number; latitude: number }) => void;
onVertexMove: (index: number, point: { longitude: number; latitude: number }) => void;
onVertexAdd: (point: { longitude: number; latitude: number; height?: number }) => void;
onVertexMove: (index: number, point: { longitude: number; latitude: number; height?: number }) => void;
onVertexSelect: (index: number) => void;
}
@@ -23,11 +23,11 @@ interface UseCesiumBoundaryRendererOptions {
*/
function getBoundaryColor(type: BoundaryType, Cesium: any) {
switch (type) {
case 'navigable': // 可通行 - 绿色
case 'navigable': // 可航行 - 绿色
return Cesium.Color.fromCssColorString('#00ff00');
case 'forbidden': // 禁行 - 红色
case 'restricted': // 禁行 - 红色
return Cesium.Color.fromCssColorString('#ff0000');
case 'warning': // 警告 - 黄色
case 'obstacle': // 障碍物 - 黄色
return Cesium.Color.fromCssColorString('#ffff00');
default:
return Cesium.Color.fromCssColorString('#00ff00');
@@ -41,9 +41,9 @@ function getBoundaryAlpha(type: BoundaryType): number {
switch (type) {
case 'navigable':
return 0.2;
case 'forbidden':
case 'restricted':
return 0.3;
case 'warning':
case 'obstacle':
return 0.2;
default:
return 0.2;
@@ -82,6 +82,12 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
// 拖动状态
const draggingEntityRef = useRef<any>(null);
const rafIdRef = useRef<number | null>(null);
const previousSceneOptionsRef = useRef<{
depthTestAgainstTerrain?: boolean;
pickTranslucentDepth?: boolean;
requestRenderMode?: boolean;
maximumRenderTimeChange?: number;
} | null>(null);
/**
* 获取Cesium对象
@@ -90,6 +96,57 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
return (window as any).Cesium;
}, []);
/**
* 安全触发一次渲染(requestRenderMode=true 时,实体变化不一定会立刻刷新)
*/
const requestRender = useCallback(() => {
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed?.()) return;
try {
viewer.scene?.requestRender?.();
} catch {
// 忽略
}
}, [viewerRef]);
/**
* 从屏幕坐标拾取地理位置:优先 pickPosition(支持 3D Tiles/模型),失败再回退 globe.pick / pickEllipsoid
*/
const pickCartesianFromScreen = useCallback((screenPosition: any) => {
const viewer = viewerRef.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.() || !screenPosition) return null;
// 1) 优先 pickPosition(依赖深度缓冲)
try {
if (viewer.scene?.pickPositionSupported) {
const cartesian = viewer.scene.pickPosition(screenPosition);
if (Cesium.defined(cartesian)) return cartesian;
}
} catch {
// pickPosition 可能在少数环境抛错,继续回退
}
// 2) 回退:globe.pick(地形/椭球)
try {
const ray = viewer.camera.getPickRay(screenPosition);
const cartesian = viewer.scene?.globe?.pick?.(ray, viewer.scene);
if (Cesium.defined(cartesian)) return cartesian;
} catch {
// 忽略
}
// 3) 最后回退:pickEllipsoid(即便没加载地形也能拿到)
try {
const cartesian = viewer.camera.pickEllipsoid(screenPosition, viewer.scene.globe.ellipsoid);
if (Cesium.defined(cartesian)) return cartesian;
} catch {
// 忽略
}
return null;
}, [viewerRef, getCesium]);
/**
* 清理所有Entity
*/
@@ -105,7 +162,8 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
}
});
entityIdsRef.current.clear();
}, [viewerRef]);
requestRender();
}, [viewerRef, requestRender]);
/**
* 渲染边界多边形
@@ -116,6 +174,8 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (vertices.length < 3) return; // 至少3个顶点才能形成多边形
// 注意:模型表面高度通常不共面,如果用 perPositionHeight 直接拉三角面,容易出现“面被模型遮挡/割裂”的视觉问题。
// 这里改为使用 Classification(投影到 3D Tiles/地形),保证填充连续;顶点依然按 height 在模型表面显示。
const positions = vertices.map(v =>
Cesium.Cartesian3.fromDegrees(v.longitude, v.latitude, 0)
);
@@ -134,7 +194,7 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
outline: true,
outlineColor: baseColor,
outlineWidth: 3,
classificationType: Cesium.ClassificationType.BOTH,
classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
}
});
@@ -142,7 +202,9 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
} catch (e) {
console.error('添加边界多边形失败:', e);
}
}, [viewerRef, vertices, boundaryType, getCesium]);
requestRender();
}, [viewerRef, vertices, boundaryType, getCesium, requestRender]);
/**
* 渲染顶点Marker
@@ -160,10 +222,11 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
try {
const entity = viewer.entities.add({
id: entityId,
position: Cesium.Cartesian3.fromDegrees(v.longitude, v.latitude, 0),
position: Cesium.Cartesian3.fromDegrees(v.longitude, v.latitude, v.height ?? 0),
point: {
pixelSize: isSelected ? 14 : 10,
color: isSelected ? Cesium.Color.YELLOW : Cesium.Color.WHITE,
pixelSize: isSelected ? 16 : 12,
// 需求:点击的点用红色标记;选中点用黄色高亮
color: isSelected ? Cesium.Color.YELLOW : Cesium.Color.RED,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
@@ -191,7 +254,9 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
console.error('添加顶点entity失败:', e);
}
});
}, [viewerRef, vertices, selectedIndex, getCesium]);
requestRender();
}, [viewerRef, vertices, selectedIndex, getCesium, requestRender]);
/**
* 设置事件处理器
@@ -217,32 +282,30 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
return;
}
// 检查 screenSpaceEventController 是否存在
if (!viewer.scene?.screenSpaceEventController) {
// 尝试查找 screenSpaceEventController 的所有可能位置
const allSceneKeys = viewer.scene ? Object.keys(viewer.scene) : [];
const controllerKey = allSceneKeys.find(key => key.toLowerCase().includes('controller') || key.toLowerCase().includes('event'));
console.error('[BoundaryRenderer] screenSpaceEventController 不可用,调试信息:', {
hasScene: !!viewer.scene,
hasController: !!viewer.scene?.screenSpaceEventController,
allSceneKeys: allSceneKeys,
matchingKeys: allSceneKeys.filter(k => k.includes('screen') || k.includes('event') || k.includes('controller')),
// 尝试其他可能的路径
alternativePaths: {
'_screenSpaceEventController': !!viewer.scene?._screenSpaceEventController,
'screenSpaceEventHandler': !!viewer.scene?.screenSpaceEventHandler,
'_screenSpaceEventHandler': !!viewer.scene?._screenSpaceEventHandler,
}
});
return;
// 说明:Cesium 标准相机交互控制器是 screenSpaceCameraController
// 某些场景下该对象不可用,但不应阻断绘制(只影响“禁用旋转”等体验)
if (!viewer.scene?.screenSpaceCameraController) {
console.warn('[BoundaryRenderer] screenSpaceCameraController 不可用,将跳过相机交互锁定');
}
console.log('[BoundaryRenderer] ✓ 事件处理器初始化, mode=', mode);
// 启用深度测试,确保可以正确拾取3D模型上的点
try {
if (!previousSceneOptionsRef.current) {
previousSceneOptionsRef.current = {
depthTestAgainstTerrain: viewer.scene?.globe?.depthTestAgainstTerrain,
pickTranslucentDepth: viewer.scene?.pickTranslucentDepth,
requestRenderMode: viewer.scene?.requestRenderMode,
maximumRenderTimeChange: viewer.scene?.maximumRenderTimeChange,
};
}
viewer.scene.globe.depthTestAgainstTerrain = true;
viewer.scene.pickTranslucentDepth = true;
// 绘制/编辑时关闭 requestRenderMode,提升 pickPosition 稳定性(尤其是 3D Tiles 按需渲染场景)
viewer.scene.requestRenderMode = false;
viewer.scene.maximumRenderTimeChange = 0;
console.log('[BoundaryEditor] 已启用深度测试,支持在3D模型上绘制');
} catch (e) {
console.warn('[BoundaryEditor] 启用深度测试失败:', e);
@@ -264,7 +327,9 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
console.log('[BoundaryRenderer] ✓ 进入绘制模式,设置十字光标');
// 绘制模式:点击地图添加顶点
try {
viewer.scene.screenSpaceEventController.enableRotate = false;
if (viewer.scene?.screenSpaceCameraController) {
viewer.scene.screenSpaceCameraController.enableRotate = false;
}
} catch (e) {
console.warn('禁用旋转失败:', e);
}
@@ -274,17 +339,11 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
console.log('[BoundaryRenderer] 光标已设置为 crosshair, 当前值=', viewer.scene.canvas.style.cursor);
handler.setInputAction((movement: any) => {
// 优先使用 pickPosition 获取点击位置(支持3D模型和地形)
let cartesian = viewer.scene.pickPosition(movement.position);
// 如果 pickPosition 失败(例如点击天空),尝试使用 globe.pick
if (!cartesian) {
const ray = viewer.camera.getPickRay(movement.position);
cartesian = viewer.scene.globe.pick(ray, viewer.scene);
}
// 统一拾取:优先 pickPosition(支持模型/3D Tiles),失败回退 globe.pick / pickEllipsoid
const cartesian = pickCartesianFromScreen(movement.position);
if (cartesian) {
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const cartographic = Cesium.Cartographic.fromCartesian(cartesian as any);
const longitude = Cesium.Math.toDegrees(cartographic.longitude);
const latitude = Cesium.Math.toDegrees(cartographic.latitude);
const height = cartographic.height;
@@ -294,7 +353,8 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
latitude: latitude.toFixed(6),
height: height.toFixed(2) + 'm'
});
onVertexAdd({ longitude, latitude });
onVertexAdd({ longitude, latitude, height });
requestRender();
} else {
console.warn('[BoundaryEditor] ✗ 未能获取点击位置,请确保点击在地图或模型上');
}
@@ -308,7 +368,9 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
} else if (mode === 'edit') {
// 编辑模式:支持拖动和选择
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
if (viewer.scene?.screenSpaceCameraController) {
viewer.scene.screenSpaceCameraController.enableRotate = true;
}
} catch (e) {
console.warn('启用旋转失败:', e);
}
@@ -336,7 +398,9 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
draggingEntityRef.current = entity;
viewer.scene.canvas.style.setProperty('cursor', 'grabbing', 'important'); // 拖动光标
try {
viewer.scene.screenSpaceEventController.enableRotate = false;
if (viewer.scene?.screenSpaceCameraController) {
viewer.scene.screenSpaceCameraController.enableRotate = false;
}
} catch (e) {
console.warn('禁用旋转失败:', e);
}
@@ -356,23 +420,24 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
return;
}
const ray = viewer.camera.getPickRay(movement.endPosition);
const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
const cartesian = pickCartesianFromScreen(movement.endPosition);
if (cartesian) {
// 更新entity位置
entity.position = cartesian;
entity.position = cartesian as any;
// 通知外部更新vertex数据
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const cartographic = Cesium.Cartographic.fromCartesian(cartesian as any);
const vertexIndex = entity.properties?.vertexIndex?.getValue();
if (typeof vertexIndex === 'number') {
onVertexMove(vertexIndex, {
longitude: Cesium.Math.toDegrees(cartographic.longitude),
latitude: Cesium.Math.toDegrees(cartographic.latitude),
height: cartographic.height,
});
}
requestRender();
}
rafIdRef.current = null;
@@ -385,18 +450,23 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
if (draggingEntityRef.current) {
viewer.scene.canvas.style.setProperty('cursor', 'pointer', 'important'); // 恢复指针光标
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
if (viewer.scene?.screenSpaceCameraController) {
viewer.scene.screenSpaceCameraController.enableRotate = true;
}
} catch (e) {
console.warn('启用旋转失败:', e);
}
draggingEntityRef.current = null;
requestRender();
}
}, Cesium.ScreenSpaceEventType.LEFT_UP);
} else {
// view模式:恢复默认交互
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
if (viewer.scene?.screenSpaceCameraController) {
viewer.scene.screenSpaceCameraController.enableRotate = true;
}
} catch (e) {
console.warn('启用旋转失败:', e);
}
@@ -404,7 +474,7 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
// 恢复默认光标
viewer.scene.canvas.style.setProperty('cursor', 'default', 'important');
}
}, [viewerRef, mode, getCesium, onVertexAdd, onVertexMove, onVertexSelect]);
}, [viewerRef, mode, getCesium, onVertexAdd, onVertexMove, onVertexSelect, pickCartesianFromScreen, requestRender]);
/**
* 计算边界范围
@@ -514,9 +584,9 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
// 恢复地图旋转(增加完整检查)
const viewer = viewerRef.current;
if (viewer && !viewer.isDestroyed?.() && viewer.scene?.screenSpaceEventController) {
if (viewer && !viewer.isDestroyed?.() && viewer.scene?.screenSpaceCameraController) {
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
viewer.scene.screenSpaceCameraController.enableRotate = true;
// 恢复默认光标
if (viewer.scene.canvas) {
viewer.scene.canvas.style.setProperty('cursor', 'default', 'important');
@@ -526,8 +596,30 @@ export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOpti
console.warn('恢复地图旋转失败:', e);
}
}
// 恢复场景拾取相关选项
if (viewer && !viewer.isDestroyed?.() && previousSceneOptionsRef.current) {
try {
if (viewer.scene?.globe && typeof previousSceneOptionsRef.current.depthTestAgainstTerrain === 'boolean') {
viewer.scene.globe.depthTestAgainstTerrain = previousSceneOptionsRef.current.depthTestAgainstTerrain;
}
if (typeof previousSceneOptionsRef.current.pickTranslucentDepth === 'boolean') {
viewer.scene.pickTranslucentDepth = previousSceneOptionsRef.current.pickTranslucentDepth;
}
if (typeof previousSceneOptionsRef.current.requestRenderMode === 'boolean') {
viewer.scene.requestRenderMode = previousSceneOptionsRef.current.requestRenderMode;
}
if (typeof previousSceneOptionsRef.current.maximumRenderTimeChange === 'number') {
viewer.scene.maximumRenderTimeChange = previousSceneOptionsRef.current.maximumRenderTimeChange;
}
} catch {
// 忽略
}
}
previousSceneOptionsRef.current = null;
requestRender();
};
}, [cleanup, viewerRef]);
}, [cleanup, viewerRef, requestRender]);
return {
cleanup,
@@ -1,9 +1,6 @@
.editor {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
inset: 0;
pointer-events: none; // 允许点击穿透到地图
z-index: 900;
@@ -43,6 +40,12 @@
}
}
.boundaryInfo {
color: rgba(255, 255, 255, 0.72);
font-size: 12px;
line-height: 20px;
}
.vertexMarker {
width: 20px;
height: 20px;
@@ -1,9 +1,9 @@
/**
* 水域边界编辑器主组件
* @author Claude
* @author dzc
* @date 2026-01-06
*/
import React, { useState, useEffect, useCallback } from 'react';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Modal, Form, Input, Select, message, Spin } from 'antd';
import type { BoundaryEditorProps, BoundaryType, BoundaryVertex } from './types';
import { useBoundaryDrawing } from './hooks/useBoundaryDrawing';
@@ -12,15 +12,40 @@ import BoundaryToolbar from './BoundaryToolbar';
import BoundaryPreview from './BoundaryPreview';
import {
createWaterBoundary,
updateWaterBoundary,
getWaterBoundaryDetail,
} from '@/services/waterBoundary';
import styles from './index.less';
const { Option } = Select;
/**
* 计算多边形面积(使用Shoelace公式,简化局部投影,适用于小范围区域)
*/
function calculatePolygonArea(vertices: { longitude: number; latitude: number }[]): number {
if (vertices.length < 3) return 0;
const R = 6371000; // 地球半径(米)
const toRadians = (deg: number) => deg * Math.PI / 180;
const centerLat = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length;
const centerLon = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length;
const points = vertices.map(v => ({
x: R * toRadians(v.longitude - centerLon) * Math.cos(toRadians(centerLat)),
y: R * toRadians(v.latitude - centerLat),
}));
let area = 0;
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
area += points[i].x * points[j].y;
area -= points[j].x * points[i].y;
}
return Math.abs(area) / 2;
}
const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
scenicId,
deviceSn,
boundaryId,
initialVertices,
onSaveSuccess,
@@ -46,8 +71,25 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
clearVertices,
setVertices,
markSaved,
undo,
canUndo,
} = useBoundaryDrawing({ initialVertices });
const boundaryArea = useMemo(() => calculatePolygonArea(vertices), [vertices]);
const areaText = useMemo(() => {
if (!boundaryArea) return '-';
if (boundaryArea < 1000) return `${boundaryArea.toFixed(2)} m2`;
if (boundaryArea < 1000000) return `${(boundaryArea / 1000).toFixed(2)} 千m2`;
return `${(boundaryArea / 1000000).toFixed(2)} km2`;
}, [boundaryArea]);
const centerPointText = useMemo(() => {
if (vertices.length === 0) return '-';
const centerLon = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length;
const centerLat = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length;
return `${centerLon.toFixed(6)}, ${centerLat.toFixed(6)}`;
}, [vertices]);
// Cesium边界渲染Hook
useCesiumBoundaryRenderer({
viewerRef,
@@ -71,19 +113,18 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
setLoading(true);
try {
const response = await getWaterBoundaryDetail(id);
if (response.resp_code === 0 && response.datas) {
const boundary = response.datas;
const boundary = (response as any)?.data ?? (response as any)?.datas;
if (response.resp_code === 0 && boundary) {
// 设置表单值
form.setFieldsValue({
boundaryName: boundary.boundaryName,
boundaryType: boundary.boundaryType,
remark: boundary.remark,
});
setBoundaryType(boundary.boundaryType);
setBoundaryType(boundary.boundaryType as BoundaryType);
// 解析GeoJSON并设置顶点
try {
const geoJson = JSON.parse(boundary.geoJson);
const geoJson = JSON.parse(boundary.polygonData);
if (geoJson.type === 'Polygon' && geoJson.coordinates && geoJson.coordinates[0]) {
const coords = geoJson.coordinates[0];
const verts: BoundaryVertex[] = coords.map((coord: number[]) => ({
@@ -109,7 +150,7 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
};
// 处理地图点击
function handleMapClick(event: { longitude: number; latitude: number }) {
function handleMapClick(event: { longitude: number; latitude: number; height?: number }) {
if (editorState.mode === 'draw') {
addVertex(event);
}
@@ -151,68 +192,62 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
[vertices[0].longitude, vertices[0].latitude], // 闭合多边形
];
const geoJson = JSON.stringify({
const polygonData = JSON.stringify({
type: 'Polygon',
coordinates: [coordinates],
});
// 计算中心点
const centerLongitude =
vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length;
const centerLatitude =
vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length;
// TODO: 计算面积(可选)
const area = 0;
if (boundaryId) {
// 更新边界
const updateData = {
boundaryName: values.boundaryName,
boundaryType: values.boundaryType,
geoJson,
centerLongitude,
centerLatitude,
area,
remark: values.remark,
};
const response = await updateWaterBoundary(boundaryId, updateData);
if (response.resp_code === 0) {
message.success('边界更新成功');
markSaved();
setSaveModalVisible(false);
onSaveSuccess?.(boundaryId);
} else {
message.error(response.resp_msg || '更新失败');
}
message.error('当前后端暂不支持更新边界,请删除后重新创建');
return;
} else {
// 创建边界
const sn = String(deviceSn || '').trim();
if (!sn) {
message.error('设备SN无效,请先选择设备');
return;
}
// 计算中心点(经纬度平均值)
const centerLongitude = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length;
const centerLatitude = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length;
const centerPoint = `${centerLongitude.toFixed(6)},${centerLatitude.toFixed(6)}`;
const createData = {
scenicId,
deviceSn: sn,
boundaryName: values.boundaryName,
boundaryType: values.boundaryType,
geoJson,
centerLongitude,
centerLatitude,
area,
remark: values.remark,
polygonData,
centerPoint,
sourceType: 'manual' as const,
showInModel: 1 as const,
};
const response = await createWaterBoundary(createData);
if (response.resp_code === 0 && response.datas) {
message.success('边界创建成功');
const createdId = (response as any)?.data ?? (response as any)?.datas;
if (response.resp_code === 0 && createdId) {
message.success(response.resp_msg || '边界创建成功');
markSaved();
setSaveModalVisible(false);
onSaveSuccess?.(response.datas);
setMode('view');
selectVertex(null);
onSaveSuccess?.(createdId);
} else {
message.error(response.resp_msg || '创建失败');
}
}
} catch (error) {
console.error('保存边界失败:', error);
const anyErr = error as any;
const serverMsg =
anyErr?.data?.resp_msg ||
anyErr?.data?.message ||
anyErr?.response?.data?.resp_msg ||
anyErr?.response?.data?.message;
message.error(serverMsg || '保存失败:后端参数校验未通过(请检查控制台 Network 响应内容)');
} finally {
setLoading(false);
}
}, [form, vertices, boundaryId, scenicId, markSaved, onSaveSuccess]);
}, [form, vertices, boundaryId, deviceSn, markSaved, onSaveSuccess, setMode, selectVertex]);
// 处理取消
const handleCancel = useCallback(() => {
@@ -244,6 +279,26 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
};
}, [isDrawing, finishDrawing]);
// 快捷键:Ctrl+Z 撤销(输入框内不拦截)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null;
const tagName = target?.tagName?.toLowerCase?.();
const isTypingTarget = tagName === 'input' || tagName === 'textarea' || !!target?.isContentEditable;
if (isTypingTarget) return;
const key = e.key?.toLowerCase?.();
const isUndo = (e.ctrlKey || e.metaKey) && key === 'z';
if (!isUndo) return;
if (!canUndo) return;
e.preventDefault();
undo();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [canUndo, undo]);
return (
<div className={styles.editor}>
{/* 工具栏 - 独立渲染,不受Spin影响 */}
@@ -252,9 +307,11 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
hasVertices={vertices.length > 0}
hasUnsavedChanges={editorState.hasUnsavedChanges}
isDrawing={isDrawing}
canUndo={canUndo}
onModeChange={handleModeChange}
onStartDraw={startDrawing}
onFinishDraw={finishDrawing}
onUndo={undo}
onClear={clearVertices}
onSave={handleOpenSaveModal}
onCancel={handleCancel}
@@ -302,19 +359,17 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
placeholder="请选择边界类型"
onChange={(value) => setBoundaryType(value as BoundaryType)}
>
<Option value="navigable">可通行区域</Option>
<Option value="forbidden">禁止通行</Option>
<Option value="warning">警告区域</Option>
<Option value="navigable">可航行区域</Option>
<Option value="obstacle">障碍物</Option>
<Option value="restricted">禁行区</Option>
</Select>
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} placeholder="可选备注信息" />
</Form.Item>
<Form.Item label="边界信息" style={{ marginBottom: 0 }}>
<div style={{ color: 'rgba(0, 0, 0, 0.45)', fontSize: 12 }}>
顶点数量: {vertices.length}
<div className={styles.boundaryInfo}>
<div>顶点数量:{vertices.length}</div>
<div>中心点:{centerPointText}</div>
<div>估算面积:{areaText}</div>
</div>
</Form.Item>
</Form>
@@ -323,7 +378,7 @@ const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
{/* 全局Loading遮罩 - 仅在加载时显示 */}
{loading && (
<div style={{
position: 'fixed',
position: 'absolute',
top: 0,
left: 0,
right: 0,
@@ -1,13 +1,13 @@
/**
* 水域边界编辑器类型定义
* @author Claude
* @author dzc
* @date 2026-01-06
*/
/**
* 边界类型
*/
export type BoundaryType = 'navigable' | 'forbidden' | 'warning';
export type BoundaryType = 'navigable' | 'obstacle' | 'restricted';
/**
* 边界顶点
@@ -15,6 +15,8 @@ export type BoundaryType = 'navigable' | 'forbidden' | 'warning';
export interface BoundaryVertex {
longitude: number;
latitude: number;
/** 点击 3D 模型/地形时的高度(米),用于在模型表面正确显示顶点) */
height?: number;
}
/**
@@ -35,14 +37,19 @@ export interface EditorState {
* 边界创建DTO(对应后端)
*/
export interface WaterBoundaryCreateDTO {
scenicId: number;
/** 绑定设备SN(用于与设备关联) */
deviceSn: string;
/** 所属景区ID(可选,当前前端不依赖) */
scenicId?: number;
boundaryName: string;
boundaryType: BoundaryType;
geoJson: string;
centerLongitude?: number;
centerLatitude?: number;
polygonData: string;
centerPoint?: string;
area?: number;
remark?: string;
sourceType?: 'manual' | 'model' | 'import';
modelId?: string;
/** 是否在模型中显示标绘:0-否,1-是(可选,默认1) */
showInModel?: 0 | 1;
}
/**
@@ -51,37 +58,40 @@ export interface WaterBoundaryCreateDTO {
export interface WaterBoundaryUpdateDTO {
boundaryName?: string;
boundaryType?: BoundaryType;
geoJson?: string;
centerLongitude?: number;
centerLatitude?: number;
polygonData?: string;
centerPoint?: string;
area?: number;
remark?: string;
sourceType?: 'manual' | 'model' | 'import';
modelId?: string;
}
/**
* 边界详情VO(对应后端)
*/
export interface WaterBoundaryVO {
id: string;
scenicId: number;
boundaryId: string;
deviceSn?: string;
scenicId?: number;
boundaryName: string;
boundaryType: BoundaryType;
geoJson: string;
centerLongitude: number;
centerLatitude: number;
area: number;
vertexCount: number;
remark?: string;
createTime: string;
updateTime: string;
boundaryTypeDesc?: string;
polygonData: string;
centerPoint?: string;
area?: number;
sourceType?: string;
/** 是否在模型中显示标绘:0-否,1-是 */
showInModel?: 0 | 1;
status?: number;
statusDesc?: string;
createTime?: string;
}
/**
* BoundaryEditor组件Props
*/
export interface BoundaryEditorProps {
/** 景区ID */
scenicId: number;
/** 绑定设备SN */
deviceSn: string;
/** 编辑已有边界的ID(可选) */
boundaryId?: string;
/** 初始顶点(可选) */
@@ -102,9 +112,11 @@ export interface BoundaryToolbarProps {
hasVertices: boolean;
hasUnsavedChanges: boolean;
isDrawing: boolean;
canUndo?: boolean;
onModeChange: (mode: EditorMode) => void;
onStartDraw: () => void;
onFinishDraw: () => void;
onUndo?: () => void;
onClear: () => void;
onSave: () => void;
onCancel: () => void;
@@ -1,12 +1,17 @@
.layerPanel {
position: absolute;
bottom: 20px;
left: 20px;
top: 20px;
width: 320px;
max-height: 600px;
z-index: 100;
}
.cardTitle {
cursor: move;
user-select: none;
}
.card {
background: rgba(10, 20, 40, 0.95) !important;
border-radius: 8px;
File diff suppressed because it is too large Load Diff
@@ -64,6 +64,13 @@
}
}
.headerActions {
display: flex;
align-items: center;
gap: 8px;
}
.minimizeBtn,
.closeBtn {
width: 32px;
height: 32px;
@@ -75,12 +82,18 @@
color: rgba(255, 255, 255, 0.6);
cursor: pointer;
transition: all 0.3s;
&:hover {
background: rgba(255, 50, 50, 0.2);
border-color: rgba(255, 50, 50, 0.5);
color: @neon-red;
}
}
.minimizeBtn:hover {
background: rgba(0, 240, 255, 0.12);
border-color: rgba(0, 240, 255, 0.5);
color: @cyan;
}
.closeBtn:hover {
background: rgba(255, 50, 50, 0.2);
border-color: rgba(255, 50, 50, 0.5);
color: @neon-red;
}
}
}
@@ -365,4 +378,4 @@
}
}
}
}
}
@@ -3,6 +3,7 @@ import { Spin, Empty, message, Tooltip, Tabs, Progress, Modal } from 'antd';
import type { TabsProps } from 'antd';
import {
CloseOutlined,
RightOutlined,
HomeOutlined,
RocketOutlined,
VideoCameraOutlined,
@@ -14,7 +15,6 @@ import {
UnorderedListOutlined,
CompassOutlined,
EnvironmentOutlined,
EditOutlined,
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { saveMission, MissionType } from '@/services/mission';
@@ -26,6 +26,9 @@ import styles from './RightPanel.less';
interface RightPanelProps {
visible: boolean;
device: any; // 直接接收选中的设备
/** 收起到“设备面板”按钮(不清空选中设备) */
onMinimize: () => void;
/** 关闭面板(退出设备:会清空选中设备等) */
onClose: () => void;
onControlClick: (device: any, realtimeData: any) => void;
onTaskPanelOpen?: (device: any, dockData: any) => void; // 打开任务管理面板回调
@@ -37,6 +40,7 @@ interface RightPanelProps {
const RightPanel: React.FC<RightPanelProps> = ({
visible,
device,
onMinimize,
onClose,
onControlClick,
onTaskPanelOpen,
@@ -102,6 +106,11 @@ const RightPanel: React.FC<RightPanelProps> = ({
onClose();
};
// 收起到“设备面板”
const handleMinimize = () => {
onMinimize();
};
const dockData = realtimeData?.rawData?.dockData;
const battery = realtimeData?.battery ?? 0;
@@ -218,7 +227,18 @@ const RightPanel: React.FC<RightPanelProps> = ({
}
</div>
</div>
<button className={styles.closeBtn} onClick={handleClose}><CloseOutlined /></button>
<div className={styles.headerActions}>
<Tooltip title="收起到设备面板">
<button className={styles.minimizeBtn} onClick={handleMinimize}>
<RightOutlined />
</button>
</Tooltip>
<Tooltip title="退出设备">
<button className={styles.closeBtn} onClick={handleClose}>
<CloseOutlined />
</button>
</Tooltip>
</div>
</div>
</div>
@@ -278,14 +298,9 @@ const RightPanel: React.FC<RightPanelProps> = ({
{/* 操作区 */}
<div className={styles.actions}>
<div className={styles.actionRow}>
<button className={styles.primary} onClick={() => onRoutePlanningOpen?.(device)}>
<EditOutlined /> 航线规划
</button>
<button className={styles.task} onClick={() => onTaskPanelOpen?.(device, null)}>
<UnorderedListOutlined /> 任务管理
</button>
</div>
<button className={styles.task} onClick={() => onTaskPanelOpen?.(device, null)}>
<UnorderedListOutlined /> 任务管理
</button>
</div>
</div>
) : (
@@ -25,6 +25,8 @@ import {
} from '@ant-design/icons';
import { DroneData } from '../hooks/useDroneSSE';
import { waylineRouteApi, WaylineRouteListItemVO, WaypointVO } from '@/services/waylineRoute';
import { getBoatRoutesByDevice, getBoatRouteDetail } from '@/services/boatRoute';
import type { BoatRouteListVO, BoatWaypointVO } from '@/types/boatRoute';
import {
Mission,
MissionImage,
@@ -54,6 +56,29 @@ interface TaskPanelProps {
dockData?: any; // 机库数据,用于检查 mode_code
}
// 统一的航线数据类型
type UnifiedRouteItem = {
routeId: string;
routeName: string;
waypointCount: number;
totalDistance: number;
totalDuration?: number; // 可选,无人机航线有
totalDurationStr?: string; // 可选,无人船航线有
deviceSn?: string;
deviceName?: string;
routeType: 'drone' | 'boat'; // 标识航线类型
};
// 统一的航点数据类型
type UnifiedWaypoint = {
index: number;
longitude: number;
latitude: number;
height?: number; // 无人机航点有高度
speed?: number; // 无人船航点有速度
waypointType: 'drone' | 'boat';
};
// 获取任务状态图标
const getMissionStatusIcon = (status: number) => {
switch (status) {
@@ -104,10 +129,13 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
}) => {
const deviceSn = device?.deviceSn;
// 航线相关状态
const [routeList, setRouteList] = useState<WaylineRouteListItemVO[]>([]);
// 判断是否为无人船设备 (deviceType === 4)
const isBoatDevice = useMemo(() => device?.deviceType === 4, [device?.deviceType]);
// 航线相关状态 - 使用统一的数据类型
const [routeList, setRouteList] = useState<UnifiedRouteItem[]>([]);
const [selectedRouteId, setSelectedRouteId] = useState<string | null>(null);
const [waypoints, setWaypoints] = useState<WaypointVO[]>([]);
const [waypoints, setWaypoints] = useState<UnifiedWaypoint[]>([]);
const [routeLoading, setRouteLoading] = useState(false);
// 任务相关状态
@@ -171,17 +199,6 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
}
}, [visible, deviceSn]);
// 调试:监测 props 变化
useEffect(() => {
console.log('[TaskPanel] props变化:', {
visible,
hasViewer: !!viewer,
hasCesium: !!Cesium,
deviceSn,
hasDroneData: !!droneData,
});
}, [visible, viewer, Cesium, deviceSn, droneData]);
// 飞到无人机位置
const flyToDrone = useCallback(() => {
if (!viewer || !Cesium || !realtimePosition) {
@@ -211,20 +228,76 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
message.success('已飞到无人机位置');
}, [viewer, Cesium, realtimePosition]);
// 加载航线列表
// 加载航线列表 - 根据设备类型调用不同的API
const loadRoutesByDevice = useCallback(async (sn: string) => {
try {
setRouteLoading(true);
const res = await waylineRouteApi.getRouteListByDevice(sn);
if (res.resp_code === 0) {
setRouteList(res.data || []);
if (isBoatDevice) {
// 无人船航线
const res = await getBoatRoutesByDevice(sn);
const list = (res as any)?.datas ?? (res as any)?.data;
if (res.resp_code === 0 && Array.isArray(list)) {
// 转换为统一格式
const unifiedRoutes: UnifiedRouteItem[] = list.map((route: BoatRouteListVO) => ({
routeId: route.routeId,
routeName: route.routeName,
waypointCount: route.waypointCount,
totalDistance: route.totalDistance,
totalDuration: route.totalDuration,
totalDurationStr: route.totalDurationStr,
deviceSn: route.deviceSn,
deviceName: route.deviceName,
routeType: 'boat' as const,
}));
setRouteList(unifiedRoutes);
// 默认选中第一条,并绘制到模型上(仅首次进入或未选中时)
if (!selectedRouteId && unifiedRoutes.length > 0) {
const first = unifiedRoutes[0];
setSelectedRouteId(first.routeId);
loadWaypoints(first.routeId, first.routeType);
}
} else {
console.warn('[TaskPanel] 加载无人船航线失败:', res);
setRouteList([]);
}
} else {
// 无人机航线
const res = await waylineRouteApi.getRouteListByDevice(sn);
const list = (res as any)?.datas ?? (res as any)?.data;
if (res.resp_code === 0 && Array.isArray(list)) {
// 转换为统一格式
const unifiedRoutes: UnifiedRouteItem[] = list.map((route: WaylineRouteListItemVO) => ({
routeId: route.routeId,
routeName: route.routeName,
waypointCount: route.waypointCount,
totalDistance: route.totalDistance,
totalDuration: route.totalDuration,
deviceSn: route.deviceSn,
deviceName: route.deviceName,
routeType: 'drone' as const,
}));
setRouteList(unifiedRoutes);
if (!selectedRouteId && unifiedRoutes.length > 0) {
const first = unifiedRoutes[0];
setSelectedRouteId(first.routeId);
loadWaypoints(first.routeId, first.routeType);
}
} else {
console.warn('[TaskPanel] 加载无人机航线失败:', res);
setRouteList([]);
}
}
} catch (e) {
console.error('[TaskPanel] 加载航线列表失败:', e);
message.error('加载航线列表失败');
setRouteList([]);
} finally {
setRouteLoading(false);
}
}, []);
}, [isBoatDevice, selectedRouteId, loadWaypoints]);
// 加载任务列表
const loadMissionsByDevice = useCallback(async (sn: string) => {
@@ -248,54 +321,177 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
}
}, []);
// 加载航点并绘制
const loadWaypoints = useCallback(async (routeId: string) => {
// 加载航点并绘制 - 根据航线类型调用不同的API
const loadWaypoints = useCallback(async (routeId: string, routeTypeOverride?: UnifiedRouteItem['routeType']) => {
try {
const res = await waylineRouteApi.getRouteWaypoints(routeId);
if (res.resp_code === 0 && res.data?.length) {
setWaypoints(res.data);
if (viewer && Cesium) {
drawWaylineOnMap(res.data);
const selectedRoute = routeList.find(r => r.routeId === routeId);
const routeType = routeTypeOverride || selectedRoute?.routeType || (isBoatDevice ? 'boat' : 'drone');
if (routeType === 'boat') {
// 加载无人船航点
const res = await getBoatRouteDetail(routeId);
const payload = (res as any)?.datas ?? (res as any)?.data;
if (res.resp_code === 0 && payload?.waypoints?.length) {
// 转换为统一格式
const unifiedWaypoints: UnifiedWaypoint[] = payload.waypoints.map((wp: BoatWaypointVO) => ({
index: wp.waypointIndex,
longitude: wp.longitude,
latitude: wp.latitude,
height: 0, // 无人船航线高度为0
speed: wp.speed,
waypointType: 'boat' as const,
}));
setWaypoints(unifiedWaypoints);
if (viewer && Cesium) {
await drawWaylineOnMap(unifiedWaypoints);
}
} else {
console.warn('[TaskPanel] 加载无人船航点失败:', res);
}
} else {
// 加载无人机航点
const res = await waylineRouteApi.getRouteWaypoints(routeId);
const list = (res as any)?.datas ?? (res as any)?.data;
if (res.resp_code === 0 && Array.isArray(list) && list.length) {
// 转换为统一格式
const unifiedWaypoints: UnifiedWaypoint[] = list.map((wp: WaypointVO) => ({
index: wp.index,
longitude: wp.longitude,
latitude: wp.latitude,
height: wp.height,
speed: wp.speed,
waypointType: 'drone' as const,
}));
setWaypoints(unifiedWaypoints);
if (viewer && Cesium) {
await drawWaylineOnMap(unifiedWaypoints);
}
} else {
console.warn('[TaskPanel] 加载无人机航点失败:', res);
}
}
} catch (e) {
console.error('[TaskPanel] 加载航点失败:', e);
message.error('加载航点失败');
}
}, [viewer, Cesium]);
}, [viewer, Cesium, routeList, drawWaylineOnMap, isBoatDevice]);
// 绘制航线
const drawWaylineOnMap = useCallback((waypoints: WaypointVO[]) => {
// 绘制航线 - 支持无人机和无人船航线,使用clampToHeightMostDetailed贴模型
const drawWaylineOnMap = useCallback(async (waypoints: UnifiedWaypoint[]) => {
if (!viewer || !Cesium || !waypoints.length) return;
clearWaylineEntities();
// 调试:打印航点高度信息
console.log('[航线绘制] 航点数量:', waypoints.length);
console.log('[航线绘制] 前3个航点:', waypoints.slice(0, 3).map(wp => ({
index: wp.index,
lng: wp.longitude,
lat: wp.latitude,
height: wp.height,
ellipsoidHeight: wp.ellipsoidHeight,
})));
const isBoatRoute = waypoints[0].waypointType === 'boat';
// 使用 height(相对高度)
const positions = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(
wp.longitude,
wp.latitude,
wp.height ?? 100
)
// 检查航点数据有效性
const validWaypoints = waypoints.filter(wp =>
Number.isFinite(wp.longitude) &&
Number.isFinite(wp.latitude) &&
Math.abs(wp.longitude) <= 180 &&
Math.abs(wp.latitude) <= 90
);
// 计划航线(蓝色)- 使用简单的实线,加粗
if (validWaypoints.length !== waypoints.length) {
console.error('[航线绘制] 发现无效航点!有效:', validWaypoints.length, '总数:', waypoints.length);
message.error('航线数据异常,部分航点无效');
return;
}
if (validWaypoints.length < 2) {
message.warning('航点数量不足,无法绘制航线');
return;
}
// 准备航点位置(空中300米,用于clamp)
const waypointPositionsAbove = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300)
);
// 准备航线密集化点(用于更平滑的航线)
const densifiedPoints: any[] = [];
for (let i = 0; i < waypoints.length - 1; i++) {
const a = waypoints[i];
const b = waypoints[i + 1];
const ca = Cesium.Cartographic.fromDegrees(a.longitude, a.latitude, 300);
const cb = Cesium.Cartographic.fromDegrees(b.longitude, b.latitude, 300);
const geodesic = new Cesium.EllipsoidGeodesic(ca, cb);
const dist = Number(geodesic.surfaceDistance) || 0;
// 每段采样点数
const segments = Math.max(2, Math.min(60, Math.ceil(dist / 8)));
for (let s = 0; s <= segments; s++) {
if (i > 0 && s === 0) continue; // 避免重复点
const frac = segments === 0 ? 0 : s / segments;
const c = geodesic.interpolateUsingFraction(frac);
c.height = 300;
densifiedPoints.push(Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height));
}
}
let waypointPositions = waypointPositionsAbove;
let polylinePositions = densifiedPoints.length >= 2 ? densifiedPoints : waypointPositionsAbove;
// 如果是无人船航线,尝试贴模型表面
if (isBoatRoute && viewer.scene?.clampToHeightMostDetailed) {
try {
// 贴航点
const clampedWaypoints = await viewer.scene.clampToHeightMostDetailed(waypointPositionsAbove);
if (clampedWaypoints && clampedWaypoints.length === waypoints.length) {
waypointPositions = clampedWaypoints.map((p: any) => {
if (!p) return null;
const carto = Cesium.Cartographic.fromCartesian(p);
carto.height = (Number(carto.height) || 0) + 0.05; // 抬高5cm,避免Z-fighting
return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height);
}).filter(Boolean);
}
// 贴航线
if (densifiedPoints.length >= 2) {
const clampedLine = await viewer.scene.clampToHeightMostDetailed(densifiedPoints);
if (clampedLine && clampedLine.length >= 2) {
polylinePositions = clampedLine.map((p: any) => {
if (!p) return null;
const carto = Cesium.Cartographic.fromCartesian(p);
carto.height = (Number(carto.height) || 0) + 0.05; // 抬高5cm,避免Z-fighting
return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height);
}).filter(Boolean);
}
}
} catch (e) {
console.warn('[航线绘制] 贴模型表面失败,使用默认高度:', e);
// 失败则使用地面高度
waypointPositions = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0.05)
);
polylinePositions = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0.05)
);
}
} else if (!isBoatRoute) {
// 无人机航线,使用指定高度
waypointPositions = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height ?? 100)
);
polylinePositions = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height ?? 100)
);
}
// 根据航线类型选择颜色
const routeColor = isBoatRoute
? Cesium.Color.fromCssColorString('#52c41a').withAlpha(0.9) // 绿色 - 无人船
: Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9); // 蓝色 - 无人机
// 绘制航线
waylineEntityRef.current = viewer.entities.add({
name: '计划航线',
name: isBoatRoute ? '无人船航线' : '无人机航线',
polyline: {
positions: positions,
positions: polylinePositions,
width: 6,
material: Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9),
clampToGround: false,
material: routeColor,
clampToGround: false, // 已经手动贴地,不需要clampToGround
arcType: Cesium.ArcType?.NONE,
},
});
@@ -307,12 +503,16 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
const isFirst = index === 0;
const isLast = index === totalPoints - 1;
const isKeyPoint = isFirst || isLast || (index % labelInterval === 0);
const pointColor = isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff';
const altitude = wp.height ?? 100;
const pointColor = isBoatRoute
? (isFirst ? '#389e0d' : isLast ? '#237804' : '#52c41a') // 绿色系 - 无人船
: (isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff'); // 蓝色系 - 无人机
const position = waypointPositions[index];
if (!position) return;
const entity = viewer.entities.add({
name: `航点${index + 1}`,
position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, altitude),
position: position,
point: {
pixelSize: isKeyPoint ? 12 : 8,
color: Cesium.Color.fromCssColorString(pointColor),
@@ -335,51 +535,70 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
waypointEntitiesRef.current.push(entity);
});
// 飞到航线
flyToWayline(waypoints);
}, [viewer, Cesium]);
// 飞到航线,传递渲染后的positions用于精确计算视角
flyToWayline(waypoints, polylinePositions.length >= 2 ? polylinePositions : waypointPositions);
}, [viewer, Cesium, flyToWayline, clearWaylineEntities]);
// 飞到航线位置 - 垂直俯视整条航线
const flyToWayline = useCallback((waypoints: WaypointVO[]) => {
// 飞到航线位置 - 参考航线规划页面的实现
const flyToWayline = useCallback((waypoints: UnifiedWaypoint[], positions?: any[]) => {
if (!viewer || !Cesium || !waypoints.length) return;
let minLon = Infinity, maxLon = -Infinity;
let minLat = Infinity, maxLat = -Infinity;
let maxHeight = 0;
try {
// 优先使用实际渲染的positions(已经贴模型表面的点)
const points = positions && positions.length >= 2 ? positions : null;
waypoints.forEach(wp => {
minLon = Math.min(minLon, wp.longitude);
maxLon = Math.max(maxLon, wp.longitude);
minLat = Math.min(minLat, wp.latitude);
maxLat = Math.max(maxLat, wp.latitude);
maxHeight = Math.max(maxHeight, wp.height || 100);
});
if (points && Cesium.BoundingSphere?.fromPoints) {
// 使用边界球方式(与航线规划页面一致)
const bs = Cesium.BoundingSphere.fromPoints(points);
const radius = Number(bs.radius) || 0;
const centerLon = (minLon + maxLon) / 2;
const centerLat = (minLat + maxLat) / 2;
// 调整视距:半径的1.5倍,最小100米(更近的视角)
const range = Math.max(100, radius * 1.5);
// 计算航线范围的对角线距离(经纬度转换为大约的米数)
const lonSpan = maxLon - minLon;
const latSpan = maxLat - minLat;
// 1度经度约111km(在赤道),纬度方向约111km
const spanMeters = Math.sqrt(
Math.pow(lonSpan * 111000 * Math.cos(centerLat * Math.PI / 180), 2) +
Math.pow(latSpan * 111000, 2)
);
viewer.camera.flyToBoundingSphere(bs, {
duration: 1.2,
offset: new Cesium.HeadingPitchRange(
0, // 重置heading为正北
Cesium.Math.toRadians(-45),
range
),
});
} else {
// 回退:使用矩形范围
let minLon = Infinity, maxLon = -Infinity;
let minLat = Infinity, maxLat = -Infinity;
// 视角高度:航线范围的0.2倍 + 最高航点高度
// 更贴近航线
const viewHeight = Math.max(spanMeters * 0.2, 30) + maxHeight;
waypoints.forEach(wp => {
minLon = Math.min(minLon, wp.longitude);
maxLon = Math.max(maxLon, wp.longitude);
minLat = Math.min(minLat, wp.latitude);
maxLat = Math.max(maxLat, wp.latitude);
});
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, viewHeight),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90), // 垂直俯视,确保航迹在正下方
roll: 0,
},
duration: 1.5,
});
// 添加20%的padding,确保能看到整条航线
const lonSpan = maxLon - minLon;
const latSpan = maxLat - minLat;
const paddingLon = Math.max(lonSpan * 0.2, 0.001); // 至少0.001度
const paddingLat = Math.max(latSpan * 0.2, 0.001);
viewer.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(
minLon - paddingLon,
minLat - paddingLat,
maxLon + paddingLon,
maxLat + paddingLat
),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-45),
roll: 0,
},
duration: 1.0,
});
}
} catch (e) {
console.error('[航线视角] 飞到航线失败:', e);
}
}, [viewer, Cesium]);
// 检查 viewer 是否有效
@@ -785,7 +1004,13 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
</div>
<div className={styles.infoItem}>
<span className={styles.label}>预计时长</span>
<span className={styles.value}>{Math.ceil(selectedRoute.totalDuration / 60)} 分钟</span>
<span className={styles.value}>
{selectedRoute.totalDurationStr
? selectedRoute.totalDurationStr
: (selectedRoute.totalDuration && Number.isFinite(selectedRoute.totalDuration) && selectedRoute.totalDuration > 0
? `${Math.ceil(selectedRoute.totalDuration / 60)} 分钟`
: '--')}
</span>
</div>
</div>
</div>
@@ -827,15 +1052,15 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
<div className={styles.legend}>
<div className={styles.legendItem}>
<span className={`${styles.legendLine} ${styles.blue}`}></span>
<span>计划航线</span>
<span>无人机航线</span>
</div>
<div className={styles.legendItem}>
<span className={`${styles.legendLine} ${styles.green}`}></span>
<span>飞行轨迹</span>
<span>无人船航线</span>
</div>
<div className={styles.legendItem}>
<span className={styles.legendPoint}></span>
<span>无人机</span>
<span>实时位置</span>
</div>
</div>
</div>
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { message, Button, Tooltip } from 'antd';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import { AppstoreOutlined, BarsOutlined, ProfileOutlined, EditOutlined } from '@ant-design/icons';
import RightPanel from './3d/BottomPanel/RightPanel';
import LeftControlPanel from './3d/BottomPanel/LeftControlPanel';
import TaskPanel from './3d/BottomPanel/TaskPanel';
@@ -32,6 +32,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const entitiesRef = useRef<Map<string, any>>(new Map());
const pickHandlerRef = useRef<any>(null);
const [loading, setLoading] = useState(true);
const [viewerReady, setViewerReady] = useState(false); // 新增:viewer 是否完全就绪
@@ -52,9 +53,11 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 航线规划面板状态(无人船)
const [routePlanningVisible, setRoutePlanningVisible] = useState(false);
const [routePlanningDevice, setRoutePlanningDevice] = useState<any>(null);
const [routePlanningBoundaryId, setRoutePlanningBoundaryId] = useState<string | null>(null);
// 边界编辑面板状态(水域边界)
const [boundaryEditorVisible, setBoundaryEditorVisible] = useState(false);
const [autoShowBoundaryId, setAutoShowBoundaryId] = useState<string | null>(null);
// 图层管理面板状态
const [layerPanelVisible, setLayerPanelVisible] = useState(false);
@@ -288,12 +291,14 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 使用较短的动画时间,因为相机已经在设备附近了
if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) {
try {
const radius = Number(firstTileset?.boundingSphere?.radius);
const range = Number.isFinite(radius) && radius > 0 ? Math.max(40, radius * 0.7) : 80;
viewerRef.current.flyTo(firstTileset, {
duration: 1.0, // 缩短动画时间,因为已经在附近
duration: 0.8, // 缩短动画时间,因为已经在附近
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45),
0
Cesium.Math.toRadians(-70), // 改为70度俯视,更接近垂直俯视
range
),
});
} catch (e) {
@@ -410,6 +415,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const handleOpenRoutePlanning = useCallback((device: any) => {
setRoutePlanningDevice(device);
setRoutePlanningVisible(true);
setRoutePlanningBoundaryId(null);
// 关闭其他面板
setRightPanelVisible(false);
}, []);
@@ -418,27 +424,58 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const handleCloseRoutePlanning = useCallback(() => {
setRoutePlanningVisible(false);
setRoutePlanningDevice(null);
}, []);
setRoutePlanningBoundaryId(null);
// 退出后恢复右侧面板入口
if (selectedDevice) {
setRightPanelVisible(true);
}
}, [selectedDevice]);
// 航线保存成功回调
const handleRoutesSaveSuccess = useCallback((routeId: string) => {
message.success('航线保存成功');
setRoutePlanningVisible(false);
setRoutePlanningDevice(null);
// 保持航线规划面板不关闭:由 RouteEditor 内部切回“航线库”并刷新列表
// 这里保留回调入口,便于后续做跨面板联动
void routeId;
}, []);
// 从图层管理面板:基于边界快速进入航线规划(仅可航行边界)
const handleOpenRoutePlanningByBoundary = useCallback((boundary: any) => {
if (!selectedDevice) {
message.warning('请先选择设备');
return;
}
const boundaryId = String(boundary?.boundaryId || '').trim();
if (!boundaryId) {
message.warning('边界ID无效,无法进入航线规划');
return;
}
setRoutePlanningDevice(selectedDevice);
setRoutePlanningVisible(true);
setRoutePlanningBoundaryId(boundaryId);
setLayerPanelVisible(false);
setRightPanelVisible(false);
}, [selectedDevice]);
// 处理从图层管理面板点击"新建边界"
const handleOpenBoundaryEditor = useCallback(() => {
const sn = String(selectedDevice?.deviceSn || '').trim();
if (!sn) {
message.warning('请先选择设备后再新建边界');
return;
}
setBoundaryEditorVisible(true);
// 关闭其他面板
setLayerPanelVisible(false);
setRightPanelVisible(false);
}, []);
}, [selectedDevice]);
// 关闭边界编辑器
const handleCloseBoundaryEditor = useCallback(() => {
setBoundaryEditorVisible(false);
}, []);
if (selectedDevice) {
setRightPanelVisible(true);
}
}, [selectedDevice]);
// 边界保存成功回调
const handleBoundarySaveSuccess = useCallback((boundaryId: string) => {
@@ -446,7 +483,11 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
setBoundaryEditorVisible(false);
// 重新打开图层管理面板,显示新创建的边界
setLayerPanelVisible(true);
}, []);
setAutoShowBoundaryId(boundaryId);
if (selectedDevice) {
setRightPanelVisible(true);
}
}, [selectedDevice]);
// 计算无人机实时位置
const realtimePosition = useMemo(() => {
@@ -638,6 +679,11 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
flyToGlobal();
}, [flyToGlobal, unloadAllTilesets, onClearSelection, droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]);
// 收起到“设备面板”(不清空设备、不卸载模型)
const handleRightPanelMinimize = useCallback(() => {
setRightPanelVisible(false);
}, []);
// ========== 3D Tiles 模型管理方法 ==========
// 加载模型
@@ -862,9 +908,32 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
if (loading || !viewerRef.current || !Cesium) return;
const viewer = viewerRef.current;
viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
if (viewer.isDestroyed?.()) return;
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// 清理旧的拾取 handler(React 18 dev 下 effect 可能会触发多次)
if (pickHandlerRef.current) {
try {
pickHandlerRef.current.destroy();
} catch {
// 忽略
}
pickHandlerRef.current = null;
}
try {
viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
} catch {
// 忽略
}
let handler: any = null;
try {
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
pickHandlerRef.current = handler;
} catch (e) {
console.warn('初始化拾取事件失败:', e);
return;
}
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.position);
@@ -893,7 +962,14 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
return () => {
handler.destroy();
if (pickHandlerRef.current === handler) {
try {
handler.destroy();
} catch {
// 忽略
}
pickHandlerRef.current = null;
}
document.body.style.cursor = 'default';
};
}, [loading, handleDeviceSelect]);
@@ -964,7 +1040,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
)}
{/* 3D模型管理按钮 - 当设备有绑定模型时显示 */}
{!loading && currentDeviceModels.length > 0 && (
{!loading && !boundaryEditorVisible && currentDeviceModels.length > 0 && (
<Tooltip title="3D模型管理">
<Button
type="primary"
@@ -981,8 +1057,27 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
/>
</Tooltip>
)}
{/* 航线规划按钮(无人船) - 放到图层/模型管理同一栏 */}
{!loading && !boundaryEditorVisible && selectedDevice?.deviceType === 4 && (
<Tooltip title="航线规划">
<Button
type="primary"
icon={<EditOutlined />}
onClick={() => handleOpenRoutePlanning(selectedDevice)}
style={{
position: 'absolute',
top: 10,
right: 130,
zIndex: 700,
background: routePlanningVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
{/* 图层管理按钮 - 航线和边界图层控制 */}
{!loading && selectedDevice && (
{!loading && !boundaryEditorVisible && selectedDevice && (
<Tooltip title="图层管理">
<Button
type="primary"
@@ -1000,6 +1095,25 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
</Tooltip>
)}
{/* 设备面板按钮 - 重新打开右侧数据面板 */}
{!loading && !boundaryEditorVisible && selectedDevice && (
<Tooltip title="设备面板">
<Button
type="primary"
icon={<ProfileOutlined />}
onClick={() => setRightPanelVisible(v => !v)}
style={{
position: 'absolute',
top: 10,
right: 280,
zIndex: 700,
background: rightPanelVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
{/* 3D Tiles模型管理面板 - TODO: TilesetPanel组件未实现,暂时注释 */}
<TilesetPanel
@@ -1028,6 +1142,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
visible={rightPanelVisible}
device={selectedDevice}
onClose={handleRightPanelClose}
onMinimize={handleRightPanelMinimize}
onControlClick={handleOpenControl}
onTaskPanelOpen={handleOpenTaskPanel}
onRoutePlanningOpen={handleOpenRoutePlanning}
@@ -1052,36 +1167,31 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
onClose={() => setLayerPanelVisible(false)}
viewer={viewerRef.current}
Cesium={Cesium}
deviceSn={selectedDevice?.deviceSn}
scenicId={selectedDevice?.scenicId}
onBoundaryEditorOpen={handleOpenBoundaryEditor}
onRoutePlanningOpen={handleOpenRoutePlanningByBoundary}
autoShowBoundaryId={autoShowBoundaryId || undefined}
onAutoShowBoundaryHandled={() => setAutoShowBoundaryId(null)}
/>
{/* 无人船航线规划面板 */}
{routePlanningVisible && routePlanningDevice && (
<div style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 1000,
background: 'rgba(0, 0, 0, 0.5)',
}}>
<RouteEditor
scenicId={routePlanningDevice.scenicId || 1}
deviceSn={routePlanningDevice.deviceSn}
onSaveSuccess={handleRoutesSaveSuccess}
onCancel={handleCloseRoutePlanning}
viewerRef={viewerRef}
/>
</div>
{/* 无人船航线规划面板 - 浮层形式,不遮挡地图点击 */}
{routePlanningVisible && routePlanningDevice && viewerReady && (
<RouteEditor
scenicId={routePlanningDevice.scenicId || 1}
deviceSn={routePlanningDevice.deviceSn}
boundaryId={routePlanningBoundaryId || undefined}
onSaveSuccess={handleRoutesSaveSuccess}
onCancel={handleCloseRoutePlanning}
viewerRef={viewerRef}
/>
)}
{/* 水域边界编辑器 - 工具栏浮层形式,不遮挡地图 */}
{/* 只有当 viewer 完全就绪后才渲染 */}
{boundaryEditorVisible && viewerReady && (
{boundaryEditorVisible && viewerReady && !!selectedDevice?.deviceSn && (
<BoundaryEditor
scenicId={selectedDevice?.scenicId || 1}
deviceSn={selectedDevice?.deviceSn}
onSaveSuccess={handleBoundarySaveSuccess}
onCancel={handleCloseBoundaryEditor}
viewerRef={viewerRef}
@@ -4,7 +4,7 @@
* @date 2026-01-05
*/
import React from 'react';
import { Card, Descriptions, Alert, List, Tag, Progress } from 'antd';
import { Card, Descriptions, Alert, List, Tag } from 'antd';
import {
EnvironmentOutlined,
ClockCircleOutlined,
@@ -48,7 +48,7 @@ const RoutePreview: React.FC<RoutePreviewProps> = ({
return (
<div className={styles.preview}>
<Card size="small" title="航线预览" bordered={false}>
<Card size="small" title="航线概览" bordered={false}>
<Descriptions column={2} size="small">
<Descriptions.Item label={<><EnvironmentOutlined /> 航点数</>}>
{waypoints.length}
@@ -118,7 +118,7 @@ const RoutePreview: React.FC<RoutePreviewProps> = ({
{/* 航点列表 */}
{waypoints.length > 0 && (
<Card size="small" title="航点列表" bordered={false} style={{ marginTop: 8 }}>
<Card size="small" title="航点明细" bordered={false} style={{ marginTop: 8 }}>
<List
size="small"
dataSource={waypoints}
@@ -129,7 +129,7 @@ const RoutePreview: React.FC<RoutePreviewProps> = ({
{wp.isKeyPoint && <Tag color="blue" style={{ marginRight: 4 }}>关键</Tag>}
{wp.pointName || `航点${index + 1}`}
</span>
<span style={{ fontSize: 11, color: '#999' }}>
<span style={{ fontSize: 11, color: 'rgba(255,255,255,0.58)' }}>
{wp.longitude.toFixed(4)}, {wp.latitude.toFixed(4)}
</span>
{wp.stayDuration && wp.stayDuration > 0 && (
@@ -4,9 +4,8 @@
* @date 2026-01-05
*/
import React from 'react';
import { Button, Space, Tooltip, Popconfirm } from 'antd';
import { Button, Tooltip, Popconfirm } from 'antd';
import {
EditOutlined,
SelectOutlined,
DeleteOutlined,
UndoOutlined,
@@ -24,6 +23,7 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
mode,
hasWaypoints,
hasUnsavedChanges,
canUndo,
isValidating,
isPreviewing,
onModeChange,
@@ -37,10 +37,11 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
}) => {
return (
<div className={styles.toolbar}>
<Space size="small">
<div className={styles.toolbarGroup}>
{/* 绘制模式 */}
<Tooltip title="绘制航点">
<Button
size="small"
type={mode === 'draw' ? 'primary' : 'default'}
icon={<AimOutlined />}
onClick={() => onModeChange('draw')}
@@ -53,6 +54,7 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
{/* 选择模式 */}
<Tooltip title="选择航点">
<Button
size="small"
type={mode === 'select' || mode === 'edit' ? 'primary' : 'default'}
icon={<SelectOutlined />}
onClick={() => onModeChange('select')}
@@ -61,13 +63,14 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
选择
</Button>
</Tooltip>
</div>
<div className={styles.divider} />
<div className={styles.toolbarGroup}>
{/* 第一视角预览 */}
{isPreviewing ? (
<Tooltip title="停止预览">
<Button
size="small"
type="primary"
danger
icon={<PauseCircleOutlined />}
@@ -79,6 +82,7 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
) : (
<Tooltip title="第一视角预览航线">
<Button
size="small"
icon={<EyeOutlined />}
onClick={onPreview}
disabled={!hasWaypoints || (hasWaypoints && !onPreview)}
@@ -87,15 +91,16 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
</Button>
</Tooltip>
)}
</div>
<div className={styles.divider} />
<div className={styles.toolbarGroup}>
{/* 撤销 */}
<Tooltip title="撤销">
<Tooltip title="撤销 (Ctrl+Z)">
<Button
size="small"
icon={<UndoOutlined />}
onClick={onUndo}
disabled={!hasUnsavedChanges || isPreviewing}
disabled={!canUndo || isPreviewing}
/>
</Tooltip>
@@ -107,17 +112,19 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
>
<Tooltip title="清空航点">
<Button
size="small"
icon={<DeleteOutlined />}
danger
disabled={!hasWaypoints || isPreviewing}
/>
</Tooltip>
</Popconfirm>
</div>
<div className={styles.divider} />
<div className={`${styles.toolbarGroup} ${styles.toolbarActions}`}>
{/* 校验 */}
<Button
size="small"
icon={<CheckCircleOutlined />}
onClick={onValidate}
loading={isValidating}
@@ -128,6 +135,7 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
{/* 保存 */}
<Button
size="small"
type="primary"
icon={<SaveOutlined />}
onClick={onSave}
@@ -138,13 +146,15 @@ const RouteToolbar: React.FC<RouteToolbarProps> = ({
{/* 取消 */}
<Popconfirm
title={hasUnsavedChanges ? "有未保存的更改,确定取消?" : "确定取消?"}
title={hasUnsavedChanges ? '有未保存的更改,确定取消?' : '确定取消?'}
onConfirm={onCancel}
disabled={isPreviewing}
>
<Button icon={<CloseOutlined />} disabled={isPreviewing}>取消</Button>
<Button size="small" icon={<CloseOutlined />} disabled={isPreviewing}>
取消
</Button>
</Popconfirm>
</Space>
</div>
</div>
);
};
@@ -78,6 +78,19 @@ const WaypointEditor: React.FC<WaypointEditorProps> = ({
width={360}
onClose={onClose}
open={true}
mask={false}
destroyOnClose
styles={{
header: {
background: 'rgba(10, 20, 30, 0.92)',
borderBottom: '1px solid rgba(0, 240, 255, 0.14)',
color: 'rgba(255, 255, 255, 0.92)',
},
body: {
background: 'rgba(10, 20, 30, 0.92)',
color: 'rgba(255, 255, 255, 0.86)',
},
}}
extra={
<Space>
<Button danger onClick={() => { onDelete(index); onClose(); }}>
@@ -104,11 +117,17 @@ const WaypointEditor: React.FC<WaypointEditorProps> = ({
onFinish={handleFinish}
>
{/* 位置信息(只读) */}
<div style={{ marginBottom: 16, padding: '8px 12px', background: '#f5f5f5', borderRadius: 4 }}>
<div style={{ fontSize: 12, color: '#666' }}>
<div style={{
marginBottom: 16,
padding: '8px 12px',
background: 'rgba(255, 255, 255, 0.06)',
border: '1px solid rgba(255, 255, 255, 0.10)',
borderRadius: 10,
}}>
<div style={{ fontSize: 12, color: 'rgba(255, 255, 255, 0.70)' }}>
经度: {waypoint.longitude.toFixed(6)}
</div>
<div style={{ fontSize: 12, color: '#666' }}>
<div style={{ fontSize: 12, color: 'rgba(255, 255, 255, 0.70)' }}>
纬度: {waypoint.latitude.toFixed(6)}
</div>
</div>
@@ -0,0 +1,197 @@
/**
* 航点内嵌编辑器(放在左侧航线规划面板内)
* 目标:避免占用右侧整列抽屉,提高与航点列表/工具栏的联动体验
* @author dzc
* @date 2026-01-07
*/
import React, { useEffect } from 'react';
import { Button, Collapse, Form, Input, InputNumber, Select, Space, Switch, Popconfirm, message } from 'antd';
import { CloseOutlined, DeleteOutlined, SaveOutlined, PlusOutlined } from '@ant-design/icons';
import type { TurnMode, WaypointActionType, BoatWaypointDTO } from '@/types/boatRoute';
import type { WaypointEditorProps } from './types';
import styles from './index.less';
const { Option } = Select;
const { TextArea } = Input;
const turnModeOptions: { value: TurnMode; label: string }[] = [
{ value: 'sharp', label: '锐角转弯' },
{ value: 'smooth', label: '平滑转弯' },
{ value: 'arc', label: '弧线转弯' },
];
const actionTypeOptions: { value: WaypointActionType; label: string }[] = [
{ value: 'hover', label: '悬停' },
{ value: 'take_photo', label: '拍照' },
{ value: 'record_video', label: '录像' },
{ value: 'horn', label: '鸣笛' },
{ value: 'light', label: '灯光' },
{ value: 'spray', label: '喷洒' },
];
const WaypointInlineEditor: React.FC<WaypointEditorProps> = ({
waypoint,
index,
onUpdate,
onDelete,
onClose,
}) => {
const [form] = Form.useForm();
const actionsWatch = Form.useWatch('actions', form);
const actionCount = Array.isArray(actionsWatch) ? actionsWatch.length : (waypoint.actions || []).length;
useEffect(() => {
form.setFieldsValue({
pointName: waypoint.pointName || `航点${index + 1}`,
speed: waypoint.speed,
stayDuration: waypoint.stayDuration || 0,
turnMode: waypoint.turnMode || 'smooth',
isKeyPoint: waypoint.isKeyPoint || false,
actions: waypoint.actions || [],
remark: waypoint.remark,
});
}, [form, waypoint, index]);
const handleFinish = (values: any) => {
const updated: BoatWaypointDTO = {
...waypoint,
...values,
};
onUpdate(index, updated);
message.success('航点已更新(已自动收起编辑区;最终请点击“保存航线”提交)');
onClose?.();
};
return (
<div className={styles.waypointInline}>
<div className={styles.waypointInlineHeader}>
<div className={styles.waypointInlineTitle}>
编辑航点 {index + 1}
</div>
<Space size={6}>
<Popconfirm
title="确定删除该航点?"
okText="删除"
cancelText="取消"
onConfirm={() => onDelete(index)}
>
<Button danger size="small" icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
<Button size="small" icon={<CloseOutlined />} onClick={onClose}>
关闭
</Button>
<Button type="primary" size="small" icon={<SaveOutlined />} onClick={() => form.submit()}>
保存(本地)
</Button>
</Space>
</div>
<div className={styles.waypointInlineMeta}>
<div className={styles.waypointInlineMetaItem}>
<span className={styles.waypointInlineMetaLabel}>经度</span>
<span className={styles.waypointInlineMetaValue}>{waypoint.longitude.toFixed(6)}</span>
</div>
<div className={styles.waypointInlineMetaItem}>
<span className={styles.waypointInlineMetaLabel}>纬度</span>
<span className={styles.waypointInlineMetaValue}>{waypoint.latitude.toFixed(6)}</span>
</div>
</div>
<Form form={form} layout="vertical" onFinish={handleFinish}>
<div className={styles.waypointInlineGrid}>
<Form.Item name="pointName" label="航点名称" className={styles.waypointInlineSpan2}>
<Input placeholder="请输入航点名称" />
</Form.Item>
<Form.Item name="speed" label="航点速度 (m/s)">
<InputNumber min={0.1} max={10} step={0.1} placeholder="默认速度" style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="stayDuration" label="停留时间 (秒)">
<InputNumber min={0} max={600} step={1} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="turnMode" label="转弯模式">
<Select>
{turnModeOptions.map((opt) => (
<Option key={opt.value} value={opt.value}>{opt.label}</Option>
))}
</Select>
</Form.Item>
<Form.Item name="isKeyPoint" label="关键航点" valuePropName="checked">
<Switch />
</Form.Item>
</div>
<Collapse
className={styles.waypointInlineCollapse}
items={[
{
key: 'actions',
label: `航点动作(${actionCount})`,
children: (
<Form.List name="actions">
{(fields, { add, remove }) => (
<div className={styles.waypointActions}>
{fields.map(({ key, name, ...restField }) => (
<div key={key} className={styles.waypointActionRow}>
<Form.Item
{...restField}
name={[name, 'actionType']}
style={{ flex: 1, marginBottom: 0 }}
>
<Select placeholder="动作类型">
{actionTypeOptions.map((opt) => (
<Option key={opt.value} value={opt.value}>{opt.label}</Option>
))}
</Select>
</Form.Item>
<Form.Item
{...restField}
name={[name, 'duration']}
style={{ width: 100, marginBottom: 0 }}
>
<InputNumber min={1} max={300} placeholder="秒" style={{ width: '100%' }} />
</Form.Item>
<Button
danger
size="small"
icon={<DeleteOutlined />}
onClick={() => remove(name)}
/>
</div>
))}
<Button
type="dashed"
block
icon={<PlusOutlined />}
onClick={() => add({ actionType: 'hover', duration: 5 })}
>
添加动作
</Button>
</div>
)}
</Form.List>
),
},
{
key: 'remark',
label: '备注',
children: (
<Form.Item name="remark" style={{ marginBottom: 0 }}>
<TextArea rows={2} placeholder="可选备注信息" />
</Form.Item>
),
},
]}
/>
</Form>
</div>
);
};
export default WaypointInlineEditor;
@@ -0,0 +1,593 @@
/**
* Cesium 已规划航线渲染 Hook
* 负责在 Cesium 地图上渲染“航线库”里勾选显示的航线(只渲染线与起终点,避免太重)
*/
import { useCallback, useEffect, useMemo, useRef } from 'react';
import type { BoatWaypointDTO } from '@/types/boatRoute';
export interface RouteLibraryRenderItem {
routeId: string;
routeName?: string;
waypoints: BoatWaypointDTO[];
visible: boolean;
highlighted?: boolean;
}
interface UseCesiumRouteLibraryRendererOptions {
viewerRef?: React.RefObject<any>;
routes: RouteLibraryRenderItem[];
}
export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRendererOptions) {
const { viewerRef, routes } = options;
const entityIdsByRouteRef = useRef<Map<string, string[]>>(new Map());
const surfaceCacheRef = useRef<Map<string, { key: string; polyline: any[]; start: any; end: any; waypointPositions?: any[] }>>(new Map());
const surfaceComputeSeqRef = useRef<Map<string, number>>(new Map());
const surfaceRetryRef = useRef<Map<string, { key: string; attempt: number; timer: any | null }>>(new Map());
const routesRef = useRef<RouteLibraryRenderItem[]>(routes);
// 贴近模型表面,避免航线“悬浮”
const ROUTE_RENDER_HEIGHT_OFFSET = 0.05;
const getCesium = useCallback(() => (window as any).Cesium, []);
const requestRender = useCallback(() => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return;
try {
viewer.scene?.requestRender?.();
} catch {
// 忽略
}
}, [viewerRef]);
useEffect(() => {
routesRef.current = routes;
}, [routes]);
const buildWaypointsKey = useCallback((points: BoatWaypointDTO[]) => {
return points
.map((p) => `${Number(p.longitude).toFixed(7)},${Number(p.latitude).toFixed(7)}`)
.join('|');
}, []);
const applyHeightOffset = useCallback((Cesium: any, cartesian: any) => {
if (!Cesium || !cartesian) return cartesian;
try {
const carto = Cesium.Cartographic.fromCartesian(cartesian);
carto.height = (Number(carto.height) || 0) + ROUTE_RENDER_HEIGHT_OFFSET;
return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height);
} catch {
return cartesian;
}
}, []);
const densifyWaypoints = useCallback((Cesium: any, points: BoatWaypointDTO[]) => {
if (!Cesium || !Array.isArray(points) || points.length < 2) return [];
const result: any[] = [];
let totalPoints = 0;
const maxTotalPoints = 600;
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const ca = Cesium.Cartographic.fromDegrees(a.longitude, a.latitude, 0);
const cb = Cesium.Cartographic.fromDegrees(b.longitude, b.latitude, 0);
const geodesic = new Cesium.EllipsoidGeodesic(ca, cb);
const dist = Number(geodesic.surfaceDistance) || 0;
const segments = Math.max(2, Math.min(50, Math.ceil(dist / 12)));
for (let s = 0; s <= segments; s++) {
if (i > 0 && s === 0) continue;
if (totalPoints >= maxTotalPoints) break;
const frac = segments === 0 ? 0 : s / segments;
const c = geodesic.interpolateUsingFraction(frac);
c.height = 300;
result.push(c);
totalPoints++;
}
if (totalPoints >= maxTotalPoints) break;
}
return result;
}, []);
const clampPositionsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.() || !Cesium) return null;
if (!Array.isArray(positions) || positions.length < 2) return null;
const scene = viewer.scene;
const fn = scene?.clampToHeightMostDetailed;
if (typeof fn !== 'function') return null;
try {
const clamped = await fn.call(scene, positions);
if (!Array.isArray(clamped) || clamped.length !== positions.length) return null;
let definedCount = 0;
const merged = clamped.map((p: any, idx: number) => {
if (p) definedCount++;
return p || positions[idx];
});
if (definedCount < 2) return null;
return merged.map((p: any) => applyHeightOffset(Cesium, p));
} catch {
return null;
}
}, [viewerRef, applyHeightOffset]);
const clampWaypointsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.() || !Cesium) return null;
if (!Array.isArray(positions) || positions.length < 1) return null;
const scene = viewer.scene;
const fn = scene?.clampToHeightMostDetailed;
if (typeof fn !== 'function') return null;
try {
const clamped = await fn.call(scene, positions);
if (!Array.isArray(clamped) || clamped.length !== positions.length) return null;
return clamped.map((p: any, idx: number) => applyHeightOffset(Cesium, p || positions[idx]));
} catch {
return null;
}
}, [viewerRef, applyHeightOffset]);
const colorFromRouteId = useCallback((routeId: string) => {
let hash = 0;
for (let i = 0; i < routeId.length; i++) {
hash = (hash * 31 + routeId.charCodeAt(i)) >>> 0;
}
const hue = hash % 360;
return `hsl(${hue}, 90%, 60%)`;
}, []);
const calculateBounds = useCallback((points: BoatWaypointDTO[]) => {
const valid = (points || []).filter((p) => {
const lon = Number(p.longitude);
const lat = Number(p.latitude);
return Number.isFinite(lon) && Number.isFinite(lat) && lon >= -180 && lon <= 180 && lat >= -90 && lat <= 90;
});
if (valid.length === 0) {
return { west: 0, south: 0, east: 0, north: 0 };
}
let west = valid[0].longitude;
let east = valid[0].longitude;
let south = valid[0].latitude;
let north = valid[0].latitude;
for (const p of valid) {
west = Math.min(west, p.longitude);
east = Math.max(east, p.longitude);
south = Math.min(south, p.latitude);
north = Math.max(north, p.latitude);
}
const paddingLon = (east - west) * 0.12 || 0.01;
const paddingLat = (north - south) * 0.12 || 0.01;
return {
west: west - paddingLon,
south: south - paddingLat,
east: east + paddingLon,
north: north + paddingLat,
};
}, []);
const removeRouteEntities = useCallback((routeId: string) => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return;
const ids = entityIdsByRouteRef.current.get(routeId) || [];
for (const id of ids) {
try {
viewer.entities.removeById(id);
} catch {
// 忽略
}
}
entityIdsByRouteRef.current.delete(routeId);
// 终止可能的异步贴模计算(通过序列号跳过回写)
const prevSeq = surfaceComputeSeqRef.current.get(routeId) || 0;
surfaceComputeSeqRef.current.set(routeId, prevSeq + 1);
const retry = surfaceRetryRef.current.get(routeId);
if (retry?.timer) {
clearTimeout(retry.timer);
}
surfaceRetryRef.current.delete(routeId);
}, [viewerRef]);
const scheduleSurfaceCompute = useCallback((routeId: string) => {
const Cesium = getCesium();
if (!Cesium) return;
const cur = routesRef.current.find((r) => r.routeId === routeId);
if (!cur?.visible || !cur?.waypoints || cur.waypoints.length < 2) return;
const key = buildWaypointsKey(cur.waypoints);
const cached = surfaceCacheRef.current.get(routeId);
if (cached?.key === key && Array.isArray(cached.polyline) && cached.polyline.length >= 2) return;
const retryState = surfaceRetryRef.current.get(routeId);
if (retryState?.key === key && retryState?.timer) return;
const nextAttempt = (retryState?.key === key ? retryState.attempt : 0) + 1;
const next = { key, attempt: nextAttempt, timer: null as any };
surfaceRetryRef.current.set(routeId, next);
const MAX_RETRY = 6;
if (nextAttempt > MAX_RETRY) return;
next.timer = setTimeout(async () => {
const state = surfaceRetryRef.current.get(routeId);
if (state && state.key === key) {
state.timer = null;
}
const viewer = viewerRef?.current;
const Cesium2 = getCesium();
if (!viewer || viewer.isDestroyed?.() || !Cesium2) return;
const cur2 = routesRef.current.find((r) => r.routeId === routeId);
if (!cur2?.visible || !cur2?.waypoints || cur2.waypoints.length < 2) return;
const key2 = buildWaypointsKey(cur2.waypoints);
if (key2 !== key) return;
// 每次尝试前先触发一次渲染,让瓦片/深度尽量就绪
try {
viewer.scene?.requestRender?.();
} catch {
// 忽略
}
const seq = (surfaceComputeSeqRef.current.get(routeId) || 0) + 1;
surfaceComputeSeqRef.current.set(routeId, seq);
const cartos = densifyWaypoints(Cesium2, cur2.waypoints);
const densified = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300));
const clampedLine = await clampPositionsToModelSurface(Cesium2, densified);
const wpAbove = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300));
const clampedWp = await clampWaypointsToModelSurface(Cesium2, wpAbove);
if ((surfaceComputeSeqRef.current.get(routeId) || 0) !== seq) return;
if (!clampedLine || clampedLine.length < 2) {
scheduleSurfaceCompute(routeId);
return;
}
surfaceCacheRef.current.set(routeId, {
key,
polyline: clampedLine,
start: clampedLine[0],
end: clampedLine[clampedLine.length - 1],
waypointPositions: Array.isArray(clampedWp) ? clampedWp : undefined,
});
// 触发一次增量更新(避免等下一轮effect)
try {
const pathId = `library-route-${routeId}-path`;
const startId = `library-route-${routeId}-start`;
const endId = `library-route-${routeId}-end`;
const path = viewer.entities.getById?.(pathId);
if (path?.polyline) {
path.polyline.positions = clampedLine;
path.polyline.clampToGround = false;
if (Cesium2?.ArcType) path.polyline.arcType = Cesium2.ArcType.NONE;
}
const start = viewer.entities.getById?.(startId);
if (start) start.position = clampedLine[0];
const end = viewer.entities.getById?.(endId);
if (end) end.position = clampedLine[clampedLine.length - 1];
if (Array.isArray(clampedWp)) {
const total = cur2.waypoints.length;
const maxPoints = 80;
const step = Math.max(1, Math.ceil(total / maxPoints));
for (let i = 0; i < total; i += step) {
const wpId = `library-route-${routeId}-wp-${i}`;
const wpEntity = viewer.entities.getById?.(wpId);
if (wpEntity) wpEntity.position = clampedWp[i];
}
}
viewer.scene?.requestRender?.();
} catch {
// 忽略
}
}, 240 + nextAttempt * 360);
}, [
viewerRef,
getCesium,
buildWaypointsKey,
densifyWaypoints,
clampPositionsToModelSurface,
clampWaypointsToModelSurface,
]);
const upsertRouteEntities = useCallback((item: RouteLibraryRenderItem) => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!item.visible) return;
if (!item.waypoints || item.waypoints.length < 2) return;
const routeId = item.routeId;
const routeName = item.routeName || '未命名航线';
const waypointsKey = buildWaypointsKey(item.waypoints);
const prevIds = entityIdsByRouteRef.current.get(routeId) || [];
const baseColorCss = colorFromRouteId(routeId);
const baseColor = Cesium.Color.fromCssColorString(baseColorCss).withAlpha(item.highlighted ? 0.98 : 0.80);
const pathId = `library-route-${routeId}-path`;
const startId = `library-route-${routeId}-start`;
const endId = `library-route-${routeId}-end`;
const ids: string[] = [pathId, startId, endId];
// path
try {
const existing = viewer.entities.getById?.(pathId);
const material = item.highlighted
? new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.35,
color: baseColor,
})
: baseColor;
const depthFailMaterial = item.highlighted ? baseColor.withAlpha(0.55) : baseColor.withAlpha(0.55);
const cached = surfaceCacheRef.current.get(routeId);
const cachedPositions = cached && cached.key === waypointsKey ? cached.polyline : null;
const fallbackPositions = item.waypoints.map((wp) => Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0));
const positionsToUse = Array.isArray(cachedPositions) && cachedPositions.length >= 2 ? cachedPositions : fallbackPositions;
const useClampToGround = !(Array.isArray(cachedPositions) && cachedPositions.length >= 2);
if (existing?.polyline) {
existing.polyline.positions = positionsToUse;
existing.polyline.width = item.highlighted ? 7 : 3;
existing.polyline.material = material;
existing.polyline.depthFailMaterial = depthFailMaterial;
existing.polyline.clampToGround = useClampToGround;
if (!useClampToGround && Cesium?.ArcType) {
existing.polyline.arcType = Cesium.ArcType.NONE;
}
existing.show = true;
} else {
viewer.entities.add({
id: pathId,
name: `已规划航线:${routeName}`,
polyline: {
positions: positionsToUse,
width: item.highlighted ? 7 : 3,
material,
depthFailMaterial,
clampToGround: useClampToGround,
arcType: !useClampToGround && Cesium?.ArcType ? Cesium.ArcType.NONE : undefined,
},
properties: {
type: 'route-library-path',
routeId,
},
});
}
} catch (e) {
console.error('渲染已规划航线失败:', e);
}
// start / end
const start = item.waypoints[0];
const end = item.waypoints[item.waypoints.length - 1];
const upsertPoint = (id: string, lon: number, lat: number, labelText: string, color: any) => {
try {
const existing = viewer.entities.getById?.(id);
const cached = surfaceCacheRef.current.get(routeId);
const positionFromCache = cached && cached.key === waypointsKey
? (id === startId ? cached.start : cached.end)
: null;
const position = positionFromCache || Cesium.Cartesian3.fromDegrees(lon, lat, 0);
if (existing) {
existing.position = position;
existing.show = true;
if (existing.point) {
existing.point.pixelSize = item.highlighted ? 12 : 10;
existing.point.color = color;
existing.point.outlineColor = Cesium.Color.WHITE.withAlpha(0.9);
existing.point.outlineWidth = 2;
}
return;
}
viewer.entities.add({
id,
position,
point: {
pixelSize: item.highlighted ? 12 : 10,
color,
outlineColor: Cesium.Color.WHITE.withAlpha(0.9),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: labelText,
font: '12px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -18),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
type: 'route-library-point',
routeId,
},
});
} catch {
// 忽略
}
};
upsertPoint(startId, start.longitude, start.latitude, '起', Cesium.Color.LIME.withAlpha(0.95));
upsertPoint(endId, end.longitude, end.latitude, '终', Cesium.Color.RED.withAlpha(0.95));
// 渲染航点(做抽样,避免过重)
try {
const maxPoints = 80;
const total = item.waypoints.length;
const step = Math.max(1, Math.ceil(total / maxPoints));
const cached = surfaceCacheRef.current.get(routeId);
const cachedWp = cached && cached.key === waypointsKey ? cached.waypointPositions : null;
for (let i = 0; i < total; i += step) {
const wp = item.waypoints[i];
const wpId = `library-route-${routeId}-wp-${i}`;
ids.push(wpId);
const existing = viewer.entities.getById?.(wpId);
const posFromCache = Array.isArray(cachedWp) ? cachedWp[i] : null;
const pos = posFromCache || Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0);
if (existing) {
existing.position = pos;
existing.show = true;
continue;
}
viewer.entities.add({
id: wpId,
position: pos,
point: {
pixelSize: item.highlighted ? 9 : 5,
color: Cesium.Color.fromCssColorString(baseColorCss).withAlpha(item.highlighted ? 0.95 : 0.75),
outlineColor: Cesium.Color.WHITE.withAlpha(0.85),
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
type: 'route-library-waypoint',
routeId,
index: i,
},
});
}
} catch {
// 忽略
}
// 清理本次未覆盖的旧ID(主要是航点抽样步长变化时)
try {
const nextSet = new Set(ids);
prevIds.forEach((oldId) => {
if (nextSet.has(oldId)) return;
try {
viewer.entities.removeById(oldId);
} catch {
// 忽略
}
});
} catch {
// 忽略
}
entityIdsByRouteRef.current.set(routeId, ids);
// 贴模型:失败则自动重试(瓦片未就绪/不在视野时容易失败)
scheduleSurfaceCompute(routeId);
requestRender();
}, [
viewerRef,
getCesium,
buildWaypointsKey,
colorFromRouteId,
scheduleSurfaceCompute,
requestRender,
]);
const visibleRoutes = useMemo(() => {
return routes.filter((r) => r.visible && r.waypoints && r.waypoints.length >= 2);
}, [routes]);
// 同步渲染:增量更新 + 移除未显示的航线
useEffect(() => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return;
const nextVisibleIds = new Set(visibleRoutes.map((r) => r.routeId));
for (const routeId of Array.from(entityIdsByRouteRef.current.keys())) {
if (!nextVisibleIds.has(routeId)) {
removeRouteEntities(routeId);
}
}
for (const item of visibleRoutes) {
upsertRouteEntities(item);
}
}, [viewerRef, visibleRoutes, removeRouteEntities, upsertRouteEntities]);
// 卸载清理
useEffect(() => {
return () => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return;
for (const routeId of Array.from(entityIdsByRouteRef.current.keys())) {
removeRouteEntities(routeId);
}
entityIdsByRouteRef.current.clear();
surfaceCacheRef.current.clear();
surfaceComputeSeqRef.current.clear();
surfaceRetryRef.current.forEach((s) => {
if (s?.timer) clearTimeout(s.timer);
});
surfaceRetryRef.current.clear();
requestRender();
};
}, [viewerRef, removeRouteEntities, requestRender]);
const flyToRoute = useCallback((routeId: string) => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
const item = routes.find((r) => r.routeId === routeId);
if (!item?.waypoints || item.waypoints.length === 0) return;
const bounds = calculateBounds(item.waypoints);
try {
try {
if (Cesium?.Matrix4) {
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
} catch {
// 忽略
}
try {
viewer.camera.cancelFlight?.();
} catch {
// 忽略
}
if (![bounds.west, bounds.south, bounds.east, bounds.north].every((v) => Number.isFinite(v))) {
return;
}
viewer.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(bounds.west, bounds.south, bounds.east, bounds.north),
duration: 1.0,
});
} catch {
// 忽略
}
}, [viewerRef, routes, getCesium, calculateBounds]);
return {
flyToRoute,
};
}
@@ -83,13 +83,17 @@ export const useRouteDrawing = (options: UseRouteDrawingOptions = {}): UseRouteD
return;
}
const defaultSpeed = point.speed != null ? Number(point.speed) : undefined;
const newWaypoint: BoatWaypointDTO = {
longitude: point.longitude,
latitude: point.latitude,
pointName: `航点${waypoints.length + 1}`,
speed: Number.isFinite(defaultSpeed as any) ? (defaultSpeed as number) : undefined,
turnMode: 'smooth',
isKeyPoint: false,
};
// 保存拾取高度(仅用于前端渲染点线对齐,不参与后端DTO)
(newWaypoint as any).altitude = point.altitude;
const newWaypoints = [...waypoints, newWaypoint];
setWaypointsState(newWaypoints);
@@ -135,7 +139,16 @@ export const useRouteDrawing = (options: UseRouteDrawingOptions = {}): UseRouteD
setEditorState(prev => ({
...prev,
hasUnsavedChanges: true,
selectedWaypointIndex: prev.selectedWaypointIndex === index ? null : prev.selectedWaypointIndex,
selectedWaypointIndex: (() => {
const selected = prev.selectedWaypointIndex;
if (selected === null) return null;
if (selected === index) {
if (newWaypoints.length === 0) return null;
return Math.min(index, newWaypoints.length - 1);
}
if (selected > index) return selected - 1;
return selected;
})(),
}));
}, [waypoints, pushHistory]);
@@ -149,6 +162,7 @@ export const useRouteDrawing = (options: UseRouteDrawingOptions = {}): UseRouteD
longitude: point.longitude,
latitude: point.latitude,
};
(newWaypoints[index] as any).altitude = point.altitude;
setWaypointsState(newWaypoints);
pushHistory(newWaypoints);
@@ -61,24 +61,26 @@ export const useRouteValidation = (options: UseRouteValidationOptions): UseRoute
};
const response = await validateBoatRoute(dto, boundaryId);
if (response.resp_code === 0 && response.datas) {
setValidationResult(response.datas);
const result = (response as any)?.datas ?? (response as any)?.data;
if (response.resp_code === 0 && result) {
setValidationResult(result);
if (!response.datas.valid) {
message.error(`航线校验失败: ${response.datas.errors.join(', ')}`);
if (!result.valid) {
const errText = Array.isArray(result.errors) && result.errors.length > 0 ? result.errors.join(', ') : '未知原因';
message.error(`航线校验失败: ${errText}`);
return false;
}
if (response.datas.warnings.length > 0) {
message.warning(`校验通过,但有警告: ${response.datas.warnings.join(', ')}`);
if (Array.isArray(result.warnings) && result.warnings.length > 0) {
message.warning(`校验通过,但有警告: ${result.warnings.join(', ')}`);
} else {
message.success('航线校验通过');
}
// 更新预览信息
setPreviewInfo({
totalDistance: response.datas.totalDistance,
estimatedDuration: response.datas.estimatedDuration,
totalDistance: Number(result.totalDistance) || 0,
estimatedDuration: Number(result.estimatedDuration) || 0,
});
return true;
@@ -1,41 +1,782 @@
.toolbar {
display: flex;
align-items: center;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.95);
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
flex-wrap: wrap;
gap: 8px;
padding: 10px 12px;
background: rgba(10, 20, 30, 0.82);
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45);
border: 1px solid rgba(0, 240, 255, 0.18);
backdrop-filter: blur(10px);
width: 100%;
box-sizing: border-box;
:global {
.ant-btn {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.10);
color: rgba(255, 255, 255, 0.88);
border-radius: 10px;
&:hover {
color: #00f0ff;
border-color: rgba(0, 240, 255, 0.45);
background: rgba(0, 240, 255, 0.10);
}
}
.ant-btn-primary {
background: linear-gradient(135deg, rgba(0, 240, 255, 0.95), rgba(0, 153, 255, 0.85));
border: none;
color: #001019;
&:hover {
background: linear-gradient(135deg, rgba(0, 240, 255, 1), rgba(0, 153, 255, 0.95));
color: #001019;
}
}
.ant-btn-dangerous {
background: rgba(255, 77, 79, 0.12);
border-color: rgba(255, 77, 79, 0.35);
color: rgba(255, 255, 255, 0.9);
&:hover {
background: rgba(255, 77, 79, 0.18);
border-color: rgba(255, 77, 79, 0.6);
}
}
}
}
.divider {
width: 1px;
height: 24px;
background: #e8e8e8;
margin: 0 8px;
.toolbarGroup {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.toolbarActions {
flex-basis: 100%;
margin-left: 0;
justify-content: flex-start;
padding-top: 8px;
border-top: 1px solid rgba(255, 255, 255, 0.10);
:global {
.ant-btn {
height: 34px;
border-radius: 12px;
padding: 0 14px;
}
}
}
.preview {
width: 280px;
max-height: 400px;
overflow-y: auto;
width: 100%;
:global {
.ant-card {
background: rgba(10, 20, 30, 0.82);
border: 1px solid rgba(0, 240, 255, 0.14);
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(10px);
}
.ant-card-head {
border-bottom: 1px solid rgba(255, 255, 255, 0.10);
color: rgba(255, 255, 255, 0.9);
}
.ant-card-body {
color: rgba(255, 255, 255, 0.82);
}
.ant-descriptions-item-label {
color: rgba(255, 255, 255, 0.55);
}
.ant-descriptions-item-content {
color: rgba(255, 255, 255, 0.88);
}
}
}
.editor {
position: relative;
position: absolute;
inset: 0;
pointer-events: none; // 允许点击穿透到地图
z-index: 900;
> * {
pointer-events: auto;
}
}
.editorOverlay {
position: absolute;
top: 12px;
left: 12px;
z-index: 100;
top: 0;
left: 0;
z-index: 901;
}
.editorSidebar {
.leftPanel {
width: clamp(360px, 30vw, 480px);
max-height: calc(100vh - 120px);
overflow: hidden;
border-radius: 16px;
background: linear-gradient(180deg, rgba(12, 24, 40, 0.92), rgba(7, 10, 16, 0.78));
border: 1px solid rgba(0, 240, 255, 0.18);
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
backdrop-filter: blur(14px);
position: relative;
&::before {
content: '';
position: absolute;
inset: -1px;
border-radius: 16px;
padding: 1px;
background: linear-gradient(135deg, rgba(0, 240, 255, 0.55), rgba(99, 102, 241, 0.25), rgba(0, 240, 255, 0.18));
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
opacity: 0.65;
}
&::after {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 20% 10%, rgba(0, 240, 255, 0.10), transparent 45%),
radial-gradient(circle at 80% 30%, rgba(99, 102, 241, 0.12), transparent 55%),
linear-gradient(rgba(255, 255, 255, 0.04) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
background-size: auto, auto, 24px 24px, 24px 24px;
opacity: 0.75;
}
:global {
.ant-tabs-nav {
margin: 0;
padding: 0 12px;
}
.ant-tabs-tab {
color: rgba(255, 255, 255, 0.7);
}
.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: rgba(0, 240, 255, 0.95);
text-shadow: 0 0 18px rgba(0, 240, 255, 0.35);
}
.ant-tabs-ink-bar {
background: linear-gradient(90deg, rgba(0, 240, 255, 1), rgba(99, 102, 241, 0.9));
box-shadow: 0 0 16px rgba(0, 240, 255, 0.35);
}
.ant-input,
.ant-input-affix-wrapper {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.12);
color: rgba(255, 255, 255, 0.88);
border-radius: 12px;
}
.ant-input::placeholder {
color: rgba(255, 255, 255, 0.45);
}
}
}
.collapsedTrigger {
position: absolute;
top: 12px;
right: 12px;
z-index: 100;
top: 0;
left: 0;
z-index: 901;
pointer-events: auto;
:global {
.ant-btn {
background: rgba(10, 20, 40, 0.92);
border-color: rgba(0, 240, 255, 0.18);
color: rgba(255, 255, 255, 0.9);
border-radius: 999px;
height: 36px;
padding: 0 14px;
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.45);
backdrop-filter: blur(12px);
}
.ant-btn:hover {
background: rgba(0, 240, 255, 0.12);
border-color: rgba(0, 240, 255, 0.45);
color: rgba(0, 240, 255, 0.95);
}
}
}
.panelHeader {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 12px 8px 12px;
cursor: move;
user-select: none;
touch-action: none;
}
.panelHeader :global(.ant-btn) {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.10);
color: rgba(255, 255, 255, 0.88);
border-radius: 12px;
}
.panelHeader :global(.ant-btn:hover) {
color: rgba(0, 240, 255, 0.95);
border-color: rgba(0, 240, 255, 0.35);
background: rgba(0, 240, 255, 0.10);
}
.panelTitle {
display: flex;
align-items: baseline;
gap: 10px;
color: rgba(255, 255, 255, 0.92);
font-weight: 700;
letter-spacing: 0.3px;
}
.panelSubTitle {
font-size: 12px;
padding: 2px 10px;
border-radius: 999px;
border: 1px solid rgba(0, 240, 255, 0.18);
background: rgba(0, 240, 255, 0.08);
color: rgba(0, 240, 255, 0.9);
}
.panelBody {
padding: 10px 12px 12px 12px;
overflow: auto;
max-height: calc(100vh - 190px);
}
.editBody {
padding-bottom: 12px;
}
.toolbarSticky {
position: sticky;
top: 10px;
z-index: 3;
margin-top: 10px;
}
.waypointPreview {
margin-top: 8px;
padding: 10px 10px;
border-radius: 14px;
background: rgba(0, 0, 0, 0.26);
border: 1px solid rgba(255, 255, 255, 0.10);
}
.waypointPreviewHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
font-size: 12px;
color: rgba(255, 255, 255, 0.78);
}
.waypointPreviewHint {
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
white-space: nowrap;
}
.routeOverviewRow {
margin-top: 8px;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
}
.routeOverviewActions {
margin-top: 10px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.routeOverviewItem {
padding: 8px 10px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.10);
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
min-width: 0;
}
.routeOverviewLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.6);
white-space: nowrap;
}
.routeOverviewValue {
font-size: 12px;
font-weight: 700;
color: rgba(255, 255, 255, 0.9);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.waypointPreviewHeader2 {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid rgba(255, 255, 255, 0.10);
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
font-size: 12px;
color: rgba(255, 255, 255, 0.78);
}
.waypointPreviewHint2 {
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
white-space: nowrap;
}
.waypointPreviewList {
margin-top: 8px;
max-height: clamp(160px, 22vh, 260px);
overflow: auto;
display: flex;
flex-direction: column;
gap: 6px;
padding-right: 2px;
}
.waypointEmpty {
padding: 10px 10px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.04);
border: 1px dashed rgba(255, 255, 255, 0.18);
color: rgba(255, 255, 255, 0.65);
font-size: 12px;
text-align: center;
}
.waypointChip {
width: 100%;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.10);
background: rgba(255, 255, 255, 0.05);
color: rgba(255, 255, 255, 0.9);
cursor: pointer;
text-align: left;
outline: none;
appearance: none;
}
.waypointChip:hover {
background: rgba(0, 240, 255, 0.06);
border-color: rgba(0, 240, 255, 0.22);
}
.waypointChipActive {
border-color: rgba(0, 240, 255, 0.45);
box-shadow: 0 0 0 3px rgba(0, 240, 255, 0.08);
}
.waypointChipIndex {
width: 22px;
height: 22px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
font-weight: 800;
color: rgba(0, 0, 0, 0.75);
flex: 0 0 auto;
}
.waypointChipName {
max-width: 120px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 600;
color: rgba(255, 255, 255, 0.92);
}
.waypointChipTag {
padding: 2px 8px;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(255, 255, 255, 0.06);
color: rgba(255, 255, 255, 0.78);
font-size: 11px;
flex: 0 0 auto;
}
.waypointChipCoord {
margin-left: auto;
font-size: 11px;
color: rgba(255, 255, 255, 0.55);
font-variant-numeric: tabular-nums;
}
.waypointInline {
margin-top: 10px;
padding: 12px 12px;
border-radius: 16px;
background: rgba(0, 0, 0, 0.24);
border: 1px solid rgba(255, 255, 255, 0.10);
max-height: 360px;
overflow: auto;
}
.waypointInlineHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding-bottom: 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.10);
}
.waypointInlineTitle {
font-weight: 700;
color: rgba(255, 255, 255, 0.92);
letter-spacing: 0.2px;
}
.waypointInlineMeta {
margin-top: 10px;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.waypointInlineMetaItem {
padding: 8px 10px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.10);
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.waypointInlineMetaLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.6);
}
.waypointInlineMetaValue {
font-size: 12px;
color: rgba(255, 255, 255, 0.9);
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.waypointInlineGrid {
margin-top: 12px;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
:global {
.ant-form-item {
margin-bottom: 0;
}
}
}
.waypointInlineSpan2 {
grid-column: 1 / 3;
}
.waypointInlineCollapse {
margin-top: 12px;
:global {
.ant-collapse {
background: transparent;
}
.ant-collapse-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.10);
}
.ant-collapse-header {
padding: 10px 0;
color: rgba(255, 255, 255, 0.86);
}
.ant-collapse-content {
background: transparent;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.ant-collapse-content-box {
padding: 10px 0 0 0;
}
}
}
.waypointActions {
display: flex;
flex-direction: column;
gap: 8px;
}
.waypointActionRow {
display: flex;
align-items: center;
gap: 8px;
}
.statsRow {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 10px 10px;
border-radius: 14px;
background: rgba(0, 0, 0, 0.22);
border: 1px solid rgba(255, 255, 255, 0.10);
margin-bottom: 10px;
:global {
.ant-tag {
border-radius: 999px;
border-color: rgba(255, 255, 255, 0.12);
background: rgba(255, 255, 255, 0.06);
color: rgba(255, 255, 255, 0.86);
}
}
}
.statsLeft {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.statsRight {
flex: 0 0 auto;
:global {
.ant-btn {
border-radius: 12px;
}
.ant-input-number {
border-radius: 12px;
}
}
}
.speedField {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 10px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.12);
}
.speedLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.7);
white-space: nowrap;
}
.speedUnit {
font-size: 12px;
color: rgba(255, 255, 255, 0.55);
white-space: nowrap;
}
.panelDivider {
margin: 10px 0 12px 0;
border-color: rgba(255, 255, 255, 0.12);
}
.boundaryRow {
display: grid;
grid-template-columns: 70px 1fr;
grid-template-rows: auto auto;
column-gap: 10px;
row-gap: 8px;
padding: 10px 10px;
border-radius: 14px;
background: rgba(0, 0, 0, 0.25);
border: 1px solid rgba(255, 255, 255, 0.10);
margin-bottom: 10px;
}
.boundaryLabel {
grid-column: 1 / 2;
grid-row: 1 / 2;
align-self: center;
color: rgba(255, 255, 255, 0.78);
font-size: 12px;
white-space: nowrap;
}
.boundarySelect {
grid-column: 2 / 3;
grid-row: 1 / 2;
:global {
.ant-select-selector {
background: rgba(255, 255, 255, 0.06) !important;
border-color: rgba(255, 255, 255, 0.12) !important;
border-radius: 12px !important;
color: rgba(255, 255, 255, 0.88);
}
.ant-select-arrow {
color: rgba(255, 255, 255, 0.55);
}
}
}
.boundaryMeta {
grid-column: 2 / 3;
grid-row: 2 / 3;
color: rgba(255, 255, 255, 0.6);
font-size: 12px;
}
.libraryActions {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
}
.libraryTopRow {
display: grid;
grid-template-columns: 1fr 110px;
gap: 10px;
align-items: center;
}
.libraryFilter {
:global {
.ant-select-selector {
background: rgba(255, 255, 255, 0.06) !important;
border-color: rgba(255, 255, 255, 0.12) !important;
border-radius: 12px !important;
color: rgba(255, 255, 255, 0.88);
}
.ant-select-arrow {
color: rgba(255, 255, 255, 0.55);
}
}
}
.libraryButtons {
display: flex;
gap: 8px;
justify-content: flex-end;
align-items: center;
}
.visibleCountTag {
margin-inline-start: auto;
border-radius: 999px;
background: rgba(0, 240, 255, 0.08);
border: 1px solid rgba(0, 240, 255, 0.14);
color: rgba(0, 240, 255, 0.9);
}
.centerHint {
padding: 18px 0;
text-align: center;
color: rgba(255, 255, 255, 0.6);
font-size: 12px;
}
.routeList {
max-height: calc(100vh - 260px);
overflow: auto;
:global {
.ant-list-item {
border-block-end: 1px solid rgba(255, 255, 255, 0.08);
padding: 10px 8px;
}
.ant-list-item-action {
margin-inline-start: 8px;
}
.ant-list-item-action > li {
padding: 0 2px;
}
.ant-list-item-meta-title {
margin-bottom: 2px;
}
.ant-list-item-meta-description {
color: rgba(255, 255, 255, 0.6);
}
}
}
.routeItem {
border-radius: 12px;
transition: background 0.18s ease, border-color 0.18s ease;
cursor: pointer;
&:hover {
background: rgba(0, 240, 255, 0.06);
}
}
.routeItemSelected {
background: rgba(99, 102, 241, 0.10);
border: 1px solid rgba(99, 102, 241, 0.25);
}
.routeTitleRow {
display: flex;
align-items: center;
gap: 8px;
}
.routeColorDot {
width: 10px;
height: 10px;
border-radius: 50%;
box-shadow: 0 0 12px rgba(0, 240, 255, 0.25);
border: 1px solid rgba(255, 255, 255, 0.35);
flex: 0 0 auto;
}
.routeName {
color: rgba(255, 255, 255, 0.92);
font-weight: 600;
}
.routeMeta {
display: flex;
flex-wrap: wrap;
gap: 10px;
font-size: 12px;
color: rgba(255, 255, 255, 0.62);
}
.saveModal {
@@ -46,6 +787,21 @@
}
}
.loadingToast {
position: absolute;
top: 12px;
left: 50%;
transform: translateX(-50%);
z-index: 902;
padding: 8px 12px;
border-radius: 999px;
background: rgba(0, 0, 0, 0.35);
border: 1px solid rgba(0, 240, 255, 0.18);
color: rgba(255, 255, 255, 0.86);
backdrop-filter: blur(10px);
pointer-events: none;
}
.waypointMarker {
width: 24px;
height: 24px;
@@ -93,9 +849,11 @@
.tip {
padding: 8px 12px;
background: rgba(0, 0, 0, 0.7);
color: #fff;
border-radius: 4px;
background: rgba(0, 0, 0, 0.38);
color: rgba(255, 255, 255, 0.88);
border-radius: 12px;
font-size: 12px;
margin-top: 8px;
border: 1px solid rgba(255, 255, 255, 0.12);
backdrop-filter: blur(10px);
}
File diff suppressed because it is too large Load Diff
@@ -22,6 +22,8 @@ export interface MapClickEvent {
longitude: number;
latitude: number;
altitude?: number;
/** 默认航点速度(可选,用于新增航点时回填) */
speed?: number;
}
/** 航点编辑表单值 */
@@ -60,6 +62,7 @@ export interface RouteToolbarProps {
mode: EditorMode;
hasWaypoints: boolean;
hasUnsavedChanges: boolean;
canUndo?: boolean;
isValidating: boolean;
isPreviewing?: boolean;
onModeChange: (mode: EditorMode) => void;
+13
View File
@@ -136,6 +136,19 @@ export async function publishBoatRoute(routeId: string) {
});
}
/**
* 按设备批量更新“模型中显示航线”状态:未包含的航线会被置为不显示
*/
export async function updateBoatRouteShowInModelByDeviceSn(deviceSn: string, routeIds: string[]) {
return request<API.Result<void>>(
`${API_PREFIX}/device/boat/route/display/device/${encodeURIComponent(deviceSn)}`,
{
method: 'PUT',
data: { routeIds: Array.isArray(routeIds) ? routeIds : [] },
},
);
}
/**
* 计算航线预览信息 (前端本地计算)
*/
+42 -20
View File
@@ -6,7 +6,6 @@
import { request } from 'umi';
import type {
WaterBoundaryCreateDTO,
WaterBoundaryUpdateDTO,
WaterBoundaryVO,
} from '@/pages/map3d/components/BoundaryEditor/types';
@@ -22,16 +21,6 @@ export async function createWaterBoundary(data: WaterBoundaryCreateDTO) {
});
}
/**
* 更新水域边界
*/
export async function updateWaterBoundary(boundaryId: string, data: WaterBoundaryUpdateDTO) {
return request<API.Result<void>>(`${API_PREFIX}/device/water/boundary/${boundaryId}`, {
method: 'PUT',
data,
});
}
/**
* 获取水域边界详情
*/
@@ -42,10 +31,19 @@ export async function getWaterBoundaryDetail(boundaryId: string) {
}
/**
* 获取景区水域边界列表
* 获取设备水域边界列表
*/
export async function getWaterBoundariesByDeviceSn(deviceSn: string) {
return request<API.Result<WaterBoundaryVO[]>>(`${API_PREFIX}/device/water/boundary/list/device/${encodeURIComponent(deviceSn)}`, {
method: 'GET',
});
}
/**
* 获取景区水域边界列表(兼容旧接口,优先使用按设备SN查询)
*/
export async function getWaterBoundariesByScenicId(scenicId: number) {
return request<API.Result<WaterBoundaryVO[]>>(`${API_PREFIX}/device/water/boundary/list/scenic/${scenicId}`, {
return request<API.Result<WaterBoundaryVO[]>>(`${API_PREFIX}/device/water/boundary/list/${scenicId}`, {
method: 'GET',
});
}
@@ -59,6 +57,29 @@ export async function deleteWaterBoundary(boundaryId: string) {
});
}
/**
* 更新边界状态
*/
export async function updateWaterBoundaryStatus(boundaryId: string, status: 0 | 1) {
return request<API.Result<void>>(`${API_PREFIX}/device/water/boundary/${boundaryId}/status`, {
method: 'PUT',
params: { status },
});
}
/**
* 按设备批量更新“模型中显示标绘”状态:未包含的边界会被置为不显示
*/
export async function updateWaterBoundaryShowInModelByDeviceSn(deviceSn: string, boundaryIds: string[]) {
return request<API.Result<void>>(
`${API_PREFIX}/device/water/boundary/display/device/${encodeURIComponent(deviceSn)}`,
{
method: 'PUT',
data: { boundaryIds: Array.isArray(boundaryIds) ? boundaryIds : [] },
},
);
}
/**
* 检测点是否在边界内
*/
@@ -66,9 +87,9 @@ export async function checkPointInBoundary(
boundaryId: string,
point: { longitude: number; latitude: number }
) {
return request<API.Result<boolean>>(`${API_PREFIX}/device/water/boundary/${boundaryId}/check/point`, {
method: 'POST',
data: point,
return request<API.Result<boolean>>(`${API_PREFIX}/device/water/boundary/check/point`, {
method: 'GET',
params: { boundaryId, longitude: point.longitude, latitude: point.latitude },
});
}
@@ -80,10 +101,11 @@ export async function checkRouteInBoundary(
waypoints: Array<{ longitude: number; latitude: number }>
) {
return request<API.Result<{
allInside: boolean;
outsidePoints: number[];
}>>(`${API_PREFIX}/device/water/boundary/${boundaryId}/check/route`, {
allInBoundary: boolean;
outOfBoundarySegments: string[];
}>>(`${API_PREFIX}/device/water/boundary/check/route`, {
method: 'POST',
data: { waypoints },
params: { boundaryId },
data: waypoints,
});
}
+12
View File
@@ -84,6 +84,10 @@ export interface BoatRouteCreateDTO {
loopCount?: number; // 循环次数
returnMode?: ReturnMode;
safeDistance?: number; // 安全距离 (米)
/** 规划水域边界ID(可选) */
boundaryId?: string;
/** 是否在模型中显示航线:0-否,1-是(可选,默认0) */
showInModel?: 0 | 1;
waypoints: BoatWaypointDTO[];
remark?: string;
}
@@ -96,6 +100,10 @@ export interface BoatRouteUpdateDTO {
loopCount?: number;
returnMode?: ReturnMode;
safeDistance?: number;
/** 规划水域边界ID(可选) */
boundaryId?: string;
/** 是否在模型中显示航线:0-否,1-是(可选) */
showInModel?: 0 | 1;
waypoints?: BoatWaypointDTO[];
remark?: string;
}
@@ -114,6 +122,10 @@ export interface BoatRouteListVO {
totalDuration: number; // 预计时长 (秒)
totalDurationStr: string;
isTemplate: boolean;
/** 是否在模型中显示航线:0-否,1-是 */
showInModel?: 0 | 1;
/** 规划水域边界ID */
boundaryId?: string;
createTime: string;
updateTime: string;
}
+1
View File
@@ -0,0 +1 @@
test