package com.aircraft.modules.order.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.NumberChineseFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aircraft.domain.dto.AttachmentMaterialDTO;
import com.aircraft.exception.BadRequestException;
import com.aircraft.modules.aircraft.domain.AircraftDevice;
import com.aircraft.modules.aircraft.service.AircraftDeviceService;
import com.aircraft.modules.order.domain.*;
import com.aircraft.modules.order.domain.constant.OrderConstant;
import com.aircraft.modules.order.domain.constant.OrderRedisConstant;
import com.aircraft.modules.order.domain.dto.AddOrderDTO;
import com.aircraft.modules.order.domain.dto.AddOrderTaskDTO;
import com.aircraft.modules.order.domain.dto.OrderMainPageQueryDTO;
import com.aircraft.modules.order.domain.dto.UpdateOrderDTO;
import com.aircraft.modules.order.domain.enums.*;
import com.aircraft.modules.order.domain.vo.*;
import com.aircraft.modules.order.service.*;
import com.aircraft.modules.route.domain.CpRoute;
import com.aircraft.modules.route.service.CpRouteService;
import com.aircraft.modules.system.domain.*;
import com.aircraft.modules.system.domain.dto.LocalAttachmentMaterialDTO;
import com.aircraft.modules.system.domain.enums.AttachmentMaterialBusinessTypeEnum;
import com.aircraft.modules.system.domain.vo.KeyValueEntity;
import com.aircraft.modules.system.mapper.UserRoleMapper;
import com.aircraft.modules.system.service.*;
import com.aircraft.utils.RedisUtils;
import com.aircraft.utils.SecurityUtils;
import com.aircraft.utils.enums.UserTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工单业务处理类
 *
 * @author chenxiky
 * @version 1.0.0
 * @since 2025/7/11
 */

@Component
@Slf4j
public class OrderBiz {

    @Resource
    private IOrderMainService orderMainService;
    @Resource
    private IOrderOperatorService orderOperatorService;
    @Resource
    private IAttachmentMaterialService attachmentMaterialService;
    @Resource
    private IOrderDetailService orderDetailService;
    @Resource
    private EmScenicService emScenicService;
    @Resource
    private  RedisUtils redisUtils;
    @Resource
    private EmEmployeesService emEmployeesService;
    @Resource
    private CpRouteService cpRouteService;
    @Resource
    private ISettlementMainService settlementMainService;
    @Resource
    private ISettlementDetailService settlementDetailService;
    @Resource
    private CnCustomerService cnCustomerService;
    @Resource
    private AircraftDeviceService aircraftDeviceService;
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleMapper userRoleMapper;

    public IPage<OrderMainPageQueryVO> queryAll(OrderMainPageQueryDTO pageQueryDTO, Page page) {

        // 根据不同的客户端获取数据
        UserTypeEnum currentUserType = SecurityUtils.getCurrentUserType();
        // 暂时使用用 switch方式, 可结合工厂+策略获取不同的执行方法（也可通过反射代理的方式去实现，暂时使用最简单的方式）
        List<OrderMain>  orderMainList = new ArrayList<>();
        switch (currentUserType) {
            case ADMIN:
                orderMainList = adminAllOrderQueryList(pageQueryDTO);
                log.info("当前用户是后台管理员用户");
                break;
            case EMPLOYEES:
                orderMainList = employeeAllOrderQueryList(pageQueryDTO);
                log.info("当前用户是飞行员用户");
                break;
            case CUSTOMER:
                orderMainList = customerAllOrderQueryList(pageQueryDTO);
                log.info("当前用户是B端客户");
                break;
            default:
                break;
        }
        if (CollectionUtil.isEmpty(orderMainList)) {
            return new Page<>();
        }

        // 查询发起人信息
        List<Long> orderInitiatorIds = orderMainList.stream().map(OrderMain::getOrderInitiatorId).toList();
        List<EmEmployees> employeesList = emEmployeesService.obtainEmployeesByIds(orderInitiatorIds);
        Map<Long, EmEmployees> operatorMap = employeesList.stream()
                .collect(Collectors.toMap(EmEmployees::getId, item -> item, (o1, o2) -> o1));

        // 获取所有的路线信息
        List<CpRoute> routes = cpRouteService.obtainAllRoutes();
        Map<Long, CpRoute> routeMap = routes.stream()
                .collect(Collectors.toMap(CpRoute::getId, route -> route));

        // 构建查询结果集
        List<OrderMainPageQueryVO> orderMainPageList = new ArrayList<>();
        for (OrderMain orderMain : orderMainList) {
            OrderMainPageQueryVO pageQueryVO = BeanUtil.copyProperties(orderMain, OrderMainPageQueryVO.class);
            String routeIds = orderMain.getRouteIds();
            // 转换成数组
            String[] routeIdArray = routeIds.split(StrUtil.COMMA);
            StringBuilder routeNameBuilder = new StringBuilder();
            for (String routeIdStr : routeIdArray) {
                CpRoute cpRoute = routeMap.get(Long.valueOf(routeIdStr));
                String name = cpRoute.getName();
                routeNameBuilder.append(name).append(StrUtil.COMMA);
            }
            // 去掉最后一个逗号
            routeNameBuilder.deleteCharAt(routeNameBuilder.length() - 1);
            pageQueryVO.setRouteName(routeNameBuilder.toString());
            EmEmployees emEmployees = operatorMap.get(orderMain.getOrderInitiatorId());
            if (ObjectUtil.isNotNull(emEmployees)) {
                pageQueryVO.setInitiatorPhone(emEmployees.getPhone());
            }
            pageQueryVO.setCustomerPhone(orderMain.getPhone());
            orderMainPageList.add(pageQueryVO);
        }
        // 内存分页
        Page<OrderMainPageQueryVO> pageResult = new Page<>(page.getCurrent(), page.getSize());
        pageResult.setTotal(orderMainPageList.size());
        // 计算分页起始和结束位置
        long start = (page.getCurrent() - 1) * page.getSize();
        long end = Math.min(start + page.getSize(), orderMainPageList.size());
        // 如果起始位置超出了数据总量，则返回空列表
        if (start >= orderMainPageList.size()) {
            pageResult.setRecords(new ArrayList<>());
        } else {
            // 截取当前页数据
            pageResult.setRecords(orderMainPageList.subList((int) start, (int) end));
        }
        return pageResult;
    }

    /**
     * 查询所有订单<客户端>
     *
     * @param pageQueryDTO  {@link OrderMainPageQueryDTO}
     * @return  {@link List<OrderMain>}
     */
    private List<OrderMain> customerAllOrderQueryList(OrderMainPageQueryDTO pageQueryDTO) {
        // 获取当前用户的手机号
        Long currentUserId = SecurityUtils.getCurrentUserId();
        pageQueryDTO.setOrderInitiatorId(null);
        pageQueryDTO.setPhone(null);
        pageQueryDTO.setCustomerId(currentUserId);
        pageQueryDTO.setAttractionId(null);
        return orderMainService.queryAll(pageQueryDTO);
    }

    /**
     * 查询所有订单<飞行员端>
     *
     * @param pageQueryDTO 分页参数
     * @return  {@link List<OrderMain>}
     */
    private List<OrderMain> employeeAllOrderQueryList(OrderMainPageQueryDTO pageQueryDTO) {
        // 获取当前登录人的ID
        Long orderInitiatorId = SecurityUtils.getCurrentUserId();
        pageQueryDTO.setOrderInitiatorId(orderInitiatorId);
        pageQueryDTO.setPhone(null);
        pageQueryDTO.setCustomerId(null);
        pageQueryDTO.setAttractionId(null);
        return orderMainService.obtainOrderList(pageQueryDTO);
    }

    /**
     * 查询所有订单<Admin端>
     *
     * @param pageQueryDTO  {@link OrderMainPageQueryDTO}
     * @return  {@link List<OrderMain>}
     */
    private List<OrderMain> adminAllOrderQueryList(OrderMainPageQueryDTO pageQueryDTO) {
        // 用户角色获取对应的数据（财务、区域、管理员角色）
        // 获取当前角色
        Long currentUserId = SecurityUtils.getCurrentUserId();
        // 根据用户ID获取用户角色
        User user = userService.getById(currentUserId);
        Long userRoleId =userRoleMapper.obtainRoleByUserId(currentUserId);
        // 获取对应的角色等级
        Role role = roleService.getById(userRoleId);
        if (ObjectUtil.isNotNull(role)) {
            Integer level = role.getLevel();
            if (level != null && level == 2) {
                if (ObjectUtil.isNotNull(user.getAreaId())) {
                    pageQueryDTO.setAreaId(user.getAreaId());
                }
            }
        }

        // 处理时间格式
        if (ObjectUtil.isNotNull(pageQueryDTO.getQueryStartTime())) {
            Date start = DateUtil.beginOfDay(pageQueryDTO.getQueryStartTime());
            pageQueryDTO.setQueryStartTime(start);
        }
        if (ObjectUtil.isNotNull(pageQueryDTO.getQueryEndTime())) {
            Date end = DateUtil.endOfDay(pageQueryDTO.getQueryEndTime());
            pageQueryDTO.setQueryEndTime(end);
        }
        List<OrderMain> list = orderMainService.queryAll(pageQueryDTO);
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addOrder(AddOrderDTO addOrderDTO) {

        // 获取当前登录用户（飞行端用户）
        Long orderInitiatorId = SecurityUtils.getCurrentUserId();
        // 新增订单
        OrderMain orderMain = orderMainService.addOrder(buildOrderParam(addOrderDTO, orderInitiatorId));
        // 构建保存操作人信息
        List<OrderOperator> orderOperatorList = buildOrderOperatorParam(addOrderDTO.getOperatorIds(),  orderMain.getId());
        // 批量新增订单操作人
        orderOperatorService.batchAddOrderOperator(orderOperatorList);
    }

    /**
     * 构建新增订单参数
     *
     * @param addOrderDTO  {@link AddOrderDTO}
     * @param orderInitiatorId  当前登录人即为订单发起人
     * @return  {@link OrderMain}
     */
    private OrderMain buildOrderParam(AddOrderDTO addOrderDTO, Long orderInitiatorId) {

        // 生成订单编号《年月日 + 五位数字 Redis 进行自增》
        String datePrefix = LocalDateTime.now().format(DateTimeFormatter.ofPattern(OrderConstant.DATE_PREFIX));
        String serialNumber = redisUtils.increase(OrderRedisConstant.ORDER_NO_PREFIX
                + datePrefix, OrderConstant.ORDER_NO_SEQUENCE);
        String orderNO = OrderConstant.ORDER_NO_PREFIX+ datePrefix + serialNumber;

        // 逗号分隔成字符串存储
        List<Long> routeIds = addOrderDTO.getRouteIds();
        String routeIdsStr = CollectionUtil.join(routeIds, StrUtil.COMMA);

        // 根据景区ID 获取对应的 KG金额, 计算出金额 = 重量 * 金额
        EmScenic scenic = emScenicService.obtainScenicById(addOrderDTO.getAttractionId());
        if (ObjectUtil.isNull(scenic)) {
            throw new BadRequestException("景区不存在");
        }
        BigDecimal price = scenic.getPrice();
        if (ObjectUtil.isNull(price)) {
            throw new BadRequestException("景区重量（kg）配置金额不存在");
        }
        BigDecimal amount = addOrderDTO.getCargoWeight().multiply(price);

        OrderMain orderMain = new OrderMain();
        orderMain.setOrderNo(orderNO);
        orderMain.setOrderInitiatorId(orderInitiatorId);
        orderMain.setOrderType(addOrderDTO.getOrderType());
        orderMain.setPhone(addOrderDTO.getPhone());
        orderMain.setAttractionId(addOrderDTO.getAttractionId());
        orderMain.setCustomerId(addOrderDTO.getCustomerId());
        orderMain.setRouteIds(routeIdsStr);
        orderMain.setCargoWeight(addOrderDTO.getCargoWeight());
        orderMain.setAmount(amount);
        // 订单总金额
        BigDecimal surchargeAmount = addOrderDTO.getSurchargeAmount();
        if (surchargeAmount == null) {
            surchargeAmount = BigDecimal.ZERO;
        }
        BigDecimal totalAmount = amount.add(surchargeAmount);
        orderMain.setTotalAmount(totalAmount);
        orderMain.setSurchargeAmount(addOrderDTO.getSurchargeAmount());
        orderMain.setOrderCreateTime(addOrderDTO.getOrderCreateTime());
        orderMain.setMainOrderStatus(MainOrderStatusEnum.NOT_STARTED.getCode());
        orderMain.setSettlementStatus(OrderSettlementStatusEnum.NOT_SETTLED.getCode());
        orderMain.setAreaId(scenic.getAreaId());
        return orderMain;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addOrderTask(AddOrderTaskDTO orderTaskDTO) {
        // 获取当前登录用户
        Long orderInitiatorId = SecurityUtils.getCurrentUserId();

        // 订单处于完成/取消状态/待确认状态，不允许新增任务
        OrderMain orderMain = orderMainService.obtainOrderMainById(orderTaskDTO.getOrderId());
        if (!Objects.equals(orderMain.getMainOrderStatus(), MainOrderStatusEnum.NOT_STARTED.getCode()) &&
                !Objects.equals(orderMain.getMainOrderStatus(), MainOrderStatusEnum.PROCESSING.getCode())) {
            throw new BadRequestException("当前订单状态处于:"+ MainOrderStatusEnum.getInstance(orderMain.getMainOrderStatus()).getDescription() + "，不允许新增任务");
        }

        // 新建订单飞行任务限制（当前飞行员不能存在任务处于未进行，进行中）
        Long orderId = orderTaskDTO.getOrderId();
        orderDetailService.checkOrderDetail(orderId, orderInitiatorId);

        // 构建任务参数
        OrderDetail orderTask = buildOrderTaskParam(orderTaskDTO, orderInitiatorId);
        // 新增订单飞行任务
        OrderDetail orderDetail = orderDetailService.addOrderDetail(orderTask);

        // 判断是否存在材料
        if (CollectionUtil.isEmpty(orderTaskDTO.getAttachmentMaterialList())) {
            return;
        }
        // 保存材料
        List<AttachmentMaterial> attachmentMaterialList = buildAttachmentMaterialParam(orderTaskDTO, orderDetail.getId());
        attachmentMaterialService.batchAddAttachmentMaterial(attachmentMaterialList);
    }

    /**
     * 构建订单任务参数
     *
     * @param orderTaskDTO  {@link AddOrderTaskDTO}
     * @param orderInitiatorId  当前飞行员ID
     * @return  {@link OrderDetail}
     */
    private OrderDetail buildOrderTaskParam(AddOrderTaskDTO orderTaskDTO, Long orderInitiatorId) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderTaskDTO.getOrderId());
        orderDetail.setDeviceId(orderTaskDTO.getDeviceId());
        orderDetail.setRouteId(orderTaskDTO.getRouteId());
        orderDetail.setCargoWeight(orderTaskDTO.getCargoWeight());
        orderDetail.setOrderItemStatus(OrderTaskStatusEnum.NOT_STARTED.getCode());
        orderDetail.setOperatorId(orderInitiatorId);
        return orderDetail;
    }

    /**
     * 构建保存材料参数
     *
     * @param orderTaskDTO  {@link AddOrderTaskDTO}
     * @param orderDetailId 订单详情ID
     * @return  {@link AttachmentMaterial}
     */
    private List<AttachmentMaterial> buildAttachmentMaterialParam(AddOrderTaskDTO orderTaskDTO, Long orderDetailId) {
        List<AttachmentMaterial> materialList  = new ArrayList<>();
        for (LocalAttachmentMaterialDTO materialDTO : orderTaskDTO.getAttachmentMaterialList()) {
            AttachmentMaterial attachmentMaterial = new AttachmentMaterial();
            attachmentMaterial.setBusinessId(orderDetailId);
            attachmentMaterial.setBusinessType(AttachmentMaterialBusinessTypeEnum.ORDER_TASK_MATERIAL.getCode());
            attachmentMaterial.setFileType(materialDTO.getFileType());
            attachmentMaterial.setSourceFileName(materialDTO.getSourceFileName());
            attachmentMaterial.setNewFileName(materialDTO.getNewFileName());
            attachmentMaterial.setFileSize(materialDTO.getFileSize());
            attachmentMaterial.setFileFullPath(materialDTO.getFileFullPath());
            materialList.add(attachmentMaterial);
        }
        return materialList;
    }

    /**
     * 根据订单ID查询详情
     */
    public OrderAllDetailVO queryOrderDetail(Long id) {
        // 获取订单详情
        OrderMain orderMain = orderMainService.obtainOrderMainById(id);

        Long orderInitiatorId = orderMain.getOrderInitiatorId();
        List<EmEmployees> emEmployeesList = emEmployeesService.list();
        Map<Long, EmEmployees> emEmployeesMap = emEmployeesList.stream().collect( Collectors.toMap(EmEmployees::getId, v -> v));
        EmEmployees emEmployees = emEmployeesMap.get(orderInitiatorId);
        String customerName = cnCustomerService.getById(orderMain.getCustomerId()).getName();

        // 构建订单回显
        OrderAllDetailVO orderAllDetailVO = new OrderAllDetailVO();
        orderAllDetailVO.setId(orderMain.getId());
        orderAllDetailVO.setOrderNo(orderMain.getOrderNo());
        orderAllDetailVO.setOrderType(OrderTypeEnum.getInstance(orderMain.getOrderType()).getDescription());
        orderAllDetailVO.setMainOrderStatus(MainOrderStatusEnum.getInstance(orderMain.getMainOrderStatus()).getDescription());
        orderAllDetailVO.setOrderInitiator(emEmployees.getName());
        orderAllDetailVO.setInitiatorPhone(emEmployees.getPhone());
        orderAllDetailVO.setCustomerName(customerName);
        orderAllDetailVO.setPhone(orderMain.getPhone());
        orderAllDetailVO.setCargoWeight(orderMain.getCargoWeight());
        orderAllDetailVO.setSurchargeAmount(orderMain.getSurchargeAmount());
        orderAllDetailVO.setTotalAmount(orderMain.getTotalAmount());
        orderAllDetailVO.setAmount(orderMain.getAmount());
        orderAllDetailVO.setScenicName(emScenicService.obtainScenicById(orderMain.getAttractionId()).getName());
        orderAllDetailVO.setCustomerId(orderMain.getCustomerId());
        orderAllDetailVO.setOrderInitiatorId(orderMain.getOrderInitiatorId());
        orderAllDetailVO.setAttractionId(orderMain.getAttractionId());

        // 获取路线
        String routeName = obtainRouteName(orderMain, orderAllDetailVO);
        orderAllDetailVO.setRouteName(routeName);
        // 获取该订单下的操作人
        List<OrderOperator> orderOperatorList = orderOperatorService.queryAllByOrderIds(List.of(id));
        orderAllDetailVO.setOperatorIds(orderOperatorList.stream().map(OrderOperator::getOperatorId).toList());
        // 转成map
        StringBuilder nameBuilder = new StringBuilder();
        for (OrderOperator operator : orderOperatorList) {
            Long operatorId = operator.getOperatorId();
            String name = emEmployeesMap.get(operatorId).getName();
            nameBuilder.append(name).append(StrUtil.COMMA);
        }
        // 去掉最后一个逗号
        orderAllDetailVO.setOperatorName(nameBuilder.substring(0, nameBuilder.length() - 1));
        orderAllDetailVO.setOrderCreateTime(orderMain.getOrderCreateTime());
        orderAllDetailVO.setOrderFinishTime(orderMain.getOrderFinishTime());

        // 根据订单id获取任务
        List<OrderDetail> orderDetailList = orderDetailService.queryOrderDetailByOrderId(id);
        if (CollectionUtil.isEmpty(orderDetailList)) {
            return orderAllDetailVO;
        }

        // 获取任务ID集合
        List<Long> taskIdList = orderDetailList.stream().map(OrderDetail::getId).toList();
        //根据任务分别获取材料
        List<String> businessCodeList = new ArrayList<>();
        businessCodeList.add(AttachmentMaterialBusinessTypeEnum.ORDER_TASK_MATERIAL.getCode());
        List<AttachmentMaterial> attachmentMaterialList = attachmentMaterialService.obtainAttachmentMaterialByBusinessIdAndCode(
                taskIdList, businessCodeList);

        // 根据 businessId 进行分组
        if (CollectionUtil.isEmpty(attachmentMaterialList)){
            return new OrderAllDetailVO();
        }
        Map<Long, List<AttachmentMaterial>> attachmentMaterialMap = attachmentMaterialList.stream().
                collect(Collectors.groupingBy(AttachmentMaterial::getBusinessId));

        // 获取所有设备
        List<AircraftDevice> aircraftDeviceList = aircraftDeviceService.list();
        Map<Long, AircraftDevice> aircraftDeviceMap = aircraftDeviceList.stream().
                collect(Collectors.toMap(AircraftDevice::getId, device -> device));

        // 构建返回订单任务参数
        List<OrderTaskDetailVO> orderTaskDetailList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            OrderTaskDetailVO orderTaskDetailVO = new OrderTaskDetailVO();
            orderTaskDetailVO.setId(orderDetail.getId());
            AircraftDevice aircraftDevice = aircraftDeviceMap.get(orderDetail.getDeviceId());
            if (ObjectUtil.isNotNull(aircraftDevice)) {
                orderTaskDetailVO.setDeviceName(aircraftDevice.getName());
            }
            orderTaskDetailVO.setCargoWeight(orderDetail.getCargoWeight());
            EmEmployees employees = emEmployeesMap.get(orderDetail.getOperatorId());
            if (ObjectUtil.isNotNull(employees)) {
                orderTaskDetailVO.setOperatorName(employees.getName());
            }
            OrderTaskStatusEnum orderTaskStatusEnum = OrderTaskStatusEnum.getInstance(orderDetail.getOrderItemStatus());
            orderTaskDetailVO.setOrderItemStatus(orderTaskStatusEnum.getDescription());
            // 获取对应的材料信息
            List<AttachmentMaterial> materialList = attachmentMaterialMap.get(orderDetail.getId());
            if (CollectionUtil.isNotEmpty(materialList)) {
                orderTaskDetailVO.setAttachmentMaterialList(BeanUtil.copyToList(materialList, AttachmentMaterialDTO.class));
            }
            orderTaskDetailList.add(orderTaskDetailVO);
        }
        orderAllDetailVO.setOrderTaskDetailList(orderTaskDetailList);
        return orderAllDetailVO;
    }

    /**
     * 获取路线名称
     *
     * @param orderMain  {@link OrderMain}
     * @param orderAllDetailVO
     * @return  拼接的路线名称
     */
    private String obtainRouteName(OrderMain orderMain, OrderAllDetailVO orderAllDetailVO) {
        String routeIds = orderMain.getRouteIds();
        List<CpRoute> cpRoutes = cpRouteService.obtainAllRoutes();
        Map<Long, CpRoute> routeMap = cpRoutes.stream().collect(Collectors.toMap(CpRoute::getId, route -> route));
        String[] routeIdArray = routeIds.split(StrUtil.COMMA);
        StringBuilder routeNameBuilder = new StringBuilder();
        for (String routeIdStr : routeIdArray) {
            CpRoute cpRoute = routeMap.get(Long.valueOf(routeIdStr));
            String name = cpRoute.getName();
            routeNameBuilder.append(name).append(StrUtil.COMMA);
            orderAllDetailVO.setRouteIds(List.of(cpRoute.getId()));
        }
        // 去掉最后一个逗号
        return routeNameBuilder.substring(0, routeNameBuilder.length() - 1);
    }

    /**
     * 修改订单
     */
    @Transactional(rollbackFor = Exception.class)
    public void editOrder(UpdateOrderDTO updateOrderDTO) {
        // 获取订单详情
        Long orderId = updateOrderDTO.getOrderId();
        OrderMain orderMain = orderMainService.obtainOrderMainById(orderId);
        if (ObjectUtil.isNull(orderMain)) {
            throw new BadRequestException("订单不存在");
        }
        // 判断当前订单状态是否处于未进行中
        if (!orderMain.getMainOrderStatus().equals(MainOrderStatusEnum.NOT_STARTED.getCode())) {
            throw new BadRequestException("当前订单状态不是未进行中，不允许修改");
        }
        // 判断当前登录人、是否为订单发起人，不是则不允许修改
        Long currentId = SecurityUtils.getCurrentUserId();
        if (!currentId.equals(orderMain.getOrderInitiatorId())) {
            throw new BadRequestException("当前登录用户不是订单发起人，不允许修改");
        }
        // 当前若存在订单任务则不允许修改
        List<OrderDetail> orderDetailList = orderDetailService.queryOrderDetailByOrderId(orderId);
        if (CollectionUtil.isNotEmpty(orderDetailList)) {
            throw new BadRequestException("当前订单已存在订单任务，不允许修改");
        }
        // 进行更新订单（附加费变化或者重量变化需要重新计算金额）
        BigDecimal cargoWeight = updateOrderDTO.getCargoWeight();
        // 根据景区ID 获取对应的 KG金额, 计算出金额 = 重量 * 金额
        EmScenic scenic = emScenicService.obtainScenicById(orderMain.getAttractionId());
        if (ObjectUtil.isNull(scenic)) {
            throw new BadRequestException("景区不存在");
        }
        BigDecimal price = scenic.getPrice();
        if (ObjectUtil.isNull(price)) {
            throw new BadRequestException("景区重量（kg）配置金额不存在");
        }
        BigDecimal amount = cargoWeight.multiply(price);
        updateOrderDTO.setTotalAmount(amount.add(updateOrderDTO.getSurchargeAmount()));
        updateOrderDTO.setAmount(amount);
        orderMainService.editOrder(updateOrderDTO);

        // 删除相关的操作人表，进行新增操作
        orderOperatorService.deleteOrderOperatorByOrderId(orderId);
        // 进行新增操作员
        orderOperatorService.batchAddOrderOperator(buildOrderOperatorParam(updateOrderDTO.getOperatorIds(), orderId));
    }

    /**
     * 删除订单
     * @param orderId  订单ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrder(Long orderId) {
        // 获取订单详情
        OrderMain orderMain = orderMainService.obtainOrderMainById(orderId);
        if (ObjectUtil.isNull(orderMain)) {
            throw new BadRequestException("订单不存在");
        }
        // 判断当前订单状态是否处于未进行中
        if (!orderMain.getMainOrderStatus().equals(MainOrderStatusEnum.NOT_STARTED.getCode())) {
            throw new BadRequestException("当前订单状态不是处于未进行中，不允许删除");
        }
        // 判断当前登录人、是否为订单发起人，不是则不允许修改
        Long currentId = SecurityUtils.getCurrentUserId();
        if (!currentId.equals(orderMain.getOrderInitiatorId())) {
            throw new BadRequestException("当前登录用户不是订单发起人，不允许删除订单");
        }
        // 检查是否存在订单任务
        List<OrderDetail> orderDetailList = orderDetailService.queryOrderDetailByOrderId(orderId);
        if (CollectionUtil.isNotEmpty(orderDetailList)) {
            throw new BadRequestException("当前订单存在订单任务，不允许删除");
        }
        // 删除相关记录
        orderMainService.deleteOrderMainById(orderId);
        orderDetailService.deleteOrderDetailByOrderId(orderId);
        orderOperatorService.deleteOrderOperatorByOrderId(orderId);
        attachmentMaterialService.deleteAttachmentMaterialByBusinessId(orderId, AttachmentMaterialBusinessTypeEnum.ORDER_TASK_MATERIAL.getCode());
    }

    /**
     * 构建新增操作员参数
     *
     * @param operatorIds  操作员集合
     * @param orderId  订单ID
     * @return  {@link List<OrderOperator>}
     */
    private List<OrderOperator> buildOrderOperatorParam(List<Long> operatorIds, Long orderId) {
        // 获取当前登录人ID
        Long currentOperatorId = SecurityUtils.getCurrentUserId();
        // 如果操作人不包含在 operatorIds则添加当前登录人ID（默认添加任务发起者为操作人）
        if (!operatorIds.contains(currentOperatorId)) {
            operatorIds.add(currentOperatorId);
        }
        List<OrderOperator> orderOperatorList = new ArrayList<>();
        for (Long operatorId : operatorIds) {
            OrderOperator orderOperator = new OrderOperator();
            orderOperator.setOrderId(orderId);
            orderOperator.setOperatorId(operatorId);
            orderOperatorList.add(orderOperator);
        }
        return orderOperatorList;
    }

    /**
     * 修改订单任务状态
     *
     * @param orderTaskId  订单任务ID
     * @param taskStatus  飞行状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void editOrderTaskStatus(Long orderTaskId, Integer taskStatus) {
        // 获取订单详情
        OrderDetail orderDetail = orderDetailService.obtainOrderDetailById(orderTaskId);
        if (ObjectUtil.isNull(orderDetail)) {
            throw new BadRequestException("订单任务不存在");
        }
        // 判断当前用户是否是订单发起者
        Long currentOperatorId = SecurityUtils.getCurrentUserId();
        if (!currentOperatorId.equals(orderDetail.getOperatorId())) {
            throw new BadRequestException("您没有权限更改此飞行任务状态");
        }
        // 获取当前订单状态的枚举值
        OrderTaskStatusEnum orderTaskStatusEnum = OrderTaskStatusEnum.getInstance(orderDetail.getOrderItemStatus());
        if (ObjectUtil.isNull(orderTaskStatusEnum)) {
            throw new BadRequestException("订单任务状态错误");
        }
        boolean checkStatusTransitionValid = OrderTaskStatusEnum.checkStatusTransitionValid(orderTaskStatusEnum.getCode(), taskStatus);
        if (!checkStatusTransitionValid) {
            return;
        }
        // 进行订单状态变更，飞行任务变更
        Long orderId = orderDetail.getOrderId();
        OrderMain orderMain = orderMainService.obtainOrderMainById(orderId);
        if (ObjectUtil.isNull(orderMain)) {
            throw new BadRequestException("订单不存在,无法更新订单飞行任务状态");
        }
        orderDetailService.updateOrderTaskStatus(orderTaskId, taskStatus);
        if (MainOrderStatusEnum.PROCESSING.getCode().equals(orderMain.getMainOrderStatus())) {
            return;
        }
        // 更新主单状态
        orderMainService.updateOrderStatus(orderId, MainOrderStatusEnum.PROCESSING.getCode());
    }

    /**
     * 删除飞行任务
     *
     * @param orderTaskId  订单任务ID
     */
    public void deleteOrderTask(Long orderTaskId) {
        OrderDetail orderDetail = orderDetailService.obtainOrderDetailById(orderTaskId);
        if (ObjectUtil.isNull(orderDetail)) {
            throw new BadRequestException("订单飞行任务不存在");
        }
        Long orderInitiatorId = SecurityUtils.getCurrentUserId();
        // 判断当前用户是否是订单发起者
        if (!orderInitiatorId.equals(orderDetail.getOperatorId())) {
            throw new BadRequestException("您没有权限删除此订单任务");
        }
        // 判断订单任务是否处于未开始
        if (!OrderTaskStatusEnum.NOT_STARTED.getCode().equals(orderDetail.getOrderItemStatus())) {
            String description = OrderTaskStatusEnum.getInstance(orderDetail.getOrderItemStatus()).getDescription();
            String msg = String.format("订单飞行任务处于[%s]状态，不能进行删除", description);
            throw new BadRequestException(msg);
        }
        orderDetailService.deleteOrderDetailById(orderTaskId);
    }

    /**
     * 生成结算订单
     *
     * @param orderIds  订单ID集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void generateSettlementOrder(List<Long> orderIds) {
        if (CollectionUtil.isEmpty(orderIds)) {
            throw new BadRequestException("请选择要生成结算订单的订单");
        }
        // 验证这些结算订单是否复处于未结算且订单状态为已完成状态
        List<OrderMain> orderMainList= orderMainService.obtainOrderListByOrderIds(orderIds);
        // 检查订单数据
        checkOrderData(orderIds, orderMainList);
        // 按照景区ID进行分组
        Map<Long, List<OrderMain>> attractionGroupMap = orderMainList.stream().collect(Collectors.groupingBy(OrderMain::getAttractionId));
        List<SettlementMain> settlementMainList = new ArrayList<>();

        Long currentUserId = SecurityUtils.getCurrentUserId();
        // 构建结算订单数据
        attractionGroupMap.forEach((attractionId, orderList) -> {
            // 按照订单创建时间进行升序牌排序
            orderList.sort(Comparator.comparing(OrderMain::getCreateTime));
            SettlementMain settlementMain = new SettlementMain();
            settlementMain.setAttractionId(attractionId);
            // 生成订单编号《年月日 + 五位数字 Redis 进行自增》
            String datePrefix = LocalDateTime.now().format(DateTimeFormatter.ofPattern(OrderConstant.DATE_PREFIX));
            String serialNumber = redisUtils.increase(OrderRedisConstant.SETTLEMENT_NO_PREFIX
                    + datePrefix, OrderConstant.ORDER_NO_SEQUENCE);
            String batchNo = OrderConstant.SETTLEMENT_BATCH_NO_PREFIX + datePrefix + serialNumber;
            settlementMain.setBatchNo(batchNo);
            settlementMain.setOperatorId(currentUserId);
            settlementMain.setSettlementStatus(OrderSettlementStatusEnum.NOT_SETTLED.getCode());
            Date startOrderCreateTime = orderList.get(0).getOrderCreateTime();
            String startOrderCreateTimeStr = DateUtil.format(startOrderCreateTime, OrderConstant.DATE_TIME_PREFIX);
            String settlementTimeScope = StrUtil.EMPTY;
            if (orderList.size() == 1) {
                settlementTimeScope = startOrderCreateTimeStr + "~" + startOrderCreateTimeStr;
            } else {
                Date lastOrderCreateTime = orderList.get(orderList.size() - 1).getOrderCreateTime();
                String lastOrderCreateTimeStr = DateUtil.format(lastOrderCreateTime, OrderConstant.DATE_TIME_PREFIX);
                settlementTimeScope = startOrderCreateTimeStr + "~" + lastOrderCreateTimeStr;
            }
            settlementMain.setSettlementTimeScope(settlementTimeScope);
            settlementMainList.add(settlementMain);
        });
        // 批量新增结算订单
        List<SettlementMain> settlementMains = settlementMainService.batchInsert(settlementMainList);
        // 构建结算订单明细数据
        List<SettlementDetail> settlementDetailList = buildSettlementDetail(settlementMains, attractionGroupMap);
        settlementDetailService.batchInsert(settlementDetailList);
        // 更新结算订单状态（更新为结算中）
        orderMainService.updateSettlementStatus(orderIds, OrderSettlementStatusEnum.SETTLING.getCode());
    }

    /**
     * 检查订单数据是否合法
     */
    private void checkOrderData(List<Long> orderIds, List<OrderMain> orderMainList) {
        if (CollectionUtil.isEmpty(orderMainList)) {
            throw new BadRequestException("订单不存在");
        }
        // 待优化（提示完整错误信息）
        for (OrderMain orderMain : orderMainList) {
            if (!orderIds.contains(orderMain.getId())) {
                throw new BadRequestException("订单不存在");
            }
            // 判断订单是否处于未结算且订单状态为已完成状态
            if (!OrderSettlementStatusEnum.NOT_SETTLED.getCode().equals(orderMain.getSettlementStatus())
                    || !MainOrderStatusEnum.COMPLETED.getCode().equals(orderMain.getMainOrderStatus())) {
                throw new BadRequestException("订单状态错误，无法生成结算订单");
            }
        }
    }

    /**
     * 构建结算订单明细数据
     *
     * @param settlementMains 结算订单集合
     * @param attractionGroupMap 景区ID分组的订单集合
     * @return  {@link List<SettlementDetail> }
     */
    private List<SettlementDetail> buildSettlementDetail(List<SettlementMain> settlementMains, Map<Long, List<OrderMain>> attractionGroupMap) {
        List<SettlementDetail> settlementDetailList = new ArrayList<>();
        for (SettlementMain settlementMain : settlementMains) {
            List<OrderMain> orderMainList = attractionGroupMap.get(settlementMain.getAttractionId());
            for (OrderMain orderMain : orderMainList) {
                SettlementDetail settlementDetail = BeanUtil.copyProperties(orderMain, SettlementDetail.class);
                settlementDetail.setSettlementMainId(settlementMain.getId());
                settlementDetail.setOrderId(orderMain.getId());
                // 此时结算状态为结算中
                settlementDetail.setSettlementStatus(OrderSettlementStatusEnum.SETTLING.getCode());
                // 自动生成的时间变为空
                settlementDetail.setId(null);
                settlementDetail.setCreateTime(null);
                settlementDetail.setCreateBy(null);
                settlementDetail.setUpdateTime(null);
                settlementDetail.setUpdateBy(null);
                settlementDetail.setDelFlag(null);
                settlementDetailList.add(settlementDetail);
            }
        }
        return settlementDetailList;
    }

    /**
     * 打印结算单数据
     *
     * @param settlementOrderId  结算订单ID
     * @return  {@link PrintSettlementOrderDataVO}
     */
    public PrintSettlementOrderDataVO printSettlementOrder(Long settlementOrderId) {
        // 查询结算订单是否存在
        SettlementMain settlementMain = settlementMainService.obtainSettlementMainById(settlementOrderId);
        if (ObjectUtil.isNull(settlementMain)) {
            throw new BadRequestException("结算订单不存在");
        }
        // 获取结算订单明细
        List<SettlementDetail> settlementDetailList = settlementDetailService.obtainDetailBySettlementOrderId(settlementOrderId);
        if (CollectionUtil.isEmpty(settlementDetailList)) {
            throw new BadRequestException("结算订单明细不存在");
        }
        // 获取所有客户
        List<CnCustomer> cnCustomerList = cnCustomerService.list();
        // 根据ID 转换成map
        Map<Long, CnCustomer> customerMap = cnCustomerList.stream().collect(Collectors.toMap(CnCustomer::getId, v -> v));

        // 构建数据
        PrintSettlementOrderDataVO printSettlement = new PrintSettlementOrderDataVO();
        printSettlement.setBatchNo(settlementMain.getBatchNo());
        printSettlement.setSettlementTimeScope(settlementMain.getSettlementTimeScope());
        // 获取景区
        EmScenic scenic = emScenicService.obtainScenicById(settlementMain.getAttractionId());
        if (ObjectUtil.isNotNull(scenic)) {
            printSettlement.setClientName(scenic.getName());
        }
        // 获取重量
        printSettlement.setCargoWeight(settlementDetailList.stream().map(SettlementDetail::getCargoWeight).reduce(BigDecimal.ZERO, BigDecimal::add));
        BigDecimal totalAmount = settlementDetailList.stream().map(SettlementDetail::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 保留小数点2位
        totalAmount = totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        // 金额转换成中文
        printSettlement.setTotalAmountUpper(NumberChineseFormatter.format(totalAmount, true, true));
        printSettlement.setTotalAmount(totalAmount);

        // 构建List
        List<SettlementDetailVO> settlementDetailVOList = new ArrayList<>();
        for (SettlementDetail settlementDetail : settlementDetailList) {
            SettlementDetailVO settlementDetailVO = new SettlementDetailVO();
            settlementDetailVO.setOrderNo(settlementDetail.getOrderNo());
            settlementDetailVO.setOrderCreateTime(settlementDetail.getOrderCreateTime());
            settlementDetailVO.setCargoWeight(settlementDetail.getCargoWeight());
            settlementDetailVO.setTotalAmount(settlementDetail.getTotalAmount());
            // 客户ID
            CnCustomer cnCustomer = customerMap.get(settlementDetail.getCustomerId());
            if (ObjectUtil.isNotNull(cnCustomer)) {
                settlementDetailVO.setConfirmPerson(cnCustomer.getName());
            }
            settlementDetailVOList.add(settlementDetailVO);
        }
        printSettlement.setSettlementDetailList(settlementDetailVOList);
        return printSettlement;
    }

    /**
     *  获取结算订单详情
     *
     * @param settlementOrderId 结算订单ID
     * @return  List<SettlementDetail>
     */
    public List<SettlementDetail> querySettlementOrderDetail(Long settlementOrderId) {
        return settlementDetailService.obtainDetailBySettlementOrderId(settlementOrderId);
    }

    /**
     * 更新结算订单状态
     *
     * @param settlementOrderId  结算订单ID
     * @param settlementOrderStatus  {@link SettlementStatusEnum} 更新的状态枚举值
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSettlementOrderStatus(Long settlementOrderId, Integer settlementOrderStatus) {
        SettlementMain settlementMain = settlementMainService.obtainSettlementMainById(settlementOrderId);
        if (ObjectUtil.isNull(settlementMain)) {
            throw new BadRequestException("结算订单不存在");
        }
        // 结算单状态相同或者结算完成，则不处理
        if (settlementOrderStatus.equals(settlementMain.getSettlementStatus())
                || SettlementStatusEnum.CONFIRMED.getCode().equals(settlementMain.getSettlementStatus())) {
            return;
        }
        // 如果结算单状态本身为取消则不许再处理
        if (SettlementStatusEnum.CANCELED.getCode().equals(settlementMain.getSettlementStatus())) {
            throw new BadRequestException("结算单已取消，无法变更状态");
        }
        // 查询出所有明细
        List<SettlementDetail> settlementDetailList = settlementDetailService.obtainDetailBySettlementOrderId(settlementOrderId);

        // 获取所有订单ID
        List<Long> orderIds = settlementDetailList.stream().map(SettlementDetail::getOrderId).toList();
        // 获取id
        List<Long> ids = settlementDetailList.stream().map(SettlementDetail::getId).toList();
        // 更新结算单的状态
        settlementMainService.updateSettlementStatus(settlementOrderId, settlementOrderStatus);
        // 订单等于完成或取消才去更新结算单的状态
        if (SettlementStatusEnum.SETTLING.getCode().equals(settlementOrderStatus) ||
                SettlementStatusEnum.SETTLED.getCode().equals(settlementOrderStatus)) {
            return;
        }
        Integer updateStatus = null;
        if (SettlementStatusEnum.CANCELED.getCode().equals(settlementOrderStatus)) {
            updateStatus = OrderSettlementStatusEnum.NOT_SETTLED.getCode();
        } else {
            updateStatus = OrderSettlementStatusEnum.SETTLED.getCode();
        }
        // 更新订单表的状态
        orderMainService.updateSettlementStatus(orderIds, updateStatus);
        // 更新结算订单状态
        settlementDetailService.updateSettlementOrderStatus(ids, updateStatus);
    }

    /**
     * 完成订单
     * @param orderId  订单ID
     */
    public void completeOrder(Long orderId) {
        // 查询订单信息
        OrderMain orderMain = orderMainService.obtainOrderMainById(orderId);
        // 获取当前用户（根据不同的登录类型，处理不同的逻辑）
        UserTypeEnum currentUserType = SecurityUtils.getCurrentUserType();
        switch (currentUserType) {
            case CUSTOMER:
                customerCompleteOrder(orderMain);
                break;
            case EMPLOYEES:
                employeesCompleteOrder(orderMain);
                break;
            default:
                break;
        }
        // 是否存在飞行任务（至少存在一个飞行失败或者完成的，才能点击完成，且不能存在未开始，进行中的）
        List<OrderDetail> orderDetailList = orderDetailService.queryOrderDetailByOrderId(orderId);
        if (CollectionUtil.isEmpty(orderDetailList)) {
            throw new BadRequestException("该订单不存在飞行任务，无法完成订单");
        }
        // 订单不能存在未开始或者进行中的飞行任务
        boolean hasFlightTask = orderDetailList.stream().anyMatch(orderDetail -> {
            Integer flightTaskStatus = orderDetail.getOrderItemStatus();
            return OrderTaskStatusEnum.NOT_STARTED.getCode().equals(flightTaskStatus)
                    || OrderTaskStatusEnum.PROCESSING.getCode().equals(flightTaskStatus);
        });
        if (hasFlightTask) {
            throw new BadRequestException("订单存在未开始或者进行中的飞行任务，无法完成");
        }
        OrderMain updateOrderMain = new OrderMain();
        updateOrderMain.setId(orderId);
        updateOrderMain.setOrderFinishTime(new Date());
        if (currentUserType.equals(UserTypeEnum.EMPLOYEES)) {
            updateOrderMain.setMainOrderStatus(MainOrderStatusEnum.WAIT_CONFIRM.getCode());
            updateOrderMain.setConfirmTime(new Date());
        } else {
            updateOrderMain.setMainOrderStatus(MainOrderStatusEnum.COMPLETED.getCode());
        }
        orderMainService.finishMainOrder(updateOrderMain);
    }

    /**
     * 客户端完成订单
     *
     * @param orderMain  {@link OrderMain}
     */
    private void customerCompleteOrder(OrderMain orderMain) {
        // TODO 客户端不限制
    }

    /**
     * 飞行端完成订单
     *
     * @param orderMain  {@link OrderMain}
     */
    private void employeesCompleteOrder(OrderMain orderMain) {
        // 飞行员端只能由发起人才能完成
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!orderMain.getOrderInitiatorId().equals(currentUserId)) {
            throw new BadRequestException("订单不属于当前用户,无法完成");
        }
    }

    /**
     * 生成结算订单列表
     *
     * @param orderIds  订单集合
     * @return  {@link List<GenerateSettlementOrderConfirmVO>} 待确认结算订单列表
     */
    public List<GenerateSettlementOrderConfirmVO> generateSettlementOrderConfirmList(List<Long> orderIds) {
        if (CollectionUtil.isEmpty(orderIds)) {
            throw new BadRequestException("请选择要生成结算订单的订单");
        }
        // 验证这些结算订单是否复处于未结算且订单状态为已完成状态
        List<OrderMain> orderMainList= orderMainService.obtainOrderListByOrderIds(orderIds);
        // 检查订单数据
        this.checkOrderData(orderIds, orderMainList);

        List<GenerateSettlementOrderConfirmVO> orderConfirmList = new ArrayList<>();
        // 按照景点分组
        Map<Long, List<OrderMain>> attractionGroupMap = orderMainList.stream().collect(Collectors.groupingBy(OrderMain::getAttractionId));
        attractionGroupMap.forEach((attractionId, orderList) -> {
            GenerateSettlementOrderConfirmVO orderConfirmVO = new GenerateSettlementOrderConfirmVO();
            orderConfirmVO.setAttractionId(attractionId);
            // 计算重量 相加
            orderConfirmVO.setCargoWeight(orderList.stream().map(OrderMain::getCargoWeight).reduce(BigDecimal.ZERO, BigDecimal::add));
            // 计算总金额 相加
            orderConfirmVO.setTotalAmount(orderList.stream().map(OrderMain::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            orderConfirmList.add(orderConfirmVO);
        });
        return orderConfirmList;
    }

    /**
     *  根据订单 ID 获取对应的路线下拉
     *
     * @param orderId  订单ID
     * @return  List<KeyValueEntity>
     */
    public List<KeyValueEntity> obtainRouteListByOrderId(Long orderId) {
        // 根据订单ID 获取订单结果
        OrderMain orderMain = orderMainService.obtainOrderMainById(orderId);
        if (ObjectUtil.isNull(orderMain)) {
            throw new BadRequestException("订单不存在");
        }
        if (StrUtil.isBlank(orderMain.getRouteIds())) {
            throw new BadRequestException("订单未指定路线");
        }
        // 获取所有路线
        List<CpRoute> routeList = cpRouteService.obtainAllRoutes();
        Map<Long, CpRoute> routeMap = routeList.stream().collect(Collectors.toMap(CpRoute::getId, route -> route));
        String routeIds = orderMain.getRouteIds();

        // 逗号分割成数组
        String[] routeIdArray = routeIds.split(StrUtil.COMMA);
        List<KeyValueEntity> keyValueEntityList = new ArrayList<>();
        for (String routeId : routeIdArray) {
            Long routeIdLong = Long.valueOf(routeId);
            CpRoute route = routeMap.get(routeIdLong);
            if (ObjectUtil.isNull(route)) {
                continue;
            }
            KeyValueEntity keyValueEntity = KeyValueEntity.builder()
                    .key(routeIdLong)
                    .value(route.getName())
                    .build();
            keyValueEntityList.add(keyValueEntity);
        }

        return keyValueEntityList;
    }
}
