package com.unis.base.server.service;

import com.unis.base.server.dao.CcsbtzjsmxDao;
import com.unis.user.common.vo.org.OrgainzeVO;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

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

/**
 * @Classname OrgainzeService
 * @Description 组织结构
 * @Date 2024/1/18 10:50
 * @Created by rising123sun
 */
@Service
public class OrgainzeService {

    @Resource
    private CcsbtzjsmxDao ccsbtzjsmxDao;

    @Cacheable(value = "organizations")
    public OrgainzeVO getOrganization() {
        String orgCode = "LS001";
        OrgainzeVO orgainzeDTO = ccsbtzjsmxDao.findByOrgCodeAndStateCode(orgCode);
        if (orgainzeDTO == null) {
            return null;
        } else {
            List<OrgainzeVO> treeDataList = new ArrayList<>();
            String orgLevel = "10180007,10180008,10180005";
            List<OrgainzeVO> list = ccsbtzjsmxDao.findByParentCodeAndStateCode(orgCode, orgLevel);
            for (OrgainzeVO departmentPO : list) {
                OrgainzeVO tree = this.getTree(departmentPO.getOrgCode());
                treeDataList.add(tree);
            }
            orgainzeDTO.setChildren(treeDataList);
        }
        // 把orgainzeDTO当中的自节点orgCode为LS001020，LS001021剔除
        List<OrgainzeVO> children = orgainzeDTO.getChildren();
        List<OrgainzeVO> children1 = new ArrayList<>();
        for (OrgainzeVO orgainzeVO : children) {
            if (!"LS001020".equals(orgainzeVO.getOrgCode()) && !"LS001021".equals(orgainzeVO.getOrgCode())) {
                children1.add(orgainzeVO);
            }
        }
        orgainzeDTO.setChildren(children1);
        return orgainzeDTO;
    }

    public OrgainzeVO getTree(String orgCode) {
        // 递归查询所有子节点，以及子节点的子节点直到没有子节点为止
        OrgainzeVO orgainzeDTO = ccsbtzjsmxDao.findByOrgCodeAndStateCode(orgCode);
        if (orgainzeDTO == null) {
            return null;
        } else {
            List<OrgainzeVO> treeDataList = new ArrayList<>();
            String orgLevel = "10180009,10180008";
            List<OrgainzeVO> list = ccsbtzjsmxDao.findByParentCodeAndStateCode(orgCode, orgLevel);
            for (OrgainzeVO departmentPO : list) {
                OrgainzeVO tree = this.getTree(departmentPO.getOrgCode());
                treeDataList.add(tree);
            }
            orgainzeDTO.setChildren(treeDataList);
        }
        return orgainzeDTO;
    }

}
