package com.sckw.transport.handler;


import com.alibaba.fastjson.JSON;
import com.sckw.core.common.enums.enums.ErrorCodeEnum;
import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.core.model.enums.CarWaybillV1Enum;
import com.sckw.core.model.enums.GatekeeperStatusEnum;
import com.sckw.fleet.api.model.vo.RTruckVo;
import com.sckw.transport.model.*;
import com.sckw.core.model.enums.GatekeeperTypeEnum;
import com.sckw.transport.model.KwtGatekeeperWaybillOrder;
import com.sckw.transport.model.KwtWaybillOrder;
import com.sckw.transport.model.KwtWaybillOrderSubtask;
import com.sckw.transport.model.KwtWaybillOrderTicket;
import com.sckw.transport.model.param.WaybillOrderLiftRodReleaseParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * Author: donglang
 * Time: 2025-11-19
 * Des: 抬杆放行 mock
 * Version: 1.0
 */

@Slf4j
@Service
public class LiftRodReleaseHandler extends AbstractWaybillOrderHandler<WaybillOrderLiftRodReleaseParam> {

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

    @Override
    protected void checkState(WaybillOrderLiftRodReleaseParam param, KwtWaybillOrder waybill) {
        if (!Objects.equals(CarWaybillV1Enum.RELEASED_NOT_EXITED.getCode(), waybill.getStatus())) {
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_STATUS_ERROR, "运单状态不是“已放行待离场”状态, 无法推进下一节点！");
        }
    }

    @Override
    protected void doBusiness(WaybillOrderLiftRodReleaseParam param, KwtWaybillOrder waybillOrder) {
        log.info("推进门卫数据为已离场：{}", JSON.toJSONString(waybillOrder));

        //1. 计算是否空载离场
        Boolean isEmptyLoadLeave = calculateEmptyLoad(waybillOrder);

        //2. 修改门卫订单状态为：空载离场/离场
        updateGatekeeperOrderStatus(waybillOrder, isEmptyLoadLeave);

        //3. 创建门卫卸货订单
        creatGatekeeperUnLoadingOrder(waybillOrder);
    }

    /**
     * 计算是否空载离场
     * @param waybillOrder
     * @return
     */
    private Boolean calculateEmptyLoad(KwtWaybillOrder waybillOrder) {
        //查询运单装卸货信息
        KwtWaybillOrderTicket orderTicket = waybillOrderTicketRepository.queryByWOrderIdByIdAndType(waybillOrder.getId(), 1);
        if (orderTicket == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_TICKET_NOT_FOUND, "当前物流运单装卸货信息不存在，无法记录皮重！");
        }
        BigDecimal loadAmount = orderTicket.getAmount();

        //空载离场,净重<=0.5
        return loadAmount != null && loadAmount.compareTo(BigDecimal.valueOf(0.5)) <= 0;
    }

    /**
     * 修改门卫订单状态
     * @param waybillOrder
     * @return
     */
    public void updateGatekeeperOrderStatus(KwtWaybillOrder waybillOrder, Boolean isEmptyLoadLeave) {
        KwtGatekeeperWaybillOrder gatekeeper = gatekeeperWaybillOrderRepository
                .queryGatekeeperWaybillOrderByWOrderId(waybillOrder.getId(), GatekeeperTypeEnum.LOADING.getCode());
        if (gatekeeper == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.GATEKEEPER_ORDER_NOT_FOUND, "当前门卫订单数据不存在！");
        }
        if (!(GatekeeperStatusEnum.READY_RELEASE.getCode().equals(gatekeeper.getStatus()))) {
            throw new BusinessPlatfromException(ErrorCodeEnum.GATEKEEPER_ORDER_STATUS_ERROR, "当前门卫订单状态异常，不能推进为已离场状态！");
        }

        // 修改门卫状态：空载离场/已离场
        GatekeeperStatusEnum targetStatus = isEmptyLoadLeave ? GatekeeperStatusEnum.EMPTY_EXITED : GatekeeperStatusEnum.EXITED;
        gatekeeper.setStatus(targetStatus.getCode());
        gatekeeperWaybillOrderRepository.updateById(gatekeeper);

    }


    /**
     * 创建卸货门卫订单
     *
     * @param waybillOrder
     */
    private void creatGatekeeperUnLoadingOrder(KwtWaybillOrder waybillOrder) {
        // 只有原矿运输的才会新增卸货门卫订单
        KwtLogisticsOrder logisticsOrder = getLogisticsOrder(waybillOrder.getLOrderId());
        if (!Objects.equals(1, logisticsOrder.getOrderType())) {
            return;
        }

        RTruckVo truck = remoteFleetService.findTruckByTruckNo(waybillOrder.getTruckNo());
        if (truck == null || !Objects.equals(truck.getStatus(), 0)) {
            throw new BusinessPlatfromException(ErrorCodeEnum.TRUCK_STATUS_ERROR, "当前车辆非正常状态，不能接单！");
        }
        //查询子运单
        KwtWaybillOrderSubtask waybillSubtask = getWaybillSubtask(waybillOrder.getId());

        CompletableFuture.runAsync(() -> {
            try {
                KwtGatekeeperWaybillOrder gatekeeper = new KwtGatekeeperWaybillOrder();
                gatekeeper.setEntId(waybillOrder.getEntId());
                gatekeeper.setWOrderId(waybillOrder.getId());
                gatekeeper.setWOrderNo(waybillOrder.getWOrderNo());
                gatekeeper.setLOrderId(waybillOrder.getLOrderId());
                // 查询商品信息
                KwtLogisticsOrderGoods orderGoods = logisticsOrderGoodsRepository.queryByLogOrderId(waybillOrder.getLOrderId());
                if (orderGoods != null) {
                    gatekeeper.setGoodsId(orderGoods.getGoodsId());
                    gatekeeper.setGoodsName(orderGoods.getGoodsName());
                }
                gatekeeper.setWaybillAcceptTime(waybillOrder.getCreateTime());
                gatekeeper.setType(GatekeeperTypeEnum.UNLOADING.getCode());
                gatekeeper.setStatus(GatekeeperStatusEnum.PENDING_ENTRY.getCode());
                gatekeeper.setWaybillAcceptTime(waybillOrder.getCreateTime());
                gatekeeper.setTruckType(truck.getTruckType());
                gatekeeper.setEntrustAmount(waybillSubtask.getEntrustAmount());
                gatekeeper.setCarAxis(truck.getCarAxis());
                gatekeeper.setLegalLoad(truck.getLegalLoad());
                gatekeeper.setCreateTime(new Date());
                gatekeeper.setCreateUser(waybillOrder.getDriverId());
                gatekeeper.setUpdateUser(waybillOrder.getDriverId());

                log.debug("开始异步保存卸货门卫订单数据，运单ID:{}", waybillOrder.getId());
                gatekeeperWaybillOrderRepository.save(gatekeeper);
                log.debug("卸货门卫订单数据保存成功");
            } catch (Exception e) {
                log.error("异步保存卸货门卫订单数据失败！");
            }
        });
    }


    @Override
    protected void calculateAutoDispatchScore(WaybillOrderLiftRodReleaseParam param, KwtWaybillOrder waybillOrder) {

    }

    @Override
    protected String getProcessName() {
        return "抬杆放行";
    }

    @Override
    protected void getStatus(KwtWaybillOrder waybillOrder) {
        // 1. 计算是否空载离场
        Boolean isEmptyLoadLeave = calculateEmptyLoad(waybillOrder);

        // 2. 校验状态：若是空载离场，运单状态为已完成
        CarWaybillV1Enum status = isEmptyLoadLeave ? CarWaybillV1Enum.COMPLETED : CarWaybillV1Enum.WAIT_LOADING;
        if (isEmptyLoadLeave) {
            waybillOrder.setRemark("空载离场");
        }

        // 3. 修改运单状态
        waybillOrder.setStatus(status.getCode());
        waybillOrderRepository.updateById(waybillOrder);

        // 4. 修改子运单状态
        KwtWaybillOrderSubtask waybillSubtask = getWaybillSubtask(waybillOrder.getId());
        waybillSubtask.setStatus(status.getCode());
        waybillOrderSubtaskRepository.updateById(waybillSubtask);
    }

    @Override
    protected String getRemark(WaybillOrderLiftRodReleaseParam param, KwtWaybillOrder waybillOrder) {
        return "司机[" + waybillOrder.getDriverName() + "]已离场";
    }
}
