
package com.netwisd.biz.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.netwisd.biz.demo.entity.Product;
import com.netwisd.biz.demo.mapper.ProductMapper;
import com.netwisd.biz.demo.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.github.dozermapper.core.Mapper;
import com.netwisd.common.core.util.DozerUtils;
import com.netwisd.biz.demo.dto.ProductDto;
import com.netwisd.biz.demo.vo.ProductVo;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @Description 商品
 * @author incoder@netwisd.com
 * @date 2024-04-30 16:07:27
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private final Mapper dozerMapper;

    /**
    * 单表简单查询操作
    * @param productDto
    * @return
    */
    @Override
    public Page<ProductVo> page(ProductDto productDto) {
        Page<ProductVo> pageVo = DozerUtils.mapPage(dozerMapper, super.page(productDto.getPage(),query(productDto)), ProductVo.class);
        log.debug("查询条数:"+pageVo.getTotal());
        return pageVo;
    }

    /**
     * 查询条件构造器
     * @param productDto
     * @return
     */
    public LambdaQueryWrapper<Product> query(ProductDto productDto){
        return Wrappers.<Product>lambdaQuery().apply(StrUtil.isNotEmpty( productDto.getDataPermissionSql()), productDto.getDataPermissionSql());
    }

    /**
     * 通过ID查询实体
     * @param id
     * @return
     */
    @Override
    public ProductVo get(Long id) {
        Product product = Optional.ofNullable(super.getById(id)).orElse(null);
        return ObjectUtil.isNotEmpty(product) ? dozerMapper.map(product,ProductVo.class) : null;
    }

    /**
    * 保存实体
    * @param productDto
    * @return
    */
    @Transactional
    @Override
    public ProductVo save(ProductDto productDto) {
        return super.save(dozerMapper.map(productDto,Product.class)) ? dozerMapper.map(productDto,ProductVo.class) : null;
    }

    /**
    * 修改实体
    * @param productDto
    * @return
    */
    @Transactional
    @Override
    public ProductVo update(ProductDto productDto) {
        productDto.setUpdateTime(LocalDateTime.now());
        return super.updateById(dozerMapper.map(productDto,Product.class)) ? dozerMapper.map(productDto,ProductVo.class) : null;
    }

    /**
     * 通过ID删除
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Boolean delete(Long id) {
        return super.removeById(id);
    }
}
