package com.hys.app.mapper.system;

import com.hys.app.framework.context.user.AdminUserContext;
import com.hys.app.model.erp.dos.WarehouseOutDO;
import com.hys.app.model.system.dto.DeptQueryParams;
import com.hys.app.model.system.dos.DeptDO;
import com.hys.app.framework.database.mybatisplus.base.BaseMapperX;
import com.hys.app.framework.database.mybatisplus.wrapper.LambdaQueryWrapperX;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Collection;
import java.util.List;

@Mapper
public interface DeptMapper extends BaseMapperX<DeptDO> {

    default List<DeptDO> selectList(DeptQueryParams reqVO) {
        return selectList(new LambdaQueryWrapperX<DeptDO>()
                .likeIfPresent(DeptDO::getName, reqVO.getName())
                .eqIfPresent(DeptDO::getCompanyId, AdminUserContext.getCompanyId())
                .inIfPresent(DeptDO::getId, reqVO.getDeptIds()));
    }

    default DeptDO selectByParentIdAndName(Long parentId, String name) {
        return selectOne(DeptDO::getParentId, parentId, DeptDO::getName, name);
    }

    default Long selectCountByParentId(Long parentId) {
        return selectCount(DeptDO::getParentId, parentId);
    }

    default List<DeptDO> selectListByParentId(Collection<Long> parentIds) {
        return selectList(DeptDO::getParentId, parentIds);
    }

    @Select("WITH RECURSIVE sub_departments AS (" +
            "SELECT * FROM erp_company_dept WHERE id = #{deptId} " +
            "UNION ALL " +
            "SELECT d.* FROM erp_company_dept d " +
            "INNER JOIN sub_departments sd ON d.parent_id = sd.id" +
            ") " +
            "SELECT * FROM sub_departments")
    List<DeptDO> getAllSubDept(@Param("deptId") Long deptId);
}
