package com.ningdatech.pmapi.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.pmapi.sys.convert.RegionConverter;
import com.ningdatech.pmapi.sys.mapper.RegionMapper;
import com.ningdatech.pmapi.sys.model.dto.RegionDTO;
import com.ningdatech.pmapi.sys.model.entity.Region;
import com.ningdatech.pmapi.sys.service.IRegionService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zpf
 * @since 2023-1-18
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {

    @Override
    public List<RegionDTO> all() {
        return CollUtils.convert(list(), RegionConverter::toRegionDTO);
    }

    @Override
    public Region getOne(String regionCode, int regionLevel) {
        return getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getRegionCode, regionCode)
                .eq(Region::getRegionLevel, regionLevel));
    }

    @Override
    public List<RegionDTO> listGeLevel(int regionLevel) {
        List<Region> regionsByLevel = lambdaQuery().ne(Region::getId, -1)
                .le(Region::getRegionLevel, regionLevel).list();
        return CollUtils.convert(regionsByLevel, RegionConverter::toRegionDTO);
    }

    @Override
    public boolean isParentRegion(Long regionId) {
        return baseMapper.exists(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getParentId, regionId)
                .eq(Region::getDeleted, false));
    }

    @Override
    public Long getRegionIdByParentIdWithSameRegionCode(Long parentId, String regionCode) {
        return baseMapper.selectOne(Wrappers.lambdaQuery(Region.class)
                        .eq(Region::getParentId, parentId)
                        .eq(Region::getRegionCode, regionCode)
                        .eq(Region::getDeleted, false))
                .getId();
    }


}
