package com.hys.app.service.erp.impl;

import cn.hutool.core.collection.CollUtil;
import com.hys.app.framework.database.WebPage;
import com.hys.app.framework.database.mybatisplus.base.BaseServiceImpl;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.mapper.erp.GoodsLabelRelationMapper;
import com.hys.app.model.erp.dos.GoodsLabelDO;
import com.hys.app.model.erp.dos.GoodsLabelRelationDO;
import com.hys.app.model.erp.dto.GoodsLabelRelationDTO;
import com.hys.app.model.erp.dto.GoodsLabelRelationQueryParams;
import com.hys.app.model.erp.vo.GoodsLabelRelationVO;
import com.hys.app.service.erp.GoodsLabelManager;
import com.hys.app.service.erp.GoodsLabelRelationManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品标签-商品关联表业务层实现
 *
 * @author 张崧
 * 2024-03-20 16:29:17
 */
@Service
public class GoodsLabelRelationManagerImpl extends BaseServiceImpl<GoodsLabelRelationMapper, GoodsLabelRelationDO> implements GoodsLabelRelationManager {

    @Autowired
    private GoodsLabelManager goodsLabelManager;

    @Override
    public WebPage<GoodsLabelRelationVO> list(GoodsLabelRelationQueryParams queryParams) {
        return baseMapper.selectPage(queryParams);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void relationGoods(GoodsLabelRelationDTO goodsLabelRelationDTO) {
        GoodsLabelDO goodsLabelDO = goodsLabelManager.getById(goodsLabelRelationDTO.getLabelId());
        if (goodsLabelDO == null) {
            throw new ServiceException("标签不存在");
        }

        // 先删除
        lambdaUpdate().eq(GoodsLabelRelationDO::getLabelId, goodsLabelRelationDTO.getLabelId()).remove();

        // 再新增
        List<GoodsLabelRelationDO> list = goodsLabelRelationDTO.getGoodsIds().stream().map(goodsId -> {
            GoodsLabelRelationDO relationDO = new GoodsLabelRelationDO();
            relationDO.setLabelId(goodsLabelRelationDTO.getLabelId());
            relationDO.setGoodsId(goodsId);
            return relationDO;
        }).collect(Collectors.toList());
        super.saveBatch(list);
    }

    @Override
    public List<GoodsLabelRelationDO> listByGoodsIds(List<Long> goodsIds) {
        if (CollUtil.isEmpty(goodsIds)) {
            return Collections.emptyList();
        }
        return lambdaQuery()
                .in(GoodsLabelRelationDO::getGoodsId, goodsIds)
                .list();
    }

    @Override
    public void deleteByLabelIds(List<Long> labelIds) {
        lambdaUpdate().in(GoodsLabelRelationDO::getLabelId, labelIds).remove();
    }

}

