package com.njcn.device.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.pojo.po.Line;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author: cdf
 * @CreateTime: 2026-06-13
 * @Description:
 */
@Component
@RequiredArgsConstructor
public class LineSortHelper {

    private final LineMapper lineMapper;

    /**
     * 获取同一父节点下的最大 sort 值 + 1
     * @param level 层级
     * @return 下一个可用的 sort 值
     */
    public Integer getNextSort(Integer level) {
        LambdaQueryWrapper<Line> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Line::getState, DataStateEnum.ENABLE.getCode())
                .eq(Line::getLevel,level)
                .orderByDesc(Line::getSort)
                .last("limit 1");
        Line maxSortLine = lineMapper.selectOne(wrapper);

        if (Objects.nonNull(maxSortLine) && Objects.nonNull(maxSortLine.getSort())) {
            return maxSortLine.getSort() + 1;
        }
        return 0;
    }


    public void handleSort(Integer level, Integer sort,Line line) {
        int lastSort;
        if (Objects.isNull(sort) || sort == 0) {
            lastSort = getNextSort(level);
        }else {
            lastSort = sort;
        }
        line.setSort(lastSort);
    }


    public Integer handleSortBatch(Integer currentSort, Line line) {
        line.setSort(currentSort);
        return currentSort + 1;
    }

}
