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

import com.njcn.gather.steady.datavie.component.SteadyTrendIndicatorCatalog;
import com.njcn.gather.steady.datavie.pojo.bo.SteadyTrendIndicatorDefinitionBO;
import com.njcn.gather.steady.datavie.pojo.vo.SteadyDataViewIndicatorNodeVO;
import com.njcn.gather.steady.datavie.service.SteadyDataViewIndicatorService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 稳态趋势指标服务实现。
 */
@Service
@RequiredArgsConstructor
public class SteadyDataViewIndicatorServiceImpl implements SteadyDataViewIndicatorService {

    private final SteadyTrendIndicatorCatalog indicatorCatalog;

    @Override
    public List<SteadyDataViewIndicatorNodeVO> listIndicatorTree() {
        Map<String, SteadyDataViewIndicatorNodeVO> groupMap = new LinkedHashMap<String, SteadyDataViewIndicatorNodeVO>();
        for (SteadyTrendIndicatorDefinitionBO indicator : indicatorCatalog.listIndicators()) {
            SteadyDataViewIndicatorNodeVO groupNode = groupMap.get(indicator.getGroupCode());
            if (groupNode == null) {
                groupNode = new SteadyDataViewIndicatorNodeVO();
                groupNode.setId(indicator.getGroupCode());
                groupNode.setName(indicator.getGroupName());
                groupNode.setGroupCode(indicator.getGroupCode());
                groupNode.setSelectable(false);
                groupMap.put(indicator.getGroupCode(), groupNode);
            }
            groupNode.getChildren().add(buildIndicatorNode(indicator, groupNode.getId()));
        }
        return new ArrayList<SteadyDataViewIndicatorNodeVO>(groupMap.values());
    }

    private SteadyDataViewIndicatorNodeVO buildIndicatorNode(SteadyTrendIndicatorDefinitionBO indicator, String parentId) {
        SteadyDataViewIndicatorNodeVO node = new SteadyDataViewIndicatorNodeVO();
        node.setId(indicator.getIndicatorCode());
        node.setParentId(parentId);
        node.setName(indicator.getName());
        node.setGroupCode(indicator.getGroupCode());
        node.setIndicatorCode(indicator.getIndicatorCode());
        node.setTableName(indicator.getTableName());
        node.setPhaseCodes(new ArrayList<String>(indicator.getPhaseCodes()));
        node.setSeriesFields(new ArrayList<com.njcn.gather.steady.datavie.pojo.bo.SteadyTrendSeriesFieldBO>(indicator.getSeriesFields()));
        node.setSupportStats(new ArrayList<String>(indicator.getSupportStats()));
        node.setHarmonic(indicator.getHarmonic());
        node.setHarmonicOrderStart(indicator.getHarmonicOrderStart());
        node.setHarmonicOrderEnd(indicator.getHarmonicOrderEnd());
        node.setUnit(indicator.getUnit());
        node.setSelectable(true);
        return node;
    }
}
