diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java index 9a07d24d..0faa381d 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/BoatRouteController.java @@ -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 updateShowInModelByDeviceSn( + @Parameter(description = "设备SN") @PathVariable String deviceSn, + @RequestBody @Validated BoatRouteDisplayUpdateDTO dto) { + boatRouteService.updateShowInModelByDeviceSn(deviceSn, dto.getRouteIds()); + return Result.succeed(null, "航线模型显示状态更新成功"); + } } diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/WaterBoundaryController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/WaterBoundaryController.java index cb5468ba..1ba7e0f6 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/WaterBoundaryController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/WaterBoundaryController.java @@ -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 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> listByDeviceSn( + @Parameter(description = "设备SN") @PathVariable String deviceSn) { + List list = waterBoundaryService.listByDeviceSn(deviceSn); + return Result.succeed(list); + } + @Operation(summary = "检测点是否在边界内") @GetMapping("/check/point") public Result checkPoint( @@ -107,4 +119,13 @@ public class WaterBoundaryController { waterBoundaryService.deleteBoundary(boundaryId); return Result.succeed(null, "删除成功"); } + + @Operation(summary = "按设备批量更新标绘显示状态") + @PutMapping("/display/device/{deviceSn}") + public Result updateShowInModelByDeviceSn( + @Parameter(description = "设备SN") @PathVariable String deviceSn, + @RequestBody @Validated WaterBoundaryDisplayUpdateDTO dto) { + waterBoundaryService.updateShowInModelByDeviceSn(deviceSn, dto.getBoundaryIds()); + return Result.succeed(null, "标绘显示状态更新成功"); + } } diff --git a/zlt-business/device-center/src/main/java/com/central/device/entity/BoatRoute.java b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatRoute.java index 20cdb37d..cb219632 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/entity/BoatRoute.java +++ b/zlt-business/device-center/src/main/java/com/central/device/entity/BoatRoute.java @@ -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; + /** * 备注 */ diff --git a/zlt-business/device-center/src/main/java/com/central/device/entity/WaterBoundary.java b/zlt-business/device-center/src/main/java/com/central/device/entity/WaterBoundary.java index 35844291..8c9cc017 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/entity/WaterBoundary.java +++ b/zlt-business/device-center/src/main/java/com/central/device/entity/WaterBoundary.java @@ -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; + // ========== 状态 ========== /** diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatRouteMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatRouteMapper.java index de04dd64..0b9e5a23 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatRouteMapper.java +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/BoatRouteMapper.java @@ -101,4 +101,25 @@ public interface BoatRouteMapper extends BaseMapper { * @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 routeIds); } diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/WaterBoundaryMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/WaterBoundaryMapper.java index 5a549402..2c0db20e 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/mapper/WaterBoundaryMapper.java +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/WaterBoundaryMapper.java @@ -24,6 +24,15 @@ public interface WaterBoundaryMapper extends BaseMapper { */ WaterBoundary selectByBoundaryId(@Param("boundaryId") String boundaryId); + /** + * 根据设备SN查询边界列表 + * + * @param deviceSn 设备SN + * @param tenantId 租户ID + * @return 边界列表 + */ + List selectByDeviceSn(@Param("deviceSn") String deviceSn, @Param("tenantId") String tenantId); + /** * 根据景区ID查询边界列表 * @@ -54,6 +63,27 @@ public interface WaterBoundaryMapper extends BaseMapper { */ 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 boundaryIds); + /** * 根据3D模型ID查询关联边界 * diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteCreateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteCreateDTO.java index ef86e8a2..f51b1ee3 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteCreateDTO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteCreateDTO.java @@ -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 waypoints; diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteDisplayUpdateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteDisplayUpdateDTO.java new file mode 100644 index 00000000..c75b2c5b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteDisplayUpdateDTO.java @@ -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 routeIds; +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteUpdateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteUpdateDTO.java index 51d217fa..6b8662b3 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteUpdateDTO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/BoatRouteUpdateDTO.java @@ -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 waypoints; } diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryCreateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryCreateDTO.java index d84fbfee..e0b9d64b 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryCreateDTO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryCreateDTO.java @@ -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; } diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryDisplayUpdateDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryDisplayUpdateDTO.java new file mode 100644 index 00000000..f0a53a6f --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/WaterBoundaryDisplayUpdateDTO.java @@ -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 boundaryIds; +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteDetailVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteDetailVO.java index 92df4167..175575ae 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteDetailVO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteDetailVO.java @@ -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; diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteListVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteListVO.java index b0188a2b..9896be5f 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteListVO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/BoatRouteListVO.java @@ -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; } diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/WaterBoundaryVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/WaterBoundaryVO.java index 8e1c40e2..44c037bb 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/vo/WaterBoundaryVO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/WaterBoundaryVO.java @@ -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; diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java index cf67a170..1f1bb21c 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IBoatRouteService.java @@ -130,4 +130,12 @@ public interface IBoatRouteService extends IService { * @param routeId 航线ID */ void publishRoute(String routeId); + + /** + * 按设备批量更新“模型中显示航线”状态(未包含的航线会被置为不显示) + * + * @param deviceSn 设备SN + * @param routeIds 需要显示的航线ID列表 + */ + void updateShowInModelByDeviceSn(String deviceSn, List routeIds); } diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IWaterBoundaryService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IWaterBoundaryService.java index cb57a338..b863ee7d 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/IWaterBoundaryService.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IWaterBoundaryService.java @@ -33,6 +33,14 @@ public interface IWaterBoundaryService extends IService { */ WaterBoundary getByBoundaryId(String boundaryId); + /** + * 获取设备水域边界列表 + * + * @param deviceSn 设备SN + * @return 边界列表 + */ + List listByDeviceSn(String deviceSn); + /** * 获取景区水域边界列表 * @@ -83,4 +91,12 @@ public interface IWaterBoundaryService extends IService { * @param boundaryId 边界ID */ void deleteBoundary(String boundaryId); + + /** + * 按设备维度批量更新“模型中显示标绘”状态:未包含的边界会被置为不显示 + * + * @param deviceSn 设备SN + * @param boundaryIds 需要显示的边界ID列表(空列表表示全隐) + */ + void updateShowInModelByDeviceSn(String deviceSn, List boundaryIds); } diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java index 4e579096..58ac5920 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/BoatRouteServiceImpl.java @@ -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 waypoints = dto.getWaypoints(); @@ -167,6 +170,12 @@ public class BoatRouteServiceImpl extends ServiceImpl routeIds) { + String sn = StrUtil.trimToEmpty(deviceSn); + if (StrUtil.isBlank(sn)) { + throw new BusinessException("设备SN不能为空"); + } + + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List 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 listByDeviceSn(String deviceSn) { + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List 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 listByScenicId(Long scenicId) { String tenantId = LoginUserContextHolder.getCurrentTenantId(); @@ -173,6 +190,30 @@ public class WaterBoundaryServiceImpl extends ServiceImpl boundaryIds) { + String sn = StrUtil.trimToEmpty(deviceSn); + if (StrUtil.isBlank(sn)) { + throw new BusinessException("设备SN不能为空"); + } + + String tenantId = LoginUserContextHolder.getCurrentTenantId(); + List 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()); + } + // ========== 私有方法 ========== /** diff --git a/zlt-business/device-center/src/main/resources/mapper/BoatRouteMapper.xml b/zlt-business/device-center/src/main/resources/mapper/BoatRouteMapper.xml index d92f7fac..87e7a949 100644 --- a/zlt-business/device-center/src/main/resources/mapper/BoatRouteMapper.xml +++ b/zlt-business/device-center/src/main/resources/mapper/BoatRouteMapper.xml @@ -16,6 +16,7 @@ + @@ -24,6 +25,7 @@ + @@ -108,4 +110,28 @@ WHERE route_id = #{routeId} + + + UPDATE boat_route + SET show_in_model = 0, + update_time = NOW() + WHERE device_sn = #{deviceSn} + AND tenant_id = #{tenantId} + AND deleted = 0 + + + + + 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 + + #{id} + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/WaterBoundaryMapper.xml b/zlt-business/device-center/src/main/resources/mapper/WaterBoundaryMapper.xml index 5394ae1b..e84305ba 100644 --- a/zlt-business/device-center/src/main/resources/mapper/WaterBoundaryMapper.xml +++ b/zlt-business/device-center/src/main/resources/mapper/WaterBoundaryMapper.xml @@ -7,6 +7,7 @@ + @@ -15,6 +16,7 @@ + @@ -28,6 +30,16 @@ AND deleted = 0 + + + SELECT * FROM water_boundary diff --git a/zlt-business/device-center/src/main/resources/sql/boat_route_tables.sql b/zlt-business/device-center/src/main/resources/sql/boat_route_tables.sql index 924dff91..74939c0a 100644 --- a/zlt-business/device-center/src/main/resources/sql/boat_route_tables.sql +++ b/zlt-business/device-center/src/main/resources/sql/boat_route_tables.sql @@ -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`) diff --git a/zlt-business/device-center/src/main/resources/sql/water_boundary_device_sn_migration.sql b/zlt-business/device-center/src/main/resources/sql/water_boundary_device_sn_migration.sql new file mode 100644 index 00000000..2b5c307e --- /dev/null +++ b/zlt-business/device-center/src/main/resources/sql/water_boundary_device_sn_migration.sql @@ -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`); + diff --git a/zlt-business/device-center/src/main/resources/sql/water_boundary_show_in_model_migration.sql b/zlt-business/device-center/src/main/resources/sql/water_boundary_show_in_model_migration.sql new file mode 100644 index 00000000..a67d5668 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/sql/water_boundary_show_in_model_migration.sql @@ -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`); diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java index 99e61688..17246d3a 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java @@ -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 params) { + log.info("查询二维码订单统计,params: {}", params); + try { + Map 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 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 page = new Page<>(pageNum, pageSize); + QueryWrapper 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 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 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.builder() + .data(result.getRecords()) + .resp_code(0) + .count(result.getTotal()) + .build(); + } catch (Exception e) { + log.error("根据二维码ID查询订单列表异常", e); + return new PageResult(); + } + } } diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java index e130b370..48be2a6d 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java @@ -96,5 +96,12 @@ public interface IOrderService extends ISuperService { Long getUnCompleteOrderCount(String deviceSn); Order getNextQueueOrder(Long tourismId, Long currentOrderId); + + /** + * 二维码订单统计查询 + * @param params 查询参数(tenantId, includeChildren, qrcodeName, codeId, tourismId) + * @return 统计结果(tourismList: 景区列表,每个景区包含qrcodeList: 二维码统计列表) + */ + Map getQrcodeOrderStatistics(Map params); } diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java index a5403520..9be1a485 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java @@ -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 imple return baseMapper.selectOne(wrapper); } + @Override + public Map getQrcodeOrderStatistics(Map 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 tenantIds = userCenterService.getSonTenantIds(anchor); + + // 3. 统计总数(不受时间和其他筛选条件影响) + Date startOfToday = DateUtils.getStartOfDay(new Date()); + Date endOfToday = DateUtils.getEndOfDay(new Date()); + + // 3.1 统计景区总数(不受tourismId等筛选条件影响) + QueryWrapper 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 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 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 allQrcodeWrapper = new QueryWrapper<>(); + allQrcodeWrapper.in("tourism_id", allTourismIds); + allQrcodeWrapper.eq("is_del", 0); + List allCodeIds = qrCodeMapper.selectList(allQrcodeWrapper) + .stream().map(QrCode::getCodeId).collect(java.util.stream.Collectors.toList()); + log.info("二维码codeId列表: {}", allCodeIds); + + if (!allCodeIds.isEmpty()) { + // 统计所有完成订单数(状态3,不受时间限制) + QueryWrapper 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 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 filteredTourismIds = null; + if ((codeId != null && !codeId.isEmpty()) || (qrcodeName != null && !qrcodeName.isEmpty())) { + QueryWrapper 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 filteredQrCodes = qrCodeMapper.selectList(filterQrCodeWrapper); + filteredTourismIds = filteredQrCodes.stream() + .map(QrCode::getTourismId) + .collect(java.util.stream.Collectors.toSet()); + } + + // 5. 根据租户ID列表查询景区列表(带分页,用于展示) + Page tourismPage = new Page<>(page, limit); + QueryWrapper 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 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 tourismList = tourismPage.getRecords(); + + // 6. 遍历景区,查询二维码和订单统计(用于展示详细列表) + List> tourismDataList = new java.util.ArrayList<>(); + for (Tourism tourism : tourismList) { + // 查询该景区的二维码列表 + QueryWrapper 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 qrCodeList = qrCodeMapper.selectList(qrCodeWrapper); + + if (qrCodeList.isEmpty()) { + continue; // 如果该景区没有符合条件的二维码,跳过 + } + + List> qrcodeDataList = new java.util.ArrayList<>(); + long tourismOrderCount = 0; + + for (QrCode qrCode : qrCodeList) { + // 统计该二维码的订单数量(状态为3,pay_time在时间范围内) + QueryWrapper 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 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 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 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 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; + } + } diff --git a/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml b/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml index d85e9035..6479d329 100644 --- a/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml +++ b/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml @@ -38,12 +38,12 @@ AND o.mobile LIKE CONCAT('%', #{p.mobile}, '%') - + - AND o.create_time >= #{p.startTime} + AND o.pay_time >= #{p.startTime} - AND o.create_time <= #{p.endTime} + AND o.pay_time <= #{p.endTime} diff --git a/zlt-web/react-web-next/config/routes.ts b/zlt-web/react-web-next/config/routes.ts index 665f1b5c..f9f445eb 100644 --- a/zlt-web/react-web-next/config/routes.ts +++ b/zlt-web/react-web-next/config/routes.ts @@ -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' }, ], }, { diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/OrderListDrawer.tsx b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/OrderListDrawer.tsx new file mode 100644 index 00000000..cea900f7 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/OrderListDrawer.tsx @@ -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; +} + +const OrderListDrawer: React.FC = ({ open, onClose, qrcode, queryParams }) => { + const actionRef = useRef(); + + 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 = { + 1: { text: '微信支付', color: 'green' }, + 2: { text: '优惠券', color: 'blue' }, + 3: { text: '第三方', color: 'orange' }, + }; + const info = typeMap[type] || { text: '未知', color: 'default' }; + return {info.text}; + }, + }, + { + title: '订单状态', + dataIndex: 'orderStatus', + width: 120, + render: (status: number) => { + const statusMap: Record = { + 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 {info.text}; + }, + }, + { + title: '支付时间', + dataIndex: 'payTime', + width: 160, + valueType: 'dateTime', + render: (time: string) => time || '-', + }, + { + title: '创建时间', + dataIndex: 'createTime', + width: 160, + valueType: 'dateTime', + }, + ]; + + return ( + + {qrcode && ( + <> +
+
+ 二维码名称: + {qrcode.qrcodeName || '未命名'} +
+
+ 二维码Code: + + {qrcode.qrcodeCode} + +
+
+ 订单总数: + {qrcode.orderCount} +
+
+ 今日订单: + + {qrcode.todayOrderCount} + +
+
+ + + 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 }} + /> + + )} +
+ ); +}; + +export default OrderListDrawer; diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/TourismSection.tsx b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/TourismSection.tsx new file mode 100644 index 00000000..1c5b5dd0 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/components/TourismSection.tsx @@ -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 = ({ tourism, onQrcodeClick }) => { + return ( +
+
+

+ {tourism.tourismName} + {tourism.tourismAddress && ( + + {tourism.tourismAddress} + + )} +

+
+
+ + 二维码: + {tourism.qrcodeCount} +
+
+ + 订单总数: + {tourism.orderCount} +
+
+
+ +
+ + {tourism.qrcodeList.map((qrcode) => ( + + onQrcodeClick(qrcode)} + hoverable + bodyStyle={{ padding: 0 }} + > +
+ {qrcode.qrcodeName} +
+ {qrcode.status === 0 ? '启用' : '禁用'} +
+
+ +
+
+ {qrcode.qrcodeName || '未命名'} +
+ +
+
+
{qrcode.orderCount}
+
总订单
+
+
+
+ {qrcode.todayOrderCount} +
+
今日
+
+
+ +
+ Code: {qrcode.qrcodeCode} +
+
+
+ + ))} +
+
+
+ ); +}; + +export default TourismSection; diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.less b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.less new file mode 100644 index 00000000..006d61e2 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.less @@ -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; + } + } + } +} diff --git a/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.tsx b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.tsx new file mode 100644 index 00000000..d879f86b --- /dev/null +++ b/zlt-web/react-web-next/src/pages/orders/QrcodeOrder/index.tsx @@ -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(null); + const [params, setParams] = useState>({}); + const [drawerOpen, setDrawerOpen] = useState(false); + const [selectedQrcode, setSelectedQrcode] = useState(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, 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 ( + + {/* 顶部筛选栏 */} + { + 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); + }} + > + + + + + + {/* 统计概览卡片 */} + {statistics && ( + + + + } + valueStyle={{ color: '#1890ff' }} + /> + + + + + } + valueStyle={{ color: '#722ed1' }} + /> + + + + + } + valueStyle={{ color: '#52c41a' }} + /> + + + + + } + valueStyle={{ color: '#fa8c16' }} + /> + + + + )} + + {/* 景区二维码卡片网格 */} + + {statistics && statistics.tourismList.length > 0 ? ( + <> + {statistics.tourismList.map((tourism) => ( + + ))} + {/* 加载更多按钮 */} + {hasMore && ( +
+ + {loadingMore ? '加载中...' : '加载更多'} + +
+ )} + + ) : ( + + + + )} +
+ + {/* 订单列表抽屉 */} + setDrawerOpen(false)} + qrcode={selectedQrcode} + queryParams={params} + /> +
+ ); +}; + +export default QrcodeOrderPage; diff --git a/zlt-web/react-web-next/src/services/orders.ts b/zlt-web/react-web-next/src/services/orders.ts index a978e6a0..486294de 100644 --- a/zlt-web/react-web-next/src/services/orders.ts +++ b/zlt-web/react-web-next/src/services/orders.ts @@ -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 }; + }, }; diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx index 741e1c43..cd8be404 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryPreview.tsx @@ -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 = ({ fontSize: 12, color: '#faad14', }}> - ⚠️ 至少需要3个顶点才能形成边界 + 提示:至少需要3个顶点才能形成边界 )} @@ -141,7 +141,7 @@ const BoundaryPreview: React.FC = ({ fontSize: 12, color: '#52c41a', }}> - ✓ 边界已形成,可以保存 + 边界已形成,可以保存 )} diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx index 5c16ca14..eee1b098 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/BoundaryToolbar.tsx @@ -1,6 +1,6 @@ /** * 边界编辑器工具栏组件 - * @author Claude + * @author dzc * @date 2026-01-06 */ import React from 'react'; @@ -22,9 +22,11 @@ const BoundaryToolbar: React.FC = ({ hasVertices, hasUnsavedChanges, isDrawing, + canUndo, onModeChange, onStartDraw, onFinishDraw, + onUndo, onClear, onSave, onCancel, @@ -50,8 +52,9 @@ const BoundaryToolbar: React.FC = ({ icon={} 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 = ({ )} + {/* 撤销按钮 */} + {onUndo && ( + + + + )} + {/* 分隔线 */} {hasVertices && (
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]); diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts index c71938c6..191fadce 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/hooks/useCesiumBoundaryRenderer.ts @@ -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(null); const rafIdRef = useRef(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, diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less index 2d7da109..45eff9f3 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.less @@ -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; diff --git a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx index 8168616e..d70473b9 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx @@ -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 = ({ - scenicId, + deviceSn, boundaryId, initialVertices, onSaveSuccess, @@ -46,8 +71,25 @@ const BoundaryEditor: React.FC = ({ 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 = ({ 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 = ({ }; // 处理地图点击 - 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 = ({ [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 = ({ }; }, [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 (
{/* 工具栏 - 独立渲染,不受Spin影响 */} @@ -252,9 +307,11 @@ const BoundaryEditor: React.FC = ({ 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 = ({ placeholder="请选择边界类型" onChange={(value) => setBoundaryType(value as BoundaryType)} > - - - + + + - - - - -
- 顶点数量: {vertices.length} +
+
顶点数量:{vertices.length}
+
中心点:{centerPointText}
+
估算面积:{areaText}
@@ -323,7 +378,7 @@ const BoundaryEditor: React.FC = ({ {/* 全局Loading遮罩 - 仅在加载时显示 */} {loading && (
void; onStartDraw: () => void; onFinishDraw: () => void; + onUndo?: () => void; onClear: () => void; onSave: () => void; onCancel: () => void; diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less index 74455e3a..8da25f41 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.less @@ -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; diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx index cf4b4121..4744450e 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/LayerPanel.tsx @@ -1,21 +1,25 @@ /** * 图层管理面板组件 - * 用于管理航线、边界等图层的显示/隐藏 - * @author Claude + * 用于管理边界图层的显示/隐藏 + * @author dzc * @date 2026-01-06 */ -import React, { useState, useEffect, useRef, useCallback } from 'react'; -import { Card, Checkbox, List, Tag, Button, message, Empty, Tooltip, Space } from 'antd'; +import React, { useState, useEffect, useLayoutEffect, useRef, useCallback } from 'react'; +import { Card, Checkbox, List, Tag, Button, message, Empty, Tooltip, Space, Popconfirm } from 'antd'; import { CloseOutlined, ReloadOutlined, EyeOutlined, EyeInvisibleOutlined, PlusOutlined, + DeleteOutlined, } from '@ant-design/icons'; -import { getBoatRoutesByScenicId, getBoatRouteDetail } from '@/services/boatRoute'; -import { getWaterBoundariesByScenicId } from '@/services/waterBoundary'; -import type { BoatRouteListVO, RouteStatus } from '@/types/boatRoute'; +import { + getWaterBoundariesByDeviceSn, + getWaterBoundaryDetail, + updateWaterBoundaryShowInModelByDeviceSn, + deleteWaterBoundary, +} from '@/services/waterBoundary'; import type { WaterBoundaryVO } from '@/pages/map3d/components/BoundaryEditor/types'; import styles from './LayerPanel.less'; @@ -24,13 +28,91 @@ export interface LayerPanelProps { onClose: () => void; viewer: any; Cesium: any; + deviceSn?: string; scenicId?: number; onBoundaryEditorOpen?: () => void; // 新增:打开边界编辑器的回调 + onRoutePlanningOpen?: (boundary: WaterBoundaryVO) => void; + autoShowBoundaryId?: string; + onAutoShowBoundaryHandled?: () => void; } -interface LayerEntity { - id: string; - entityIds: string[]; +function normalizeId(value: any): string { + return String(value ?? '').trim(); +} + +type NormalizedPoint = { longitude: number; latitude: number }; + +function normalizePoint(coord: any): NormalizedPoint | null { + if (!Array.isArray(coord) || coord.length < 2) return null; + const longitude = Number(coord[0]); + const latitude = Number(coord[1]); + if (Number.isNaN(longitude) || Number.isNaN(latitude)) return null; + return { longitude, latitude }; +} + +function stripClosedRing(points: NormalizedPoint[]): NormalizedPoint[] { + if (points.length < 2) return points; + const first = points[0]; + const last = points[points.length - 1]; + if (first.longitude === last.longitude && first.latitude === last.latitude) { + return points.slice(0, -1); + } + return points; +} + +function parseBoundaryGeoJson(polygonData: string): Array<{ outer: NormalizedPoint[]; holes: NormalizedPoint[][] }> { + const result: Array<{ outer: NormalizedPoint[]; holes: NormalizedPoint[][] }> = []; + if (!polygonData) return result; + + let raw: any; + try { + raw = JSON.parse(polygonData); + } catch { + return result; + } + + // 兼容:Feature / FeatureCollection / Geometry + const geometry = (() => { + if (!raw) return null; + if (raw.type === 'Feature') return raw.geometry ?? null; + if (raw.type === 'FeatureCollection') return raw.features?.[0]?.geometry ?? null; + return raw; + })(); + + if (!geometry?.type) return result; + + const pushPolygon = (polygonCoords: any) => { + if (!Array.isArray(polygonCoords) || polygonCoords.length === 0) return; + const rings = polygonCoords.filter((r: any) => Array.isArray(r)); + if (rings.length === 0) return; + + const normalizeRing = (ring: any): NormalizedPoint[] => { + if (!Array.isArray(ring)) return []; + const pts = ring.map(normalizePoint).filter(Boolean) as NormalizedPoint[]; + return stripClosedRing(pts); + }; + + const outer = normalizeRing(rings[0]); + const holes = rings.slice(1).map(normalizeRing).filter(h => h.length >= 3); + if (outer.length >= 3) { + result.push({ outer, holes }); + } + }; + + if (geometry.type === 'Polygon') { + pushPolygon(geometry.coordinates); + } else if (geometry.type === 'MultiPolygon') { + const polys = Array.isArray(geometry.coordinates) ? geometry.coordinates : []; + polys.forEach(pushPolygon); + } + + return result; +} + +function getBoundaryVertexCount(boundary: WaterBoundaryVO): number { + const polys = parseBoundaryGeoJson(boundary.polygonData); + if (!polys.length) return 0; + return polys.reduce((sum, p) => sum + (p.outer?.length || 0), 0); } /** @@ -40,9 +122,9 @@ function getBoundaryColor(type: string, Cesium: any) { switch (type) { 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'); @@ -56,9 +138,9 @@ function getBoundaryAlpha(type: string): 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; @@ -70,55 +152,236 @@ const LayerPanel: React.FC = ({ onClose, viewer, Cesium, - scenicId, + deviceSn, onBoundaryEditorOpen, // 新增 + onRoutePlanningOpen, + autoShowBoundaryId, + onAutoShowBoundaryHandled, }) => { - // 航线列表 - const [routes, setRoutes] = useState([]); - const [loadingRoutes, setLoadingRoutes] = useState(false); - const [visibleRoutes, setVisibleRoutes] = useState>(new Set()); - // 边界列表 const [boundaries, setBoundaries] = useState([]); const [loadingBoundaries, setLoadingBoundaries] = useState(false); const [visibleBoundaries, setVisibleBoundaries] = useState>(new Set()); + // 用于卸载时清理(避免依赖变化触发 cleanup 误删) + const visibleBoundariesRef = useRef>(new Set()); + + useEffect(() => { + visibleBoundariesRef.current = visibleBoundaries; + }, [visibleBoundaries]); + // Entity引用管理 - const routeEntitiesRef = useRef>(new Map()); const boundaryEntitiesRef = useRef>(new Map()); + const currentDeviceSnRef = useRef(''); + const loadBoundariesSeqRef = useRef(0); + const selectionVersionRef = useRef(0); + const pendingApplyShowInModelRef = useRef<{ requestSeq: number; selectionVersionAtStart: number } | null>(null); - /** - * 加载航线列表 - */ - const loadRoutes = useCallback(async () => { - if (!scenicId) return; + const normalizedDeviceSn = normalizeId(deviceSn); - setLoadingRoutes(true); + const clearAllBoundaryEntities = useCallback(() => { + if (!viewer || viewer.isDestroyed?.()) return; + boundaryEntitiesRef.current.forEach((entityIds) => { + entityIds.forEach((id) => { + try { + viewer.entities.removeById(id); + } catch { + // 忽略 + } + }); + }); + boundaryEntitiesRef.current.clear(); try { - const response = await getBoatRoutesByScenicId(scenicId); - if (response.resp_code === 0 && response.datas) { - const routeList = Array.isArray(response.datas) ? response.datas : (response.datas as any).records || []; - setRoutes(routeList); - } - } catch (error) { - console.error('加载航线列表失败:', error); - message.error('加载航线列表失败'); - } finally { - setLoadingRoutes(false); + viewer.scene?.requestRender?.(); + } catch { + // 忽略 } - }, [scenicId]); + }, [viewer]); + + const persistShowInModel = useCallback(async (deviceSnToSave: string, boundaryIds: string[]) => { + const sn = normalizeId(deviceSnToSave); + if (!sn) { + message.warning('请先选择设备'); + return false; + } + + try { + const res = await updateWaterBoundaryShowInModelByDeviceSn(sn, boundaryIds); + if ((res as any)?.resp_code === 0) return true; + message.error((res as any)?.resp_msg || '标绘显示状态保存失败'); + return false; + } catch (e) { + console.error('标绘显示状态保存失败:', e); + message.error('标绘显示状态保存失败'); + return false; + } + }, []); + + // 面板拖动 + const panelRef = useRef(null); + const dragStateRef = useRef<{ + startX: number; + startY: number; + startLeft: number; + startTop: number; + panelWidth: number; + panelHeight: number; + } | null>(null); + const [panelPos, setPanelPos] = useState<{ left: number; top: number } | null>(null); + const panelPosRef = useRef<{ left: number; top: number } | null>(null); + const PANEL_POS_KEY = 'yingyan_layer_panel_position_v1'; + + useEffect(() => { + panelPosRef.current = panelPos; + }, [panelPos]); + + const clampPanelPos = useCallback((pos: { left: number; top: number }, panelWidth: number, panelHeight: number) => { + const margin = 12; + const maxLeft = Math.max(margin, window.innerWidth - panelWidth - margin); + const maxTop = Math.max(margin, window.innerHeight - panelHeight - margin); + return { + left: Math.min(Math.max(pos.left, margin), maxLeft), + top: Math.min(Math.max(pos.top, margin), maxTop), + }; + }, []); + + // 初始化拖动位置(优先本地缓存,否则默认左下角) + useLayoutEffect(() => { + if (!visible) return; + if (panelPos) return; + const el = panelRef.current; + if (!el) return; + + const rect = el.getBoundingClientRect(); + const width = rect.width || 320; + const height = rect.height || 300; + + try { + const raw = localStorage.getItem(PANEL_POS_KEY); + if (raw) { + const parsed = JSON.parse(raw) as { left?: number; top?: number }; + if (typeof parsed.left === 'number' && typeof parsed.top === 'number') { + setPanelPos(clampPanelPos({ left: parsed.left, top: parsed.top }, width, height)); + return; + } + } + } catch { + // 忽略 + } + + setPanelPos( + clampPanelPos( + { + left: 20, + top: Math.max(20, window.innerHeight - height - 20), + }, + width, + height, + ), + ); + }, [visible, panelPos, clampPanelPos]); + + // 窗口尺寸变化时,自动把面板“夹”回可视区域 + useEffect(() => { + if (!visible) return; + if (!panelPos) return; + const el = panelRef.current; + if (!el) return; + + const handleResize = () => { + const rect = el.getBoundingClientRect(); + setPanelPos(prev => { + if (!prev) return prev; + return clampPanelPos(prev, rect.width || 320, rect.height || 300); + }); + }; + window.addEventListener('resize', handleResize); + return () => window.removeEventListener('resize', handleResize); + }, [visible, panelPos, clampPanelPos]); + + const handleDragStart = useCallback((e: React.PointerEvent) => { + // 仅左键拖动 + if (e.button !== 0) return; + + const target = e.target as HTMLElement | null; + if (target?.closest('button,a,input,textarea,.ant-btn,.ant-checkbox-wrapper,.ant-select,.ant-dropdown')) { + return; + } + + const el = panelRef.current; + if (!el) return; + const rect = el.getBoundingClientRect(); + + const current = panelPos ?? { left: rect.left, top: rect.top }; + const next = clampPanelPos(current, rect.width || 320, rect.height || 300); + setPanelPos(next); + + dragStateRef.current = { + startX: e.clientX, + startY: e.clientY, + startLeft: next.left, + startTop: next.top, + panelWidth: rect.width || 320, + panelHeight: rect.height || 300, + }; + + try { + (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId); + } catch { + // 忽略 + } + e.preventDefault(); + }, [panelPos, clampPanelPos]); + + const handleDragMove = useCallback((e: React.PointerEvent) => { + const state = dragStateRef.current; + if (!state) return; + const { startX, startY, startLeft, startTop, panelWidth, panelHeight } = state; + + const next = clampPanelPos( + { + left: startLeft + (e.clientX - startX), + top: startTop + (e.clientY - startY), + }, + panelWidth, + panelHeight, + ); + setPanelPos(next); + e.preventDefault(); + }, [clampPanelPos]); + + const handleDragEnd = useCallback(() => { + if (!dragStateRef.current) return; + dragStateRef.current = null; + const latest = panelPosRef.current; + if (!latest) return; + try { + localStorage.setItem(PANEL_POS_KEY, JSON.stringify(latest)); + } catch { + // 忽略 + } + }, []); /** * 加载边界列表 */ - const loadBoundaries = useCallback(async () => { - if (!scenicId) return; + const loadBoundaries = useCallback(async (deviceSnOverride?: string) => { + const targetDeviceSn = normalizeId(deviceSnOverride ?? deviceSn); + if (!targetDeviceSn) return; + + const requestSeq = ++loadBoundariesSeqRef.current; + const selectionVersionAtStart = selectionVersionRef.current; setLoadingBoundaries(true); try { - const response = await getWaterBoundariesByScenicId(scenicId); - if (response.resp_code === 0 && response.datas) { - setBoundaries(response.datas); + const response = await getWaterBoundariesByDeviceSn(targetDeviceSn); + if (requestSeq !== loadBoundariesSeqRef.current) { + return; + } + const list = (response as any)?.data ?? (response as any)?.datas; + if (response.resp_code === 0 && list) { + pendingApplyShowInModelRef.current = { requestSeq, selectionVersionAtStart }; + setBoundaries(Array.isArray(list) ? list : []); } } catch (error) { console.error('加载边界列表失败:', error); @@ -126,163 +389,7 @@ const LayerPanel: React.FC = ({ } finally { setLoadingBoundaries(false); } - }, [scenicId]); - - /** - * 渲染航线 - */ - const renderRoute = useCallback(async (route: BoatRouteListVO) => { - if (!viewer || !Cesium || viewer.isDestroyed?.()) return; - - const entityIds: string[] = []; - - try { - // 获取航线详情以获取航点数据 - const detailResponse = await getBoatRouteDetail(route.routeId); - if (detailResponse.resp_code !== 0 || !detailResponse.datas) { - message.warning(`获取航线 [${route.routeName}] 详情失败`); - return; - } - - const routeDetail = detailResponse.datas; - if (!routeDetail.waypoints || routeDetail.waypoints.length < 2) { - message.warning(`航线 [${route.routeName}] 航点不足`); - return; - } - - // 渲染航点marker - routeDetail.waypoints.forEach((wp: any, i: number) => { - const entityId = `layer-route-${route.routeId}-wp-${i}`; - const entity = viewer.entities.add({ - id: entityId, - position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0), - point: { - pixelSize: 8, - color: Cesium.Color.CYAN.withAlpha(0.7), - outlineColor: Cesium.Color.WHITE, - outlineWidth: 1, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - label: { - text: `${i + 1}`, - font: '10px sans-serif', - fillColor: Cesium.Color.WHITE, - style: Cesium.LabelStyle.FILL_AND_OUTLINE, - outlineWidth: 1, - outlineColor: Cesium.Color.BLACK, - verticalOrigin: Cesium.VerticalOrigin.BOTTOM, - pixelOffset: new Cesium.Cartesian2(0, -12), - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - properties: { - type: 'layer-route-waypoint', - routeId: route.routeId, - }, - }); - entityIds.push(entityId); - }); - - // 渲染航线polyline - const positions = routeDetail.waypoints.map((wp: any) => - Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0) - ); - - const polylineId = `layer-route-${route.routeId}-path`; - viewer.entities.add({ - id: polylineId, - polyline: { - positions: positions, - width: 3, - material: new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.2, - color: Cesium.Color.CYAN.withAlpha(0.8), - }), - clampToGround: true, - }, - properties: { - type: 'layer-route-path', - routeId: route.routeId, - }, - }); - entityIds.push(polylineId); - - routeEntitiesRef.current.set(route.routeId, entityIds); - console.log(`航线 [${route.routeName}] 渲染成功`); - } catch (error) { - console.error(`渲染航线 [${route.routeName}] 失败:`, error); - message.error(`渲染航线失败`); - } - }, [viewer, Cesium]); - - /** - * 移除航线 - */ - const removeRoute = useCallback((routeId: string) => { - if (!viewer || viewer.isDestroyed?.()) return; - - const entityIds = routeEntitiesRef.current.get(routeId); - if (entityIds) { - entityIds.forEach(id => { - try { - viewer.entities.removeById(id); - } catch (e) { - console.warn(`移除entity ${id} 失败:`, e); - } - }); - routeEntitiesRef.current.delete(routeId); - } - }, [viewer]); - - /** - * 渲染边界 - */ - const renderBoundary = useCallback((boundary: WaterBoundaryVO) => { - if (!viewer || !Cesium || viewer.isDestroyed?.()) return; - - const entityIds: string[] = []; - - try { - // 解析GeoJSON - const geoJson = JSON.parse(boundary.geoJson); - if (geoJson.type !== 'Polygon' || !geoJson.coordinates || !geoJson.coordinates[0]) { - message.warning(`边界 [${boundary.boundaryName}] 数据格式错误`); - return; - } - - const coordinates = geoJson.coordinates[0]; - const positions = coordinates.map((coord: number[]) => - Cesium.Cartesian3.fromDegrees(coord[0], coord[1], 0) - ); - - // 渲染多边形 - const baseColor = getBoundaryColor(boundary.boundaryType, Cesium); - const alpha = getBoundaryAlpha(boundary.boundaryType); - - const polygonId = `layer-boundary-${boundary.id}-polygon`; - viewer.entities.add({ - id: polygonId, - polygon: { - hierarchy: new Cesium.PolygonHierarchy(positions), - material: baseColor.withAlpha(alpha), - outline: true, - outlineColor: baseColor, - outlineWidth: 2, - classificationType: Cesium.ClassificationType.BOTH, - }, - properties: { - type: 'layer-boundary', - boundaryId: boundary.id, - }, - }); - entityIds.push(polygonId); - - boundaryEntitiesRef.current.set(boundary.id, entityIds); - console.log(`边界 [${boundary.boundaryName}] 渲染成功`); - } catch (error) { - console.error(`渲染边界 [${boundary.boundaryName}] 失败:`, error); - message.error(`渲染边界失败`); - } - }, [viewer, Cesium]); + }, [deviceSn]); /** * 移除边界 @@ -301,130 +408,371 @@ const LayerPanel: React.FC = ({ }); boundaryEntitiesRef.current.delete(boundaryId); } + + try { + viewer.scene?.requestRender?.(); + } catch { + // 忽略 + } }, [viewer]); /** - * 处理航线勾选变化 + * 渲染边界 */ - const handleRouteCheckChange = useCallback((routeId: string, checked: boolean) => { - if (checked) { - // 检查是否超过最大显示数量 - if (visibleRoutes.size >= 5) { - message.warning('最多同时显示5条航线,请先取消勾选其他航线'); + const renderBoundary = useCallback((boundary: WaterBoundaryVO) => { + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + + const entityIds: string[] = []; + + try { + const normalizedBoundaryId = normalizeId((boundary as any)?.boundaryId); + if (!normalizedBoundaryId) { + message.warning('边界ID无效,无法渲染'); return; } - const route = routes.find(r => r.routeId === routeId); - if (route) { - renderRoute(route); - setVisibleRoutes(prev => new Set(prev).add(routeId)); + // 清理旧记录(以 ref 为准) + removeBoundary(normalizedBoundaryId); + + // 解析 GeoJSON(兼容 Polygon / MultiPolygon / Feature / FeatureCollection) + const polygons = parseBoundaryGeoJson(boundary.polygonData); + if (!polygons.length) { + message.warning(`边界 [${boundary.boundaryName}] 数据格式错误,无法解析为多边形`); + return; } - } else { - removeRoute(routeId); - setVisibleRoutes(prev => { - const newSet = new Set(prev); - newSet.delete(routeId); - return newSet; + + // 渲染多边形 + const baseColor = getBoundaryColor(boundary.boundaryType, Cesium); + const alpha = getBoundaryAlpha(boundary.boundaryType); + + polygons.forEach((poly, index) => { + const polygonId = `layer-boundary-${normalizedBoundaryId}-polygon-${index}`; + + // 先清理同 ID 的旧实体(避免“already exists”报错) + try { + if (viewer.entities.getById?.(polygonId)) { + viewer.entities.removeById(polygonId); + } + } catch { + // 忽略 + } + + const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)); + if (positions.length < 3) return; + + const holes = poly.holes + .map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0))) + .filter((ring) => ring.length >= 3) + .map((ring) => new Cesium.PolygonHierarchy(ring)); + + viewer.entities.add({ + id: polygonId, + polygon: { + hierarchy: new Cesium.PolygonHierarchy(positions, holes), + material: baseColor.withAlpha(alpha), + outline: true, + outlineColor: baseColor, + outlineWidth: 2, + // 为了确保在“地形”和“3D Tiles 模型”上都能显示,统一使用 BOTH + classificationType: Cesium.ClassificationType?.BOTH, + }, + properties: { + type: 'layer-boundary', + boundaryId: normalizedBoundaryId, + }, + }); + entityIds.push(polygonId); }); + + if (!entityIds.length) { + message.warning(`边界 [${boundary.boundaryName}] 顶点不足`); + return; + } + + boundaryEntitiesRef.current.set(normalizedBoundaryId, entityIds); + console.log(`边界 [${boundary.boundaryName}] 渲染成功`); + viewer.scene?.requestRender?.(); + } catch (error) { + console.error(`渲染边界 [${boundary.boundaryName}] 失败:`, error); + message.error(`渲染边界失败`); } - }, [visibleRoutes, routes, renderRoute, removeRoute]); + }, [viewer, Cesium, removeBoundary]); + + const applyShowInModelFromList = useCallback((list: WaterBoundaryVO[]) => { + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + clearAllBoundaryEntities(); + + const toShow = new Set(); + list.forEach((b) => { + const id = normalizeId((b as any)?.boundaryId); + if (!id) return; + if (Number((b as any)?.showInModel) === 1) { + toShow.add(id); + renderBoundary(b); + } + }); + setVisibleBoundaries(toShow); + }, [viewer, Cesium, clearAllBoundaryEntities, renderBoundary]); + + // 从后端列表应用 showInModel(仅在 loadBoundaries 成功后触发) + useEffect(() => { + const pending = pendingApplyShowInModelRef.current; + if (!pending) return; + + // 只处理最新一次请求的回写 + if (pending.requestSeq !== loadBoundariesSeqRef.current) { + pendingApplyShowInModelRef.current = null; + return; + } + + // 如果用户在请求期间已经修改过选择,则不要用这次返回覆盖当前显示 + if (pending.selectionVersionAtStart !== selectionVersionRef.current) { + pendingApplyShowInModelRef.current = null; + return; + } + + pendingApplyShowInModelRef.current = null; + applyShowInModelFromList(boundaries); + }, [boundaries, applyShowInModelFromList]); + + // 设备切换:清理上一设备边界,并加载后端持久化的 showInModel 状态 + useEffect(() => { + if (!viewer || viewer.isDestroyed?.()) return; + + const sn = normalizedDeviceSn; + if (!sn) { + currentDeviceSnRef.current = ''; + loadBoundariesSeqRef.current += 1; + pendingApplyShowInModelRef.current = null; + clearAllBoundaryEntities(); + setVisibleBoundaries(new Set()); + setBoundaries([]); + return; + } + + if (currentDeviceSnRef.current && currentDeviceSnRef.current !== sn) { + clearAllBoundaryEntities(); + setVisibleBoundaries(new Set()); + } + currentDeviceSnRef.current = sn; + + // 拉取当前设备边界列表(面板不打开也要渲染已选标绘) + loadBoundaries(sn); + }, [viewer, normalizedDeviceSn, clearAllBoundaryEntities, loadBoundaries]); + + // 保存成功后:自动显示刚创建的边界(避免编辑器关闭后边界消失) + useEffect(() => { + if (!autoShowBoundaryId) return; + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + + (async () => { + try { + const res = await getWaterBoundaryDetail(autoShowBoundaryId); + const boundary = (res as any)?.data ?? (res as any)?.datas; + if (res.resp_code !== 0 || !boundary) { + message.warning(res.resp_msg || '获取边界详情失败'); + return; + } + + // 先用边界详情里的 deviceSn 刷新列表(避免当前选择设备不一致导致列表不更新) + const boundaryDeviceSn = normalizeId(boundary.deviceSn); + await loadBoundaries(boundaryDeviceSn || undefined); + + // 若已显示则不重复渲染 + setVisibleBoundaries(prev => { + const next = new Set(prev); + next.add(autoShowBoundaryId); + return next; + }); + + renderBoundary(boundary); + viewer.scene?.requestRender?.(); + } catch (e) { + console.error('自动显示新边界失败:', e); + } finally { + onAutoShowBoundaryHandled?.(); + } + })(); + }, [autoShowBoundaryId, viewer, Cesium, loadBoundaries, renderBoundary, onAutoShowBoundaryHandled]); /** * 处理边界勾选变化 */ const handleBoundaryCheckChange = useCallback((boundaryId: string, checked: boolean) => { + const sn = normalizedDeviceSn; + if (!sn) { + message.warning('请先选择设备'); + return; + } + + selectionVersionRef.current += 1; + + const normalizedBoundaryId = normalizeId(boundaryId); + if (!normalizedBoundaryId) return; + + const prevSet = new Set(visibleBoundaries); + const nextSet = new Set(prevSet); + if (checked) { - const boundary = boundaries.find(b => b.id === boundaryId); + const boundary = boundaries.find(b => String((b as any)?.boundaryId ?? '').trim() === normalizedBoundaryId); if (boundary) { + // 勾选即确保渲染(renderBoundary 内部会先清理旧实体,避免重复) renderBoundary(boundary); - setVisibleBoundaries(prev => new Set(prev).add(boundaryId)); + nextSet.add(normalizedBoundaryId); + setVisibleBoundaries(nextSet); } } else { - removeBoundary(boundaryId); - setVisibleBoundaries(prev => { - const newSet = new Set(prev); - newSet.delete(boundaryId); - return newSet; - }); + removeBoundary(normalizedBoundaryId); + nextSet.delete(normalizedBoundaryId); + setVisibleBoundaries(nextSet); } - }, [boundaries, renderBoundary, removeBoundary]); + + (async () => { + const ok = await persistShowInModel(sn, Array.from(nextSet)); + if (!ok) { + // 失败后以服务端为准回滚(避免本地状态与后端不一致) + await loadBoundaries(sn); + return; + } + + // 本地同步 showInModel,确保后续刷新前 UI 与后端一致 + setBoundaries((prev) => prev.map((b) => { + const id = normalizeId((b as any)?.boundaryId); + if (!id) return b; + return { ...b, showInModel: nextSet.has(id) ? 1 : 0 }; + })); + })(); + }, [normalizedDeviceSn, visibleBoundaries, boundaries, renderBoundary, removeBoundary, persistShowInModel, loadBoundaries]); + + /** + * 处理删除边界 + */ + const handleDeleteBoundary = useCallback(async (boundaryId: string, boundaryName: string) => { + try { + const res = await deleteWaterBoundary(boundaryId); + if (res.resp_code === 0) { + message.success(`边界 [${boundaryName}] 已删除`); + // 从地图移除 + removeBoundary(boundaryId); + // 从列表移除 + setBoundaries(prev => prev.filter(b => String((b as any)?.boundaryId ?? '').trim() !== boundaryId)); + // 从可见集合移除 + setVisibleBoundaries(prev => { + const next = new Set(prev); + next.delete(boundaryId); + return next; + }); + } else { + message.error(res.resp_msg || '删除失败'); + } + } catch (error) { + console.error('删除边界失败:', error); + message.error('删除边界失败'); + } + }, [removeBoundary]); /** * 刷新数据 */ const handleRefresh = useCallback(() => { - loadRoutes(); loadBoundaries(); - }, [loadRoutes, loadBoundaries]); - - /** - * 全部显示/隐藏航线 - */ - const handleToggleAllRoutes = useCallback((show: boolean) => { - if (show) { - if (routes.length > 5) { - message.warning('最多同时显示5条航线,已自动选择前5条'); - } - const routesToShow = routes.slice(0, 5); - routesToShow.forEach(route => { - renderRoute(route); - }); - setVisibleRoutes(new Set(routesToShow.map(r => r.routeId))); - } else { - visibleRoutes.forEach(routeId => removeRoute(routeId)); - setVisibleRoutes(new Set()); - } - }, [routes, visibleRoutes, renderRoute, removeRoute]); + }, [loadBoundaries]); /** * 全部显示/隐藏边界 */ const handleToggleAllBoundaries = useCallback((show: boolean) => { + const sn = normalizedDeviceSn; + if (!sn) { + message.warning('请先选择设备'); + return; + } + + selectionVersionRef.current += 1; + if (show) { + clearAllBoundaryEntities(); boundaries.forEach(boundary => { + const normalizedBoundaryId = String((boundary as any)?.boundaryId ?? '').trim(); + if (!normalizedBoundaryId) return; renderBoundary(boundary); }); - setVisibleBoundaries(new Set(boundaries.map(b => b.id))); + const nextSet = new Set(boundaries.map(b => String((b as any)?.boundaryId ?? '').trim()).filter(Boolean)); + setVisibleBoundaries(nextSet); + try { + viewer?.scene?.requestRender?.(); + } catch { + // 忽略 + } + + (async () => { + const ok = await persistShowInModel(sn, Array.from(nextSet)); + if (!ok) { + await loadBoundaries(sn); + return; + } + setBoundaries((prev) => prev.map((b) => ({ ...b, showInModel: 1 }))); + })(); } else { - visibleBoundaries.forEach(boundaryId => removeBoundary(boundaryId)); + clearAllBoundaryEntities(); setVisibleBoundaries(new Set()); + (async () => { + const ok = await persistShowInModel(sn, []); + if (!ok) { + await loadBoundaries(sn); + return; + } + setBoundaries((prev) => prev.map((b) => ({ ...b, showInModel: 0 }))); + })(); } - }, [boundaries, visibleBoundaries, renderBoundary, removeBoundary]); + }, [normalizedDeviceSn, boundaries, renderBoundary, viewer, clearAllBoundaryEntities, persistShowInModel, loadBoundaries]); // 初始加载 useEffect(() => { - if (visible && scenicId) { - loadRoutes(); + if (!visible) return; + if (deviceSn) { loadBoundaries(); } - }, [visible, scenicId, loadRoutes, loadBoundaries]); + }, [visible, deviceSn, loadBoundaries]); - // 组件卸载时清理所有图层 + // 组件卸载时清理所有图层(注意:不要把 visibleBoundaries 放依赖里,否则每次勾选都会触发 cleanup 误删) useEffect(() => { return () => { - visibleRoutes.forEach(routeId => removeRoute(routeId)); - visibleBoundaries.forEach(boundaryId => removeBoundary(boundaryId)); + visibleBoundariesRef.current.forEach(boundaryId => removeBoundary(boundaryId)); }; - }, [visibleRoutes, visibleBoundaries, removeRoute, removeBoundary]); + }, [removeBoundary]); if (!visible) return null; return ( -
+
- 图层管理 - -
} size="small" extra={ @@ -437,66 +785,6 @@ const LayerPanel: React.FC = ({ } className={styles.card} > - {/* 航线图层 */} -
-
- 📍 航线图层 - - {routes.length > 0 && ( - <> - - - - )} - -
- - {loadingRoutes ? ( -
加载中...
- ) : routes.length === 0 ? ( - - ) : ( - ( - - handleRouteCheckChange(route.routeId, e.target.checked)} - > - {route.routeName} - - - {route.status === 1 && 已发布} - {route.status === 0 && 草稿} - {route.waypointCount || 0}点 - - - )} - /> - )} -
{/* 边界图层 */}
@@ -551,22 +839,55 @@ const LayerPanel: React.FC = ({ renderItem={boundary => ( handleBoundaryCheckChange(boundary.id, e.target.checked)} + checked={visibleBoundaries.has(String((boundary as any)?.boundaryId ?? '').trim())} + onChange={e => handleBoundaryCheckChange(String((boundary as any)?.boundaryId ?? '').trim(), e.target.checked)} > {boundary.boundaryName} {boundary.boundaryType === 'navigable' && ( - 可通行 + 可航行 )} - {boundary.boundaryType === 'forbidden' && ( - 禁行 + {boundary.boundaryType === 'restricted' && ( + 禁行区 )} - {boundary.boundaryType === 'warning' && ( - 警告 + {boundary.boundaryType === 'obstacle' && ( + 障碍物 )} - {boundary.vertexCount || 0}点 + {getBoundaryVertexCount(boundary)}点 + {boundary.boundaryType === 'navigable' && ( + + )} + { + e?.stopPropagation(); + handleDeleteBoundary( + String((boundary as any)?.boundaryId ?? '').trim(), + boundary.boundaryName + ); + }} + okText="确定" + cancelText="取消" + > +
{/* 提示信息 */} - {visibleRoutes.size > 0 || visibleBoundaries.size > 0 ? ( + {visibleBoundaries.size > 0 ? (
- 已显示: {visibleRoutes.size} 条航线, {visibleBoundaries.size} 个边界 + 已显示: {visibleBoundaries.size} 个边界
) : null} diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less index 336e2dff..75bb0da0 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.less @@ -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 @@ } } } -} \ No newline at end of file +} diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx index f8733600..61e0fb2a 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/RightPanel.tsx @@ -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 = ({ visible, device, + onMinimize, onClose, onControlClick, onTaskPanelOpen, @@ -102,6 +106,11 @@ const RightPanel: React.FC = ({ onClose(); }; + // 收起到“设备面板” + const handleMinimize = () => { + onMinimize(); + }; + const dockData = realtimeData?.rawData?.dockData; const battery = realtimeData?.battery ?? 0; @@ -218,7 +227,18 @@ const RightPanel: React.FC = ({ }
- +
+ + + + + + +
@@ -278,14 +298,9 @@ const RightPanel: React.FC = ({ {/* 操作区 */}
-
- - -
+
) : ( diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx index 3de07322..f512d561 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/3d/BottomPanel/TaskPanel.tsx @@ -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 = ({ }) => { const deviceSn = device?.deviceSn; - // 航线相关状态 - const [routeList, setRouteList] = useState([]); + // 判断是否为无人船设备 (deviceType === 4) + const isBoatDevice = useMemo(() => device?.deviceType === 4, [device?.deviceType]); + + // 航线相关状态 - 使用统一的数据类型 + const [routeList, setRouteList] = useState([]); const [selectedRouteId, setSelectedRouteId] = useState(null); - const [waypoints, setWaypoints] = useState([]); + const [waypoints, setWaypoints] = useState([]); const [routeLoading, setRouteLoading] = useState(false); // 任务相关状态 @@ -171,17 +199,6 @@ const TaskPanel: React.FC = ({ } }, [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 = ({ 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 = ({ } }, []); - // 加载航点并绘制 - 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 = ({ 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 = ({ 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 = ({
预计时长 - {Math.ceil(selectedRoute.totalDuration / 60)} 分钟 + + {selectedRoute.totalDurationStr + ? selectedRoute.totalDurationStr + : (selectedRoute.totalDuration && Number.isFinite(selectedRoute.totalDuration) && selectedRoute.totalDuration > 0 + ? `${Math.ceil(selectedRoute.totalDuration / 60)} 分钟` + : '--')} +
@@ -827,15 +1052,15 @@ const TaskPanel: React.FC = ({
- 计划航线 + 无人机航线
- 飞行轨迹 + 无人船航线
- 无人机 + 实时位置
diff --git a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx index 9d343848..f3a72bcc 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx @@ -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 = (props) => { const containerRef = useRef(null); const viewerRef = useRef(null); const entitiesRef = useRef>(new Map()); + const pickHandlerRef = useRef(null); const [loading, setLoading] = useState(true); const [viewerReady, setViewerReady] = useState(false); // 新增:viewer 是否完全就绪 @@ -52,9 +53,11 @@ const CesiumContainer: React.FC = (props) => { // 航线规划面板状态(无人船) const [routePlanningVisible, setRoutePlanningVisible] = useState(false); const [routePlanningDevice, setRoutePlanningDevice] = useState(null); + const [routePlanningBoundaryId, setRoutePlanningBoundaryId] = useState(null); // 边界编辑面板状态(水域边界) const [boundaryEditorVisible, setBoundaryEditorVisible] = useState(false); + const [autoShowBoundaryId, setAutoShowBoundaryId] = useState(null); // 图层管理面板状态 const [layerPanelVisible, setLayerPanelVisible] = useState(false); @@ -288,12 +291,14 @@ const CesiumContainer: React.FC = (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 = (props) => { const handleOpenRoutePlanning = useCallback((device: any) => { setRoutePlanningDevice(device); setRoutePlanningVisible(true); + setRoutePlanningBoundaryId(null); // 关闭其他面板 setRightPanelVisible(false); }, []); @@ -418,27 +424,58 @@ const CesiumContainer: React.FC = (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 = (props) => { setBoundaryEditorVisible(false); // 重新打开图层管理面板,显示新创建的边界 setLayerPanelVisible(true); - }, []); + setAutoShowBoundaryId(boundaryId); + if (selectedDevice) { + setRightPanelVisible(true); + } + }, [selectedDevice]); // 计算无人机实时位置 const realtimePosition = useMemo(() => { @@ -638,6 +679,11 @@ const CesiumContainer: React.FC = (props) => { flyToGlobal(); }, [flyToGlobal, unloadAllTilesets, onClearSelection, droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]); + // 收起到“设备面板”(不清空设备、不卸载模型) + const handleRightPanelMinimize = useCallback(() => { + setRightPanelVisible(false); + }, []); + // ========== 3D Tiles 模型管理方法 ========== // 加载模型 @@ -862,9 +908,32 @@ const CesiumContainer: React.FC = (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 = (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 = (props) => { )} {/* 3D模型管理按钮 - 当设备有绑定模型时显示 */} - {!loading && currentDeviceModels.length > 0 && ( + {!loading && !boundaryEditorVisible && currentDeviceModels.length > 0 && ( + -
- +
{/* 第一视角预览 */} {isPreviewing ? ( )} +
-
- +
{/* 撤销 */} - +
-
- +
{/* 校验 */} + - +
); }; diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/WaypointEditor.tsx b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/WaypointEditor.tsx index ff3fd611..bf9ff8a6 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/WaypointEditor.tsx +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/WaypointEditor.tsx @@ -78,6 +78,19 @@ const WaypointEditor: React.FC = ({ 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={ + + + + +
+ +
+
+ 经度 + {waypoint.longitude.toFixed(6)} +
+
+ 纬度 + {waypoint.latitude.toFixed(6)} +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + +
+ + + {(fields, { add, remove }) => ( +
+ {fields.map(({ key, name, ...restField }) => ( +
+ + + + + + +
+ ))} + + +
+ )} + + ), + }, + { + key: 'remark', + label: '备注', + children: ( + +