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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.app.framework.util.BeanUtil;
import com.hys.app.mapper.erp.StockDamageReportProductMapper;
import com.hys.app.model.erp.dos.StockDamageReportProduct;
import com.hys.app.model.erp.dto.StockDamageReportProductDTO;
import com.hys.app.service.erp.StockDamageReportProductManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 库存报损单产品业务接口实现类
 *
 * @author dmy
 * 2023-12-05
 */
@Service
public class StockDamageReportProductManagerImpl extends ServiceImpl<StockDamageReportProductMapper, StockDamageReportProduct> implements StockDamageReportProductManager {

    @Autowired
    private StockDamageReportProductMapper stockDamageReportProductMapper;

    /**
     * 新增库存报损单产品信息
     *
     * @param reportId 库存报损单ID
     * @param productList 产品信息集合
     */
    @Override
    @Transactional(value = "goodsTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveProduct(Long reportId, List<StockDamageReportProductDTO> productList) {
        //先删除旧数据
        List<Long> reportIds = new ArrayList<>();
        reportIds.add(reportId);
        this.deleteProduct(reportIds);

        //再循环将商品信息入库
        for (StockDamageReportProductDTO productDTO : productList) {
            StockDamageReportProduct product = new StockDamageReportProduct();
            BeanUtil.copyProperties(productDTO, product);
            product.setReportId(reportId);
            this.save(product);
        }
    }

    /**
     * 删除库存报损单产品信息
     *
     * @param reportIds 库存报损单ID集合
     */
    @Override
    @Transactional(value = "goodsTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteProduct(List<Long> reportIds) {
        LambdaQueryWrapper<StockDamageReportProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(StockDamageReportProduct::getReportId, reportIds);
        this.stockDamageReportProductMapper.delete(wrapper);
    }

    /**
     * 根据库存报损单ID获取库存报损单产品信息集合
     *
     * @param reportId 库存报损单ID
     * @return
     */
    @Override
    public List<StockDamageReportProduct> list(Long reportId) {
        return this.lambdaQuery()
                .eq(StockDamageReportProduct::getReportId, reportId)
                .list();
    }
}
