package org.springblade.manager.service.impl;


import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.manager.dto.ArchiveTreeDTO;
import org.springblade.manager.entity.ArchiveTree;
import org.springblade.manager.entity.WbsTree;
import org.springblade.manager.mapper.ArchiveTreeMapper;
import org.springblade.manager.service.IArchiveTreeService;
import org.springblade.manager.vo.ArchiveTreeVO;
import org.springblade.manager.vo.WbsTreeVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 服务实现类
 *
 * @author liuyc
 * @since 2022-05-16
 */
@Service
public class ArchiveTreeServiceImpl
        extends BaseServiceImpl<ArchiveTreeMapper, ArchiveTree>
        implements IArchiveTreeService {


    @Override
    public List<ArchiveTreeVO> lazyTree(String roleTypeNum, String tenantId, Long parentId) {
        if (AuthUtil.isAdministrator()) {
            tenantId = StringPool.EMPTY;
        }
        return ForestNodeMerger.merge(baseMapper.lazyTree(roleTypeNum, tenantId, parentId));
    }

    @Override
    public List<ArchiveTreeVO> tree(String roleTypeNum, String tenantId) {
        return ForestNodeMerger.merge(baseMapper.tree(roleTypeNum, tenantId));
    }

    @Override
    public boolean submit(ArchiveTreeDTO archiveTreeDTO) {
        //TODO 条件判断有误，当parentId=0时，Ancestors为null
        if (Func.isEmpty(archiveTreeDTO.getParentId())) {
            archiveTreeDTO.setTenantId(AuthUtil.getTenantId());
            archiveTreeDTO.setParentId(BladeConstant.TOP_PARENT_ID);
            archiveTreeDTO.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
        }
        if (archiveTreeDTO.getParentId() > 0) {
            ArchiveTree parent = getById(archiveTreeDTO.getParentId());
            if (Func.toLong(archiveTreeDTO.getParentId()) == Func.toLong(archiveTreeDTO.getId())) {
                throw new ServiceException("父节点不可选择自身!");
            }
            archiveTreeDTO.setTenantId(parent.getTenantId());
            String ancestors = parent.getAncestors() + StringPool.COMMA + archiveTreeDTO.getParentId();
            archiveTreeDTO.setAncestors(ancestors);
        }
        archiveTreeDTO.setIsDeleted(BladeConstant.DB_NOT_DELETED);
        return saveOrUpdate(archiveTreeDTO);
    }


}
