package com.tmerclub.cloud.order.service.impl;

import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.constant.DistributedIdKey;
import com.tmerclub.cloud.order.dto.AllotOrderItemDTO;
import com.tmerclub.cloud.order.mapper.AllotOrderItemMapper;
import com.tmerclub.cloud.order.model.AllotOrderItem;
import com.tmerclub.cloud.order.service.AllotOrderItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gaozijie
 * @date 2023-11-20
 */
@Service
public class AllotOrderItemServiceImpl implements AllotOrderItemService {

    @Autowired
    private AllotOrderItemMapper allotOrderItemMapper;

    @Autowired
    private SegmentManager segmentManager;

    @Override
    public void addBatchAllotOrderItem(List<AllotOrderItemDTO> allotOrderItemDTOList) {
        if (CollectionUtils.isEmpty(allotOrderItemDTOList)) {
            return;
        }
        List<AllotOrderItem> allotOrderItems = new ArrayList<>(allotOrderItemDTOList.size());
        AllotOrderItem allotOrderItem;
        for (AllotOrderItemDTO allotOrderItemDTO : allotOrderItemDTOList) {
            allotOrderItem = this.buildAllotOrderItem(allotOrderItemDTO);
            allotOrderItems.add(allotOrderItem);
        }
        allotOrderItemMapper.addBatchAllotOrderItem(allotOrderItems);
    }

    @Override
    public void updateBatchAllotOrderItem(List<AllotOrderItemDTO> allotOrderItemDTOList) {
        if (CollectionUtils.isEmpty(allotOrderItemDTOList)) {
            return;
        }
        List<AllotOrderItem> allotOrderItems = allotOrderItemDTOList.stream().map(x -> {
            AllotOrderItem allotOrderItem = new AllotOrderItem();
            BeanUtils.copyProperties(x, allotOrderItem);
            allotOrderItem.setUpdateTime(LocalDateTime.now());
            return allotOrderItem;
        }).toList();
        for (AllotOrderItem allotOrderItem : allotOrderItems) {
            allotOrderItemMapper.updateAllotOrderItem(allotOrderItem);
        }
    }

    /**
     * 构建调拨订单商品实体类
     * @param allotOrderItemDTO 调拨订单商品dto
     * @return 调拨订单商品
     */
    private AllotOrderItem buildAllotOrderItem(AllotOrderItemDTO allotOrderItemDTO) {
        AllotOrderItem allotOrderItem = new AllotOrderItem();
        BeanUtils.copyProperties(allotOrderItemDTO, allotOrderItem);
        allotOrderItem.setAllotOrderItemId(segmentManager.getSegmentIdWithDateTime(DistributedIdKey.tmerclub_ALLOT_ORDER_ITEM, allotOrderItemDTO.getShopId()));
        allotOrderItem.setAllotInCount(0);
        allotOrderItem.setCreateTime(LocalDateTime.now());
        allotOrderItem.setUpdateTime(LocalDateTime.now());
        return allotOrderItem;
    }
}
