package org.springblade.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wn.common.validator.Validator;
import org.springblade.modules.app.dto.CityDTO;
import org.apache.commons.lang3.StringUtils;
import org.springblade.modules.app.constant.ErrorCode;
import org.springblade.modules.app.entity.CityDO;
import org.springblade.modules.app.mapper.CityMapper;
import org.springblade.modules.app.service.ICityService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;


@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, CityDO> implements ICityService {

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<CityDTO> listCityDTO(CityDTO cityDTO) {
        Validator.notNull(cityDTO, ErrorCode.PARAM_DATA_NULL);
        LambdaQueryWrapper<CityDO> queryWrapper = new LambdaQueryWrapper();
        if (null != cityDTO) {
            if (cityDTO.getId() != null) {
                queryWrapper.eq(CityDO::getId, cityDTO.getFid());
            }
            if (StringUtils.isNotBlank(cityDTO.getName())) {
                queryWrapper.like(CityDO::getName, cityDTO.getName());
            }
            if (cityDTO.getFid() != null) {
                queryWrapper.eq(CityDO::getFid, cityDTO.getFid());
            }
            if (cityDTO.getLevel() != null) {
                queryWrapper.eq(CityDO::getLevel, cityDTO.getLevel());
            }
        }
        List<CityDO> cityDOS = baseMapper.selectList(queryWrapper);
        return CollectionUtils.isEmpty(cityDOS) ? null : CityDO.copyListTo(cityDOS, CityDTO.class);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public CityDTO getCityDTO(CityDTO cityDTO) {
        Validator.notNull(cityDTO, ErrorCode.PARAM_DATA_NULL);
        LambdaQueryWrapper<CityDO> queryWrapper = new LambdaQueryWrapper();
        if (cityDTO.getId() != null) {
            queryWrapper.eq(CityDO::getId, cityDTO.getId());
        }
        if (StringUtils.isNotBlank(cityDTO.getName())) {
            queryWrapper.like(CityDO::getName, cityDTO.getName());
        }
        if (cityDTO.getFid() != null) {
            queryWrapper.eq(CityDO::getFid, cityDTO.getFid());
        }
        if (cityDTO.getLevel() != null) {
            queryWrapper.eq(CityDO::getLevel, cityDTO.getLevel());
        }

        CityDO cityDO = baseMapper.selectOne(queryWrapper);
        return cityDO == null ? null : cityDO.copyTo(CityDTO.class);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public CityDTO matchCity(CityDTO cityDTO) {
        return baseMapper.matchCity(cityDTO);
    }

}

