package com.ibeetl.admin.core.web;

import cn.hutool.core.util.StrUtil;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.model.ElTreeData;
import com.ibeetl.admin.core.service.CoreDictService;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("**/core/dicts")
@RestController
public class CoreDictElController {

  @Autowired
  CoreDictService coreDictService;

  @GetMapping("/getDictTree")
  public JsonResult<List<ElTreeData>> getDictTree(Long parentId, String type) {

    if (StrUtil.isBlank(type) && parentId == null) {
      return JsonResult.failMessage("parentId and type should have at least one.");
    }
    List<CoreDict> childDictList = coreDictService.findChildrenNodes(parentId, type);
    return JsonResult.success(coreDictToElCascaderData(childDictList));
  }

  /**
   * .将字典树转成element树组件的格式
   *
   * @return List<ElCascaderData>
   * @author 一日看尽长安花
   */
  private List<ElTreeData> coreDictToElCascaderData(List<CoreDict> coreDicts) {

    List<ElTreeData> elCascaderDatas = new ArrayList<ElTreeData>(coreDicts.size());
    for (CoreDict dict : coreDicts) {
      ElTreeData data = new ElTreeData();
      data.setId(dict.getId());
      data.setLabel(dict.getName());
      data.setValue(dict.getValue());
      List<ElTreeData> children = coreDictToElCascaderData(dict.getChildren());
      data.setChildren(children);
      elCascaderDatas.add(data);
    }
    return elCascaderDatas.isEmpty() ? null : elCascaderDatas;
  }

}
