package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.mapper.ShopGoodsMapper;
import com.gxwebsoft.shop.service.ShopGoodsService;
import com.gxwebsoft.shop.entity.ShopGoods;
import com.gxwebsoft.shop.param.ShopGoodsParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 商品Service实现
 *
 * @author 科技小王子
 * @since 2025-04-24 20:52:13
 */
@Slf4j
@Service
public class ShopGoodsServiceImpl extends ServiceImpl<ShopGoodsMapper, ShopGoods> implements ShopGoodsService {

    @Override
    public PageResult<ShopGoods> pageRel(ShopGoodsParam param) {
        PageParam<ShopGoods, ShopGoodsParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ShopGoods> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<ShopGoods> listRel(ShopGoodsParam param) {
        List<ShopGoods> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<ShopGoods, ShopGoodsParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public ShopGoods getByIdRel(Integer goodsId) {
        ShopGoodsParam param = new ShopGoodsParam();
        param.setGoodsId(goodsId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @InterceptorIgnore(tenantLine = "true")
    @Override
    public boolean addSaleCount(Integer goodsId, Integer saleCount) {
        try {
            if (goodsId == null || saleCount == null || saleCount <= 0) {
                log.warn("累加商品销量参数无效 - 商品ID: {}, 销量: {}", goodsId, saleCount);
                return false;
            }

            int affectedRows = baseMapper.addSaleCount(goodsId, saleCount);
            boolean success = affectedRows > 0;

            if (success) {
                log.info("商品销量累加成功 - 商品ID: {}, 累加数量: {}, 影响行数: {}", goodsId, saleCount, affectedRows);
            } else {
                log.warn("商品销量累加失败 - 商品ID: {}, 累加数量: {}, 影响行数: {}", goodsId, saleCount, affectedRows);
            }

            return success;
        } catch (Exception e) {
            log.error("累加商品销量异常 - 商品ID: {}, 累加数量: {}", goodsId, saleCount, e);
            return false;
        }
    }

}
