package com.nbclass.szxgl.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nbclass.szxgl.mapper.ProjectClientMapper;
import com.nbclass.szxgl.model.ProjectClient;
import com.nbclass.szxgl.service.ProjectClientService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author leiyun
 * @Date 2021/3/11 19:03
 */
@Service
public class ProjectClientServiceImpl implements ProjectClientService {

    @Resource
    private ProjectClientMapper mapper;

    @Override
    public JSONArray getTreeList() {
        return getTreeList("0"); // 顶级ID为0
    }


    private JSONArray getTreeList(String ParentId) {
        JSONArray retArray = new JSONArray();
        List<ProjectClient> list = mapper.getTreeList(ParentId);
        if(list == null || list.isEmpty())return retArray;
        for(ProjectClient client : list){
            JSONObject obj = (JSONObject) JSONObject.toJSON(client);
            JSONArray arrayChild = new JSONArray();
            if(StringUtils.isNotBlank(client.getId()) && "0".equals(ParentId)){ // 为了性能，暂时只查二级，不查二级以下的子集，后台录入数据也只添加二级机构
                arrayChild = getTreeList(client.getId());
                //if(array2!=null && !array2.isEmpty())obj.put("children", array2); // 给前端空的arrayChild
            }
            obj.put("children", arrayChild);
            retArray.add(obj);
        }
        return retArray;
    }

    @Override
    public String getNamesById(String id){
        String names = "";
        ProjectClient entity = mapper.getNameById(id);
        if(entity != null){
            names = entity.getName();
            if(StringUtils.isNotBlank(entity.getParentId()) && !"0".equals(entity.getParentId())){
                entity = mapper.getNameById(entity.getParentId());
                if(entity != null)names = entity.getName() + " - " + names ;
            }
        }
        return names;
    }

}
