package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.mapper.MerchantCategoryMapper;
import com.gxwebsoft.shop.service.MerchantCategoryService;
import com.gxwebsoft.shop.entity.MerchantCategory;
import com.gxwebsoft.shop.param.MerchantCategoryParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

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

/**
 * 商家分类Service实现
 *
 * @author 科技小王子
 * @since 2024-09-30 13:05:32
 */
@Service
public class MerchantCategoryServiceImpl extends ServiceImpl<MerchantCategoryMapper, MerchantCategory> implements MerchantCategoryService {

    @Override
    public PageResult<MerchantCategory> pageRel(MerchantCategoryParam param) {
        PageParam<MerchantCategory, MerchantCategoryParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<MerchantCategory> list = baseMapper.selectPageRel(page, param);
        for (MerchantCategory item : list) {
            if (item.getParentId() != null) {
                item.setParent(baseMapper.selectById(item.getParentId()));
            }
        }
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<MerchantCategory> listRel(MerchantCategoryParam param) {
        List<MerchantCategory> list = list(
                new LambdaQueryWrapper<MerchantCategory>()
                        .eq(MerchantCategory::getParentId, 0)
        );
        if (!list.isEmpty()) {
            for (MerchantCategory item : list) {
                item.setChildren(listByParentId(item.getCategoryId()));
            }
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public MerchantCategory getByIdRel(Integer categoryId) {
        MerchantCategoryParam param = new MerchantCategoryParam();
        param.setCategoryId(categoryId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public List<MerchantCategory> listByParentId(Integer parentId) {
        return list(
                new LambdaQueryWrapper<MerchantCategory>()
                        .eq(MerchantCategory::getParentId, parentId)
        );
    }

}
