package com.clx.performance.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.clx.order.enums.VehicleUsageEnum;
import com.clx.performance.constant.RabbitKeyConstants;
import com.clx.performance.dao.OrderGoodsDao;
import com.clx.performance.dao.OrderGoodsTruckBindDao;
import com.clx.performance.enums.OrderGoodsTruckBindEnum;
import com.clx.performance.model.OrderGoods;
import com.clx.performance.vo.mq.OrderTruckBindCancelParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@AllArgsConstructor
public class OrderGoodsDriverBindListener {


    private final OrderGoodsTruckBindDao orderGoodsTruckBindDao;

    private final OrderGoodsDao orderGoodsDao;

    @RabbitListener(queues = RabbitKeyConstants.ORDER_TRUCK_BIND_LAZY_QUEUE)
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(String message) throws Exception {
        OrderTruckBindCancelParam param = JSONUtil.toBean(message, OrderTruckBindCancelParam.class);
        log.info("OrderGoodsDriverBindListener请求参数{}", JSONUtil.parse(param));
        if (StringUtils.isNotBlank(param.getOrderGoodsNo())) {
            String orderGoodsNo = param.getOrderGoodsNo();
            OrderGoods orderGoods = orderGoodsDao.getByOrderGoodsNo(orderGoodsNo).get();
            if (VehicleUsageEnum.Status.OWN.getCode().equals(orderGoods.getVehicleUsage())) {
                orderGoodsTruckBindDao.updateOrderGoodsBindStatus(orderGoodsNo, OrderGoodsTruckBindEnum.Status.CANCEL.getCode());
            }
        } else if (StringUtils.isNotBlank(param.getOrderNo())) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.getOrderGoodsListByOrderNo(param.getOrderNo());
            List<String> orderGoodsNoList = orderGoodsList.stream().filter(i -> VehicleUsageEnum.Status.OWN.getCode().equals(i.getVehicleUsage()))
                    .map(OrderGoods::getOrderGoodsNo).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(orderGoodsNoList)) {
                return;
            }
            orderGoodsTruckBindDao.updateOrderGoodsBindStatus(orderGoodsNoList, OrderGoodsTruckBindEnum.Status.CANCEL.getCode());
        }
    }
}
