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.ProcurementPlanProductMapper;
import com.hys.app.model.erp.dos.ProcurementPlanProduct;
import com.hys.app.model.erp.dto.ProcurementPlanProductDTO;
import com.hys.app.service.erp.ProcurementPlanProductManager;
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 ProcurementPlanProductManagerImpl extends ServiceImpl<ProcurementPlanProductMapper, ProcurementPlanProduct> implements ProcurementPlanProductManager {

    @Autowired
    private ProcurementPlanProductMapper procurementPlanProductMapper;

    /**
     * 新增采购计划产品信息
     *
     * @param planId 采购计划ID
     * @param productList 产品信息集合
     */
    @Override
    @Transactional(value = "goodsTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveProduct(Long planId, List<ProcurementPlanProductDTO> productList) {
        //根据采购集合ID删除旧采购商品信息
        List<Long> planIds = new ArrayList<>();
        planIds.add(planId);
        this.deleteProduct(planIds);

        //再循环将商品信息入库
        for (ProcurementPlanProductDTO productDTO : productList) {
            ProcurementPlanProduct product = new ProcurementPlanProduct();
            BeanUtil.copyProperties(productDTO, product);
            product.setPlanId(planId);
            this.save(product);
        }
    }

    /**
     * 删除采购计划产品信息
     *
     * @param planIds 采购计划ID集合
     */
    @Override
    @Transactional(value = "goodsTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteProduct(List<Long> planIds) {
        LambdaQueryWrapper<ProcurementPlanProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ProcurementPlanProduct::getPlanId, planIds);
        this.procurementPlanProductMapper.delete(wrapper);
    }

    /**
     * 根据采购计划ID获取采购计划产品信息集合
     * @param planId 采购计划ID
     * @return
     */
    @Override
    public List<ProcurementPlanProduct> list(Long planId) {
        return this.lambdaQuery()
                .eq(ProcurementPlanProduct::getPlanId, planId)
                .list();
    }
}
