package com.zksy.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.base.domain.ManholeBase;
import com.zksy.base.dto.ManholePageInDTO;
import com.zksy.base.mapper.ManholeBaseMapper;
import com.zksy.base.service.ManholeBaseService;
import com.zksy.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ManholeBaseServiceImpl extends ServiceImpl<ManholeBaseMapper, ManholeBase>
        implements ManholeBaseService {

    @Override
    public Page<ManholeBase> findByPage(ManholePageInDTO dto) {
        Page<ManholeBase> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<ManholeBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(dto.getManholeName() != null && !dto.getManholeName().isEmpty(), ManholeBase::getManholeName, dto.getManholeName());
        wrapper.like(dto.getManholeCode() != null && !dto.getManholeCode().isEmpty(), ManholeBase::getManholeCode, dto.getManholeCode());
        wrapper.eq(dto.getStatus() != null && !dto.getStatus().isEmpty(), ManholeBase::getStatus, dto.getStatus());
        wrapper.orderByDesc(ManholeBase::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public List<ManholeBase> getOptions() {
        LambdaQueryWrapper<ManholeBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ManholeBase::getManholeId, ManholeBase::getManholeName, ManholeBase::getManholeCode);
        wrapper.orderByAsc(ManholeBase::getManholeName);
        return this.list(wrapper);
    }

    @Override
    public boolean saveWithCheck(ManholeBase entity) {
        LambdaQueryWrapper<ManholeBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManholeBase::getManholeCode, entity.getManholeCode());
        if (this.count(wrapper) > 0) {
            throw new ServiceException("窨井编码已存在：" + entity.getManholeCode());
        }
        entity.setCreateTime(LocalDateTime.now());
        return this.save(entity);
    }

    @Override
    public boolean updateWithCheck(ManholeBase entity) {
        if (this.getById(entity.getManholeId()) == null) {
            throw new ServiceException("窨井信息不存在：" + entity.getManholeId());
        }
        LambdaQueryWrapper<ManholeBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManholeBase::getManholeCode, entity.getManholeCode())
                .ne(ManholeBase::getManholeId, entity.getManholeId());
        if (this.count(wrapper) > 0) {
            throw new ServiceException("窨井编码已被使用：" + entity.getManholeCode());
        }
        return this.updateById(entity);
    }
}
