package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.entity.MerchantCategory;
import com.gxwebsoft.shop.mapper.MerchantMapper;
import com.gxwebsoft.shop.service.*;
import com.gxwebsoft.shop.entity.Merchant;
import com.gxwebsoft.shop.param.MerchantParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 商户Service实现
 *
 * @author 科技小王子
 * @since 2024-04-05 00:03:54
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private MerchantCategoryService merchantCategoryService;

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

    @Override
    public List<Merchant> listRel(MerchantParam param) {
        if (param.getTopMerchantCategoryId() != null) {
            List<MerchantCategory> categoryList = merchantCategoryService.listByParentId(param.getTopMerchantCategoryId());
            List<Integer> categoryIds = new ArrayList<>();
            if (!categoryList.isEmpty()) {
                categoryIds = categoryList.stream().map(MerchantCategory::getCategoryId).toList();
                param.setMerchantCategoryIds(categoryIds);
            }else return new ArrayList<>();
        }
        List<Merchant> list = baseMapper.selectListRel(param);
        for (Merchant merchant : list) {
            if (param.getWithOrderNum() != null && param.getWithOrderNum()) {
                merchant.setOrderNum(orderGoodsService.countByMerchant(merchant.getMerchantId()));
            }
        }
        // 排序
        PageParam<Merchant, MerchantParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Merchant getByIdRel(Integer merchantId) {
        MerchantParam param = new MerchantParam();
        param.setMerchantId(merchantId);
        return param.getOne(baseMapper.selectListRel(param));
    }

}
