package com.jwipc.order.client.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Sets;
import com.jwipc.order.clent.dto.SapGoodReceiptClientDTO;
import com.jwipc.order.client.SapGoodReceiptClient;
import com.jwipc.order.client.convert.SapGoodReceiptClientConvert;
import com.jwipc.order.entity.SapGoodReceipt;
import com.jwipc.order.logic.DeliveryOrderLogic;
import com.jwipc.order.service.ISapGoodReceiptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author shenyang.ou
 * @date 2024/4/10 14:14
 * @desc
 */
@Service
@RequiredArgsConstructor
public class SapGoodReceiptClientImpl implements SapGoodReceiptClient {
    private final SapGoodReceiptClientConvert sapGoodReceiptClientConvert;
    private final ISapGoodReceiptService sapGoodReceiptService;
    private final DeliveryOrderLogic deliveryOrderLogic;

    public void saveOrUpdate(List<SapGoodReceiptClientDTO> sapGoodReceiptClientDTOS) {
        if (CollectionUtil.isNotEmpty(sapGoodReceiptClientDTOS)) {
            List<SapGoodReceipt> sapGoodReceipts = sapGoodReceiptClientConvert.dto2EntityList(sapGoodReceiptClientDTOS);
            Set<String> devOrderCodes = Sets.newHashSet();
            sapGoodReceipts.forEach(sapGoodReceipt -> {
                final SapGoodReceipt db = sapGoodReceiptService.getOne(
                        new LambdaQueryWrapper<SapGoodReceipt>()
                                .eq(SapGoodReceipt::getEbeln, sapGoodReceipt.getEbeln())
                                .eq(SapGoodReceipt::getEbelp, sapGoodReceipt.getEbelp())
                                .eq(SapGoodReceipt::getMatnr, sapGoodReceipt.getMatnr())
                                .eq(SapGoodReceipt::getLifnr, sapGoodReceipt.getLifnr())
                                .eq(SapGoodReceipt::getWerks, sapGoodReceipt.getWerks()), false);
                if (ObjectUtil.isNotNull(db)) {
                    sapGoodReceipt.setId(db.getId());
                }
                if (StrUtil.isNotEmpty(sapGoodReceipt.getBktxt())) {
                    devOrderCodes.add(sapGoodReceipt.getBktxt());
                }
                deliveryOrderLogic.complateDelivery(devOrderCodes);
            });

            sapGoodReceiptService.saveOrUpdateBatch(sapGoodReceipts);
        }
    }
}
