package com.sckw.transport.handler;


import com.sckw.core.common.enums.enums.ErrorCodeEnum;
import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.core.model.enums.CarWaybillV1Enum;
import com.sckw.order.api.model.OrderDetailVo;
import com.sckw.order.api.model.UpdateActualAmountParam;
import com.sckw.transport.model.KwtLogisticsOrder;
import com.sckw.transport.model.KwtWaybillOrder;
import com.sckw.transport.model.KwtWaybillOrderSubtask;
import com.sckw.transport.model.param.WaybillOrderCancelParam;
import com.sckw.transport.repository.KwtLogisticsOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * Author: donglang
 * Time: 2025-11-19
 * Des: 卸货
 * Version: 1.0
 */

@Slf4j
@Service
public class CancelHandler extends AbstractWaybillOrderHandler<WaybillOrderCancelParam>{

    @Autowired
    private KwtLogisticsOrderRepository logisticsOrderRepository;

    @Override
    protected KwtWaybillOrder getWaybillOrder(WaybillOrderCancelParam param) {
        return getWaybillOrder(param.getWaybillOrderId());
    }

    @Override
    protected void checkState(WaybillOrderCancelParam param, KwtWaybillOrder waybill) {
        if (!Objects.equals(CarWaybillV1Enum.PENDING_VEHICLE.getCode(), waybill.getStatus())) {
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_STATUS_ERROR, "运单状态非待接单");
        }
    }

    @Override
    protected void doBusiness(WaybillOrderCancelParam param, KwtWaybillOrder waybill) {
        //1.获取子运单任务量
        KwtWaybillOrderSubtask subtask = getWaybillSubtask(waybill.getId());
        BigDecimal entrustAmount = subtask.getEntrustAmount();

        //2.更新上游订单：更新物流订单运输量
        KwtLogisticsOrder logOrder = updateLogOrder(param, entrustAmount);

        //3.更新上游订单：更新贸易订单运输量
        updateTradeOrder(logOrder, entrustAmount);
    }



    /**
     * 更新上游物流订单 - 减运输量
     * @param param
     * @param entrustAmount
     * @return
     */
    private KwtLogisticsOrder updateLogOrder(WaybillOrderCancelParam param, BigDecimal entrustAmount) {
        KwtLogisticsOrder logOrder = logisticsOrderRepository.queryByLogisticsOrderId(param.getLogOrderId());
        if (logOrder == null) {
            log.info("当前物流运单无关联物流订单数据：{}", param.getLogOrderId());
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_NOT_LOG_ORDER, "当前物流运单无关联物流订单数据！");
        }

        //取消接单的物流订单的总运输量不能为空
        if (logOrder.getEntrustAmount() == null || logOrder.getEntrustAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_AMOUNT_ERROR, "已接单物订单的总运单量不能为空或0！");
        }
        //总接单数
        Integer totalTake = Optional.ofNullable(logOrder.getTotalTake())
                .map(val -> Math.max(val - 1, 0))
                .orElse(0);
        logOrder.setEntrustAmount(logOrder.getEntrustAmount().subtract(entrustAmount));
        logOrder.setTotalTake(totalTake);
        logisticsOrderRepository.updateById(logOrder);

        log.info("更新上游物流订单运输量成功, 物流订单ID：{}", logOrder.getId());
        return logOrder;
    }


    /**
     * 更新上游贸易订单 - 减运输量
     * @param logOrder
     * @param entrustAmount
     */
    private void updateTradeOrder(KwtLogisticsOrder logOrder, BigDecimal entrustAmount) {
        OrderDetailVo tradeOrder = tradeOrderInfoService.queryByTradeOrderId(logOrder.getTOrderId());
        //取消接单的物流订单的总运输量不能为空
        if (tradeOrder.getActualAmount() == null || tradeOrder.getActualAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRADE_ORDER_AMOUNT_ERROR, "已接单交易订单的总运输量不能为空或0！");
        }

        UpdateActualAmountParam tradeParam = new UpdateActualAmountParam();
        tradeParam.setTOrderId(tradeOrder.getId());
        tradeParam.setActualLoadAmount(tradeOrder.getActualAmount().subtract(entrustAmount));
        tradeOrderInfoService.updateOrderActualAmount(tradeParam);
        log.info("更新上游贸易订单运输量成功, 贸易订单ID：{}", tradeOrder.getId());
    }

    @Override
    protected void updateStatus(WaybillOrderCancelParam param, KwtWaybillOrder waybill) {
        // 已取消状态
        waybill.setStatus(CarWaybillV1Enum.APPROVAL_TREAT.getCode());
        waybillOrderRepository.updateById(waybill);
    }

    @Override
    protected String getProcessName() {
        return "取消接单";
    }

    @Override
    protected String getRemark(WaybillOrderCancelParam param, KwtWaybillOrder waybillOrder) {
        return "司机[" + waybillOrder.getDriverName() + "]取消订单";
    }


}
