package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.entity.Banner;
import com.zhentao.mapper.BannerMapper;
import com.zhentao.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl implements BannerService {
    
    @Autowired
    private BannerMapper bannerMapper;
    
    @Override
    public Page<Banner> getBannerList(Integer page, Integer pageSize, String keyword) {
        Page<Banner> bannerPage = new Page<>(page, pageSize);
        QueryWrapper<Banner> queryWrapper = new QueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like("title", keyword)
                       .or()
                       .like("subtitle", keyword);
        }
        
        // 按排序和创建时间排序
        queryWrapper.orderByAsc("sort_order")
                   .orderByDesc("created_at");
        
        return bannerMapper.selectPage(bannerPage, queryWrapper);
    }
    
    @Override
    public Banner getBannerById(Integer bannerId) {
        return bannerMapper.selectById(bannerId);
    }
    
    @Override
    public boolean createBanner(Banner banner) {
        banner.setCreatedAt(LocalDateTime.now());
        banner.setUpdatedAt(LocalDateTime.now());
        return bannerMapper.insert(banner) > 0;
    }
    
    @Override
    public boolean updateBanner(Banner banner) {
        banner.setUpdatedAt(LocalDateTime.now());
        return bannerMapper.updateById(banner) > 0;
    }
    
    @Override
    public boolean deleteBanner(Integer bannerId) {
        return bannerMapper.deleteById(bannerId) > 0;
    }
}

