package com.gitee.sop.admin.service.sys;

import com.gitee.fastmybatis.core.query.LambdaQuery;
import com.gitee.fastmybatis.core.util.TreeUtil;
import com.gitee.sop.admin.common.dto.StatusUpdateDTO;
import com.gitee.sop.admin.common.exception.BizException;
import com.gitee.sop.admin.common.support.ServiceSupport;
import com.gitee.sop.admin.common.util.CopyUtil;
import com.gitee.sop.admin.dao.entity.SysDept;
import com.gitee.sop.admin.dao.mapper.SysDeptMapper;
import com.gitee.sop.admin.service.sys.dto.SysDeptDTO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * @author 六如
 */
@Service
public class SysDeptService implements ServiceSupport<SysDept, SysDeptMapper> {

    public Long addDept(SysDept sysDept) {
        long count = this.query()
                .eq(SysDept::getParentId, 0)
                .getCount();
        if (count > 0 && Objects.equals(sysDept.getParentId(), 0L)) {
            throw new BizException("只能有一个根节点");
        }
        this.save(sysDept);
        return sysDept.getId();
    }

    public List<SysDeptDTO> listTree(LambdaQuery<SysDept> query) {
        List<SysDept> list = this.list(query);
        List<SysDeptDTO> sysDeptList = CopyUtil.copyList(list, SysDeptDTO::new);
        return TreeUtil.convertTree(sysDeptList, 0L);
    }


    /**
     * 修改状态
     *
     * @param statusUpdateDTO 修改值
     * @return 返回影响行数
     */
    public int updateStatus(StatusUpdateDTO statusUpdateDTO) {
        return this.query()
                .eq(SysDept::getId, statusUpdateDTO.getId())
                .set(SysDept::getStatus, statusUpdateDTO.getStatus())
                .update();
    }
}
