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.transport.model.KwtWaybillOrder;
import com.sckw.transport.model.KwtWaybillOrderSubtask;
import com.sckw.transport.model.param.WaybillOrderUnloadParam;
import com.sckw.transport.repository.KwtWaybillOrderSubtaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

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

@Service
public class UnloadingHandler extends AbstractWaybillOrderHandler<WaybillOrderUnloadParam>{

    @Autowired
    private KwtWaybillOrderSubtaskRepository waybillOrderSubtaskRepository;


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


    @Override
    protected void checkState(WaybillOrderUnloadParam param, KwtWaybillOrder waybill) {
        if (waybill == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_NOT_FOUND, "运单不存在");
        }
        if (!Objects.equals(CarWaybillV1Enum.WAIT_LOADING.getCode(), waybill.getStatus())) {
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_STATUS_ERROR, "当前物流运单不是已离场状态，无法推进下一节点！");
        }
    }

    @Override
    protected void doBusiness(WaybillOrderUnloadParam param, KwtWaybillOrder waybill) {
        //更新子运单卸货净重  TODO 审核通过后，贸易订单和物流订单的运输量需要已实际卸货净重为准
        KwtWaybillOrderSubtask subtask = getWaybillSubtask(waybill.getId());
        subtask.setUnloadAmount(param.getUnloadAmount());
        subtask.setUnloadTime(new Date());
        subtask.setUnloadUrl(param.getUnloadUrl());
        subtask.setUnloadUploadTime(new Date());
        subtask.setUnloadOperator(waybill.getDriverId());
        waybillOrderSubtaskRepository.updateById(subtask);
    }

    @Override
    protected void updateStatus(WaybillOrderUnloadParam param, KwtWaybillOrder waybill) {
        // 已卸货状态
        waybill.setStatus(CarWaybillV1Enum.COMPLETION_LOADING.getCode());
        waybillOrderRepository.updateById(waybill);
    }

    @Override
    protected String getProcessName() {
        return "卸货";
    }

    @Override
    protected String getRemark(WaybillOrderUnloadParam param, KwtWaybillOrder waybillOrder) {
        return "司机[" + waybillOrder.getDriverName() + "]已上传卸货凭证";
    }
}
