package com.nokia.hb.service;

import com.nokia.common.R;
import com.nokia.hb.dao.entity.PerCfgArea;
import com.nokia.hb.dao.mapper.PerCfgAreaMapper;
import com.nokia.hb.pojo.TreeNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class AreaService {
    private final PerCfgAreaMapper perCfgAreaMapper;

    public AreaService(PerCfgAreaMapper perCfgAreaMapper) {
        this.perCfgAreaMapper = perCfgAreaMapper;
    }

    public R<List<TreeNode>> initTreeCitys() {
        List<PerCfgArea> areas = perCfgAreaMapper.all();
        Map<String, List<TreeNode>> m = new HashMap<>();
        TreeNode allTree = new TreeNode("地市选择", "地市选择", new ArrayList<>());
        allTree.setSpread(true);
        List<TreeNode> res = new ArrayList<>();
        res.add(allTree);
        areas.forEach(a -> {
            String city = a.getCity();
            String quxian = a.getQuxian();
            String id = city + quxian;
            TreeNode t = new TreeNode(quxian, id, null);
            m.putIfAbsent(city, new ArrayList<>());
            m.get(city).add(t);
        });
        m.forEach((key, value) -> allTree.getChildren().add(new TreeNode(key, key, value)));
        return R.ok(res);
    }
}
