package com.zcloud.primeport.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.primeport.command.conf.CiolationProperties;
import com.zcloud.primeport.domain.gateway.VehicleApplyGateway;
import com.zcloud.primeport.domain.gateway.VehicleBlackGateway;
import com.zcloud.primeport.domain.gateway.VehicleViolationsGateway;
import com.zcloud.primeport.domain.model.VehicleViolationsE;
import com.zcloud.primeport.dto.VehicleViolationsAddCmd;
import com.zcloud.primeport.persistence.dataobject.VehicleViolationsDO;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * web-app
 *
 * @Author makejava
 * @Date 2026-03-05 11:33:28
 */
@Component
@AllArgsConstructor
@RefreshScope
public class VehicleViolationsAddExe {
    private final VehicleViolationsGateway vehicleViolationsGateway;
    private final VehicleApplyGateway vehicleApplyGateway;
    private final VehicleBlackGateway vehicleBlackGateway;
    private final CiolationProperties ciolationProperties;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(VehicleViolationsAddCmd cmd) {
        List<VehicleViolationsE> vehicleViolationsList = vehicleViolationsGateway.listVehicleViolationByLicenceNo(cmd.getLicenceNo());
        if (ciolationProperties.getLimit() != null && (vehicleViolationsList.size() + 1) >= ciolationProperties.getLimit()) {
            // 进入黑名单
            vehicleBlackGateway.saveIfAbsent(cmd.getLicenceNo()
                    ,cmd.getVehicleType(),cmd.getVehicleTypeName()
                    ,cmd.getLicenceType(),cmd.getLicenceTypeName()
            );
            // 申请的车辆拉黑
            vehicleApplyGateway.updateEvehicleBlockedByLicenceNo(cmd.getLicenceNo(),1);
            // 对接表里进行车辆拉黑的处理。
        }

        VehicleViolationsE examTypeE = new VehicleViolationsE();
        examTypeE.setViolationProcessingStatus(2);
        BeanUtils.copyProperties(cmd, examTypeE);
        boolean res = false;
        try {
            res = vehicleViolationsGateway.add(examTypeE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return true;
    }
}

