package com.enterprise.manage.modules.system.service.impl;

import com.enterprise.manage.common.base.BaseServiceImpl;
import com.enterprise.manage.modules.system.domain.po.Org;
import com.enterprise.manage.modules.system.mapper.OrgMapper;
import com.enterprise.manage.modules.system.service.IOrgService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * system organizational service implementation class
 *
 * @author PeiZhi Guo
 * 2022-7-11 12:59
 */
@Service
public class OrgServiceImpl extends BaseServiceImpl<OrgMapper, Org> implements IOrgService {

    @Override
    public boolean orgNameUniqueCheck(Long id,Long cityId, Long areaId, String name) {
        return baseMapper.orgNameUniqueCheck(id,cityId, areaId,name) > 0;
    }

    @Override
    public List<Org> querySelectTree() {
        List<Org> list = new ArrayList<>();
        // 添加根菜单
        Org sysOrg = new Org();
        sysOrg.setId(0L);
        sysOrg.setName("组织机构");
        sysOrg.setChildren(children(sysOrg.getId(), baseMapper.selectTreeAll()));
        list.add(sysOrg);
        return list;
    }

    @Override
    public boolean queryChildren(Long id) {
        return baseMapper.selectChildren(id) > 0;
    }

    /*
     * 递归获取部门 tree
     */
    private List<Org> children(Long parentId, List<Org> orgs) {
        List<Org> list = new ArrayList<>();
        for (Org menu : orgs) {
            if (parentId.equals(menu.getParentId())) {
                menu.setChildren(children(menu.getId(), orgs));
                list.add(menu);
            }
        }
        return list;
    }
}
