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

import com.hys.app.converter.erp.GoodsLabelConverter;
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.GoodsLabelMapper;
import com.hys.app.model.erp.dos.GoodsLabelDO;
import com.hys.app.model.erp.dto.GoodsLabelDTO;
import com.hys.app.model.erp.dto.GoodsLabelQueryParams;
import com.hys.app.model.erp.vo.GoodsLabelVO;
import com.hys.app.service.erp.GoodsLabelManager;
import com.hys.app.service.erp.GoodsLabelRelationManager;
import com.hys.app.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品标签业务层实现
 *
 * @author 张崧
 * 2024-03-20 16:23:19
 */
@Service
public class GoodsLabelManagerImpl extends BaseServiceImpl<GoodsLabelMapper, GoodsLabelDO> implements GoodsLabelManager {

    @Autowired
    private GoodsLabelConverter converter;

    @Autowired
    private GoodsLabelRelationManager goodsLabelRelationManager;

    @Override
    public WebPage<GoodsLabelVO> list(GoodsLabelQueryParams queryParams) {
        WebPage<GoodsLabelDO> page = baseMapper.selectPage(queryParams);
        return converter.convertPage(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsLabelDTO goodsLabelDTO) {
        // 校验参数
        checkParams(goodsLabelDTO);

        // 保存
        GoodsLabelDO goodsLabelDO = converter.convert(goodsLabelDTO);
        save(goodsLabelDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(GoodsLabelDTO goodsLabelDTO) {
        // 校验参数
        checkParams(goodsLabelDTO);

        // 更新
        GoodsLabelDO goodsLabelDO = converter.convert(goodsLabelDTO);
        updateById(goodsLabelDO);
    }

    @Override
    public GoodsLabelVO getDetail(Long id) {
        GoodsLabelDO goodsLabelDO = getById(id);
        return converter.convert(goodsLabelDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        removeBatchByIds(ids);
        goodsLabelRelationManager.deleteByLabelIds(ids);
    }

    private void checkParams(GoodsLabelDTO goodsLabelDTO) {
        if (ValidateUtil.checkRepeat(baseMapper, GoodsLabelDO::getName, goodsLabelDTO.getName(), GoodsLabelDO::getId, goodsLabelDTO.getId())) {
            throw new ServiceException("标签名称已存在");
        }
    }
}

