package com.hzs.sale.all.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.enums.ESysName;
import com.hzs.common.domain.sale.all.AllProduct;
import com.hzs.common.domain.sale.all.AllProductDetail;
import com.hzs.sale.all.mapper.AllProductMapper;
import com.hzs.sale.all.service.IAllProductDetailService;
import com.hzs.sale.all.service.IAllProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 全系统产品 服务实现类
 */
@Service
public class AllProductServiceImpl extends ServiceImpl<AllProductMapper, AllProduct> implements IAllProductService {

    @Autowired
    private IAllProductDetailService iAllProductDetailService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void changeInventory(AllProduct param) {
        baseMapper.changeInventory(param);

        AllProductDetail productDetail = AllProductDetail.builder()
                .pkAllProduct(param.getPkId())
                .source(ESysName.MANAGE.getValue())
                .changeNum(param.getInventory())
                .remark(param.getRemark())
                .build();
        productDetail.setPkCreator(param.getPkModified());
        iAllProductDetailService.save(productDetail);
    }

    @Override
    public void deleteProduct(Integer pkId, Long userId) {
        this.update(Wrappers.<AllProduct>lambdaUpdate()
                .eq(AllProduct::getPkId, pkId)
                .set(AllProduct::getDelFlag, EDelFlag.DELETE.getValue())
                .set(AllProduct::getPkModified, userId)
                .set(AllProduct::getModifiedTime, new Date())
        );

        iAllProductDetailService.update(Wrappers.<AllProductDetail>lambdaUpdate()
                .eq(AllProductDetail::getPkAllProduct, pkId)
                .set(AllProductDetail::getDelFlag, EDelFlag.DELETE.getValue())
                .set(AllProductDetail::getPkModified, userId)
                .set(AllProductDetail::getModifiedTime, new Date())
        );
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncData(List<AllProductDetail> productDetailList) {
        iAllProductDetailService.saveBatch(productDetailList);

        for (AllProductDetail allProductDetail : productDetailList) {
            baseMapper.changeInventory(AllProduct.builder()
                    .pkId(allProductDetail.getPkAllProduct())
                    .inventory(allProductDetail.getChangeNum())
                    .build());
        }

    }
}
