package com.mortals.xhx.base.system.menu.model;

import java.lang.reflect.Type;
import java.util.List;
import java.util.ArrayList;
import com.mortals.xhx.base.system.menu.model.vo.MenuVo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.io.Serializable;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import org.springframework.util.ObjectUtils;

/**
* 菜单信息业务前端映射树结构实体类
*
* @author zxfei
* @date 2024-09-06
*/
@Data
public class MenuTreeSelect  implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
    * 节点ID
    */
    private Long id;

    /**
    * 父节点ID
    */
    private Long parentId;

    /**
    * 节点名称
    */
    private String label;

    /**
    * 子节点
    */
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<MenuTreeSelect> children;

    public MenuTreeSelect() {};

    public MenuTreeSelect(MenuEntity entity) {
        this.id = entity.getId();
        this.parentId = entity.getParentId();
        this.label = entity.getName();
        if(!ObjectUtils.isEmpty(entity.getChildren())){
            this.children = entity.getChildren().stream().map(MenuTreeSelect::new).collect(Collectors.toList());
        }
    }

    // 反序列化器
    public  class Deserializer implements ObjectDeserializer {
        @Override
        public MenuTreeSelect deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            MenuTreeSelect node = new MenuTreeSelect();
            JSONObject jsonObject = parser.parseObject();
            node.setId(jsonObject.getLong("id"));
            node.setLabel(jsonObject.getString("label"));
            JSONArray jsonArray = jsonObject.getJSONArray("children");
            List<MenuTreeSelect> children = new ArrayList<>();
            if(!ObjectUtils.isEmpty(jsonArray)){
                for (int i = 0; i < jsonArray.size(); i++) {
                    MenuTreeSelect child = JSON.parseObject(jsonArray.getJSONObject(i).toJSONString(), MenuTreeSelect.class);
                    children.add(child);
                }
            }
            node.setChildren(children);
            return node;
        }

        @Override
        public int getFastMatchToken() {
            return JSONToken.LBRACE;
        }
    }

}