package com.cslg.ppa.service;

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.cslg.ppa.common.core.auth.Response;
import com.cslg.ppa.dto.CategoryDTO;
import com.cslg.ppa.dto.CategoryIdDTO;
import com.cslg.ppa.dto.SelectCategoryListDTO;
import com.cslg.ppa.entity.BaseEntity;
import com.cslg.ppa.entity.Category;
import com.cslg.ppa.entity.commom.Records;
import com.cslg.ppa.mapper.CategoryMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class CategoryService extends ServiceImpl<CategoryMapper, Category> {

    @Autowired
    private CategoryMapper categoryMapper;

    public String selectCategoryList(SelectCategoryListDTO vo) {
        Records records = new Records();
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        List<Category> categoryList = new ArrayList<>();
        if (vo.getPageNum()!= null && vo.getPageSize() != null) {
            Page<Category> page = new Page<>(vo.getPageNum(), vo.getPageSize());
            Page<Category> categoryPage = categoryMapper.selectPage(page, wrapper);
            categoryList = categoryPage.getRecords();
            long total = categoryPage.getTotal();
            records.setCurrent(vo.getPageNum());
            records.setTotal(total);
            records.setSize(vo.getPageSize());
        } else {
            categoryList = categoryMapper.selectList(wrapper);
        }
        records.setData(categoryList);
        return Response.success(records);
    }


    public Integer addOrEditCategory(CategoryDTO vo) {
        Integer categoryId = vo.getCategoryId();
        if (ObjectUtils.isNotEmpty(categoryId)) {
            Category category = categoryMapper.selectById(categoryId);
            category.setName(vo.getName());
            category.updateById();
        } else {
            Category category = new Category();
            category.setName(vo.getName());
            category.insert();
            categoryId = category.getId();
        }
        return categoryId;
    }

    public void deleteCategory(CategoryIdDTO vo) {
        List<Integer> categoryIds = vo.getCategoryIds();
        if (!CollectionUtils.isEmpty(categoryIds)) {
            categoryMapper.deleteBatchIds(categoryIds);
        }
    }
}
