package com.willalp.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.common.core.domain.TreeEntity;
import com.willalp.common.core.mapper.BaseTreeMapper;
import com.willalp.common.core.service.ITreeCommonService;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
public class TreeCommonServiceImpl<M extends BaseTreeMapper<T>, T extends TreeEntity>
        extends ServiceImpl<M, T> implements ITreeCommonService<T> {

    @Override
    public T getById(Serializable id) {
        return baseMapper.selectByTreeId(id);
    }

    @Override
    public List<T> selectTreeList(Wrapper<T> wrapper) {
        List<T> content = baseMapper.selectTreeList(wrapper);
        return content;
    }


    @Override
    public boolean save(T entity) {
        if (entity.getParentId() != null && entity.getParentId().equals("0")) {
            T parent = getById(entity.getParentId());
            entity.setParentId(Long.valueOf(parent.getId()));
            entity.setAncestors(parent.makeSelfAsNewParentIds());
        } else {
            entity.setParentId(null);
        }
        return super.save(entity);
    }

    @Override
    public boolean updateById(T entity) {
        if (entity.getParentId() != null && entity.getParentId().equals("0")) {
            T parent = getById(entity.getParentId());
            updateSelftAndChild(entity, parent.getId(), parent.makeSelfAsNewParentIds());
        } else {
            entity.setParentId(null);
            updateSelftAndChild(entity, "0", "0,");
        }
        return true;
    }


    private void updateSelftAndChild(T entity, String newParentId, String newParentIds) {
        T oldEntity = getById(entity.getId());
        String oldChildrenParentIds = oldEntity.makeSelfAsNewParentIds();
        entity.setParentId(Long.valueOf(newParentId));
        entity.setAncestors(newParentIds);
        super.updateById(entity);
        String newChildrenParentIds = entity.makeSelfAsNewParentIds();
        baseMapper.updateSunTreeParentIds(newChildrenParentIds, oldChildrenParentIds);
    }


    @Override
    public boolean removeById(Serializable id) {
        T entity = getById(id);
        baseMapper.deleteSunTree(entity.makeSelfAsNewParentIds());
        return super.removeById(id);
    }

}
