package com.testor.module.sys.service.impl;

import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.module.sys.service.TOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author rsq
 * @program zlmy_boot
 * @return
 **/
@Service
public class TOrgServiceImpl implements TOrgService {


    @Autowired
    private SysOrgService sysOrgService;

    @Override
    public SysOrg getRegionalCompany(String orgId) {
        return findParentWithLevel(orgId, new BigDecimal(2));
    }


    public SysOrg findParentWithLevel(String orgId, BigDecimal desiredLevel) {
        SysOrg org = sysOrgService.getById(orgId);

        if (org != null) {
            String parentId = org.getParentId();
            BigDecimal parentLevel = org.getTreeLevel();

            if (parentLevel.compareTo(desiredLevel) == 0) {
                return org;
            } else if (parentLevel.compareTo(desiredLevel) > 0 && parentId != null) {
                return findParentWithLevel(parentId, desiredLevel);
            }
        }
        return null;
    }

}
