package com.clx.performance.listener;

import com.alibaba.fastjson.JSON;
import com.clx.order.enums.UpdateEnum;
import com.clx.order.enums.VehicleUsageEnum;
import com.clx.performance.component.GoodsOrderTruckRecordComponent;
import com.clx.performance.component.OrderCancelComponent;
import com.clx.performance.constant.RabbitKeyConstants;
import com.clx.performance.dao.OrderGoodsDao;
import com.clx.performance.dto.dts.DataTransportDTO;
import com.clx.performance.enums.DtsOperationTypeEnum;
import com.clx.performance.enums.OrderGoodsLogsEnum;
import com.clx.performance.enums.OrderGoodsPendingOrderWayStatusEnum;
import com.clx.performance.model.OrderGoods;
import com.clx.performance.service.OrderGoodsLogService;
import com.msl.common.utils.DtsMapConvertUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Objects;

@Slf4j
@Component
@AllArgsConstructor
public class OrderGoodsDtsListener {

    private final OrderCancelComponent orderCancelComponent;
    private final GoodsOrderTruckRecordComponent goodsOrderTruckRecordComponent;
    private final OrderGoodsDao orderGoodsDao;
    private final OrderGoodsLogService orderGoodsLogService;



    @RabbitListener(queues = RabbitKeyConstants.CLX_PERFORMANCE_ORDER_GOODS_QUEUE)
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody());
            log.info("DTS消息同步开始, database:clx_performance.order_goods, msg:{}", msg);
            DataTransportDTO dataTransportDTO = JSON.parseObject(msg, DataTransportDTO.class);
            OrderGoods before = DtsMapConvertUtil.convert(dataTransportDTO.getBeforeMap(), new OrderGoods());
            OrderGoods after = DtsMapConvertUtil.convert(dataTransportDTO.getAfterMap(), new OrderGoods());
            if(Objects.equals(DtsOperationTypeEnum.INSERT.getCode(),dataTransportDTO.getOperationType().getCode())){
                //同步after数据
                log.info("新增:{}",after);
            }else if(Objects.equals(DtsOperationTypeEnum.UPDATE.getCode(),dataTransportDTO.getOperationType().getCode())){
                log.info("修改:{}",after);
                backFillOrderWeight(after);
            }else if(Objects.equals(DtsOperationTypeEnum.DELETE.getCode(),dataTransportDTO.getOperationType().getCode())){
                //数据删除
                log.info("删除:{}",before);
            }
        } catch (Exception e) {
            log.info("DTS消息同步失败, database:clx_performance.order_goods, error:{}", e.getMessage());
        }
    }

    //货单剩余吨数不足35吨，自动恢复吨数到订单上
    public void backFillOrderWeight(OrderGoods after){
        //剩余吨数小于35吨并且大于0，自动归还订单上
        if(new BigDecimal("35").compareTo(after.getResidueTransportWeight()) > 0 &&
                after.getResidueTransportWeight().compareTo(BigDecimal.ZERO) > 0){
            log.info("开始自动恢复吨数到订单,订单号:{},货单号:{},货单剩余吨数:{}",
                    after.getOrderNo(),after.getOrderGoodsNo(),after.getResidueTransportWeight());
            orderCancelComponent.backFillOrderWeight(after,after.getResidueTransportWeight(), UpdateEnum.ADD.getCode());
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setId(after.getId());
            orderGoods.setResidueTransportWeight(BigDecimal.ZERO);
            orderGoodsDao.updateEntityByKey(orderGoods);
            orderGoodsLogService.saveLog(after.getOrderGoodsNo(), 0L, "系统", OrderGoodsLogsEnum.Type.SYSTEM_RELEASE.getName(),
                    String.format("系统自动释放：%s吨", after.getResidueTransportWeight()));
            //释放定向单(非自由车辆)对应的定向车辆
            if(Objects.equals(after.getPendingOrderWay(), OrderGoodsPendingOrderWayStatusEnum.Status.EXCLUSIVE.getCode())
            && !Objects.equals(after.getVehicleUsage(), VehicleUsageEnum.Status.OWN.getCode())){
                goodsOrderTruckRecordComponent.releaseOrderGoodsDriverAndTruck(after.getOrderGoodsNo());
            }
            log.info("结束自动恢复吨数到订单,订单号:{},货单号:{},货单剩余吨数:{}",
                    after.getOrderNo(),after.getOrderGoodsNo(),after.getResidueTransportWeight());
        }
    }
}
