package com.njcn.gather.steady.datavie.service.impl;

import com.njcn.gather.steady.datavie.mapper.SteadyDataViewLedgerMapper;
import com.njcn.gather.steady.datavie.pojo.bo.SteadyDataViewLedgerRowBO;
import com.njcn.gather.steady.datavie.pojo.vo.SteadyDataViewLedgerNodeVO;
import com.njcn.gather.steady.datavie.service.SteadyDataViewLedgerService;
import com.njcn.gather.tool.addledger.pojo.constant.AddLedgerConst;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 稳态趋势台账树服务实现。
 */
@Service
@RequiredArgsConstructor
public class SteadyDataViewLedgerServiceImpl implements SteadyDataViewLedgerService {

    private final SteadyDataViewLedgerMapper ledgerMapper;

    @Override
    public List<SteadyDataViewLedgerNodeVO> listLedgerTree(String keyword) {
        List<SteadyDataViewLedgerRowBO> rows = ledgerMapper.selectLedgerTree(trimToNull(keyword));
        Map<String, SteadyDataViewLedgerNodeVO> nodeMap = new LinkedHashMap<String, SteadyDataViewLedgerNodeVO>();
        for (SteadyDataViewLedgerRowBO row : rows) {
            SteadyDataViewLedgerNodeVO node = new SteadyDataViewLedgerNodeVO();
            node.setId(row.getId());
            node.setParentId(row.getParentId());
            node.setName(row.getName());
            node.setLevel(row.getLevel());
            node.setSort(row.getSort());
            node.setDeviceCount(row.getDeviceCount() == null ? 0 : row.getDeviceCount());
            node.setLineCount(row.getLineCount() == null ? 0 : row.getLineCount());
            node.setSelectable(AddLedgerConst.LEVEL_EQUIPMENT == row.getLevel() || AddLedgerConst.LEVEL_LINE == row.getLevel());
            nodeMap.put(node.getId(), node);
        }
        List<SteadyDataViewLedgerNodeVO> roots = new ArrayList<SteadyDataViewLedgerNodeVO>();
        for (SteadyDataViewLedgerNodeVO node : nodeMap.values()) {
            SteadyDataViewLedgerNodeVO parent = nodeMap.get(node.getParentId());
            if (parent == null || AddLedgerConst.ROOT_PARENT_ID.equals(node.getParentId())) {
                roots.add(node);
            } else {
                parent.getChildren().add(node);
            }
        }
        sortTree(roots);
        return roots;
    }

    private void sortTree(List<SteadyDataViewLedgerNodeVO> nodes) {
        nodes.sort(Comparator.comparing(SteadyDataViewLedgerNodeVO::getSort, Comparator.nullsLast(Integer::compareTo))
                .thenComparing(SteadyDataViewLedgerNodeVO::getName, Comparator.nullsLast(String::compareTo)));
        for (SteadyDataViewLedgerNodeVO node : nodes) {
            sortTree(node.getChildren());
        }
    }

    private String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
}
