package com.ningdatech.carapi.archives.aop;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.exception.code.ExceptionCode;
import com.ningdatech.basic.function.VUtils;
import com.ningdatech.carapi.car.vehicle.model.NdVehicleBaseInfo;
import com.ningdatech.carapi.archives.enums.AuditStateEnum;
import com.ningdatech.carapi.car.vehicle.service.IVehicleBaseInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program:
 * @description: 车辆审核切面
 * @author: PoffyZhang
 * @created: 2021/10/29 09:12
 */
@Aspect
@Component
@Slf4j
@AllArgsConstructor
@Order(10)
public class AuditVehicleAspect {

    private IVehicleBaseInfoService vehicleBaseInfoService;
 
    @Pointcut("@annotation(com.ningdatech.carapi.archives.aop.AuditVehicle)")
    public void auditVehicleAspect() {
 
    }

    @Before("auditVehicleAspect() && @annotation(auditVehicle)")
    public void doBebore(JoinPoint joinPoint, AuditVehicle auditVehicle) throws Throwable {
        Object[] values = joinPoint.getArgs();
        String carPlate = (String) values[0];

        VUtils.isTrueFormat(StringUtils.isBlank(carPlate))
                .throwMessage(ExceptionCode.OPERATION_EX.getCode(), "车牌号未传 {}!",carPlate);

        LambdaQueryWrapper<NdVehicleBaseInfo> wrapper = Wrappers.lambdaQuery(NdVehicleBaseInfo.class);
        wrapper.eq(NdVehicleBaseInfo::getCarPlate,carPlate);
        //由于 车辆信息 车牌号不唯一 一辆车可能绑定多个企业
        List<NdVehicleBaseInfo> vehicles = vehicleBaseInfoService.list(wrapper);

        VUtils.isTrueFormat(CollUtil.isEmpty(vehicles))
                .throwMessage(ExceptionCode.OPERATION_EX.getCode(), "系统中没有此车辆 {}!",carPlate);

        //暂时取第一辆
        NdVehicleBaseInfo vehicle = vehicles.get(0);
        VUtils.isTrueFormat(!AuditStateEnum.AUDIT_SUCCESS.getCode().equals(vehicle.getAuditState()))
                .throwMessage(ExceptionCode.OPERATION_EX.getCode(), "此车辆未审核成功 {}!",carPlate);
    }
}