package com.bohuikeji.delivery.backstage.listener.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.entity.TLogistics;
import com.bohuikeji.delivery.backstage.entity.TLogisticsRecord;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.TOrderCircu;
import com.bohuikeji.delivery.backstage.service.ITLogisticsRecordService;
import com.bohuikeji.delivery.backstage.service.ITLogisticsService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.frame.module.admin.base.MqListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 订单物流流转更新
 * @author sjh
 * @date
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderLogisticsUpdateListener extends MqListener<String> {

    final ITOrderService orderService;
    final ITLogisticsRecordService logisticsRecordService;
    final ITLogisticsService logisticsService;
    @Override
    public boolean onReceive(String orderNum) {
        TOrder order=orderService.getByNum(orderNum);
        //更新订单流转
        //TOrderCircu.insertCircu(order);
        log.error("订单状态流转时的订单信息：{}",order.getOrderId());
        TLogistics tLogistics = logisticsService.getOne(new QueryWrapper<TLogistics>().eq("order_num",order.getOrderNum()));
        if(tLogistics==null){
            logisticsService.saveTLogistics(order.getOrderId(),order.getCourierId(),null);
        }else {
            logisticsService.updateById(tLogistics.setLogisticsStatus(order.getOrderStatus()));
        }
        //插入物流流转状态
        logisticsService.list(new QueryWrapper<TLogistics>().eq("order_id", order.getOrderId())).forEach(logistics -> {
            TLogisticsRecord record = new TLogisticsRecord();
            record.setLogisticsId(logistics.getLogisticsId());
            record.setLogisticsNum(logistics.getLogisticsNum());
            record.setOrderId(order.getOrderId());
            record.setOrderNum(order.getOrderNum());
            record.setLogisticsStatus(order.getOrderStatus());
            record.setCourierId(order.getCourierId());
            logisticsRecordService.save(record);
        });
        return true;
    }

    @Override
    public void onError(String msg, Exception e) {

    }
}
