package com.hotwj.platform.common.vo;

import lombok.Data;

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

@Data
public class AddressVo {
    private Long id;
    private String label;
    private String value;
    private List<AddressVo> children;

    public static List<AddressVo> buildTree(List<AddressVo> list) {
        Map<String, AddressVo> map = new HashMap<>();
        List<AddressVo> roots = new ArrayList<>();
        for (AddressVo vo : list) {
            if (vo != null && vo.getValue() != null) {
                map.put(vo.getValue(), vo);
            }
        }
        for (AddressVo vo : list) {
            if (vo == null) {
                continue;
            }
            String code = vo.getValue();
            String parent = parentCode(code);
            AddressVo p = parent == null ? null : map.get(parent);
            if (p == null) {
                roots.add(vo);
            } else {
                List<AddressVo> c = p.getChildren();
                if (c == null) {
                    c = new ArrayList<>();
                    p.setChildren(c);
                }
                c.add(vo);
            }
        }
        return roots;
    }

    private static String parentCode(String code) {
        if (code == null) {
            return null;
        }
        String c = code.trim();
        if (c.length() == 6) {
            if (c.endsWith("0000")) {
                return null;
            }
            if (c.endsWith("00")) {
                return c.substring(0, 2) + "0000";
            }
            return c.substring(0, 4) + "00";
        }
        return null;
    }
}
