package com.ruoyi.tjfx.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.tjfx.common.PageResponse;
import com.ruoyi.tjfx.mapper.CategoryMapper;
import com.ruoyi.tjfx.service.CategoryService;
import com.ruoyi.tjfx.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> getAllSimple() {
        return categoryMapper.selectList(null);
    }

    @Override
    public List<Category> listAll() {
        return categoryMapper.selectList(null);
    }

    @Override
    public Category getById(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public void add(Category category) {
        categoryMapper.insert(category);
    }

    @Override
    public void update(Long id, Category category) {
        category.setId(id);
        categoryMapper.updateById(category);
    }

    @Override
    public void delete(Long id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public void addBatch(List<Category> categorys) {
        if (categorys != null && !categorys.isEmpty()) {
            for (Category category : categorys) {
                categoryMapper.insert(category);
            }
        }
    }

    @Override
    public PageResponse<Category> getPage(Integer page, Integer pageSize, String name) {
        // 创建分页对象
        Page<Category> pageParam = new Page<>(page, pageSize);

        // 构建查询条件
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByDesc("id");

        // 执行分页查询
        IPage<Category> pageResult = categoryMapper.selectPage(pageParam, queryWrapper);

        // 构建分页响应
        PageResponse.Pagination pagination = new PageResponse.Pagination(
                pageResult.getTotal(), page, pageSize);

        return new PageResponse<>(pageResult.getRecords(), pagination);
    }
}
