package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysTag;
import org.dromara.system.domain.bo.SysTagBo;
import org.dromara.system.domain.vo.SysTagVo;
import org.dromara.system.mapper.SysTagMapper;
import org.dromara.system.service.ISysTagService;
import org.springframework.stereotype.Service;

import java.util.Collection;

@RequiredArgsConstructor
@Service
public class SysTagServiceImpl implements ISysTagService {
    private final SysTagMapper baseMapper;

    @Override
    public TableDataInfo<SysTagVo> queryPageList(SysTagBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysTag> lqw = buildQueryWrapper(bo);
        Page<SysTagVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public SysTagVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public Boolean insertByBo(SysTagBo bo) {
        SysTag add = MapstructUtils.convert(bo, SysTag.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(SysTagBo bo) {
        SysTag update = MapstructUtils.convert(bo, SysTag.class);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    private LambdaQueryWrapper<SysTag> buildQueryWrapper(SysTagBo bo) {
        LambdaQueryWrapper<SysTag> lqw = Wrappers.lambdaQuery();
        lqw.like(ObjectUtil.isNotNull(bo.getName()), SysTag::getName, bo.getName());
        lqw.eq(ObjectUtil.isNotNull(bo.getStatus()), SysTag::getStatus, bo.getStatus());
        return lqw;
    }
}
