package com.gxwebsoft.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.cms.entity.CmsProduct;
import com.gxwebsoft.cms.mapper.CmsProductMapper;
import com.gxwebsoft.cms.param.CmsProductParam;
import com.gxwebsoft.cms.service.CmsProductService;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 产品Service实现
 *
 * @author WorkBuddy
 * @since 2026-07-17
 */
@Service
public class CmsProductServiceImpl extends ServiceImpl<CmsProductMapper, CmsProduct> implements CmsProductService {

    @Override
    public PageResult<CmsProduct> pageRel(CmsProductParam param) {
        // 聚合场景：传入 categoryIds 时忽略单值 categoryId，避免 AND 冲突
        if (StrUtil.isNotBlank(param.getCategoryIds())) {
            param.setCategoryId(null);
        }
        PageParam<CmsProduct, CmsProductParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        QueryWrapper<CmsProduct> wrapper = page.getWrapper();
        if (StrUtil.isNotBlank(param.getKeywords())) {
            wrapper.and(w -> w.like("product_name", param.getKeywords())
                    .or().like("summary", param.getKeywords()));
        }
        IPage<CmsProduct> result = page(page, page.getOrderWrapper(wrapper));
        return new PageResult<>(result.getRecords(), result.getTotal());
    }

    @Override
    public List<CmsProduct> listRel(CmsProductParam param) {
        PageParam<CmsProduct, CmsProductParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        QueryWrapper<CmsProduct> wrapper = page.getWrapper();
        if (StrUtil.isNotBlank(param.getKeywords())) {
            wrapper.and(w -> w.like("product_name", param.getKeywords())
                    .or().like("summary", param.getKeywords()));
        }
        return list(page.getOrderWrapper(wrapper));
    }

    @Override
    public CmsProduct getByIdRel(Integer productId) {
        return getById(productId);
    }
}
