package com.ningdatech.carapi.driver.helper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.carapi.common.helper.UserInfoHelper;
import com.ningdatech.carapi.driver.entity.Certificate;
import com.ningdatech.carapi.driver.entity.DriverInfo;
import com.ningdatech.carapi.driver.service.ICertificateService;
import com.ningdatech.carapi.driver.service.IDriverInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author liuxinxin
 * @date 2022/11/14 下午2:44
 */
@Component
@RequiredArgsConstructor
public class DriverInfoHelper {
    private final UserInfoHelper userInfoHelper;
    private final IDriverInfoService iDriverInfoService;
    private final ICertificateService iCertificateService;

    /**
     * 判断驾驶员是否拥有合格证书判断
     *
     * @param userId
     */
    public void driverCertificateValidCheck(Long userId) {
        DriverInfo driverInfo = iDriverInfoService.getOne(Wrappers.lambdaQuery(DriverInfo.class)
                .eq(DriverInfo::getUserId, userId));
        if (Objects.isNull(driverInfo)) {
            throw new BizException("当前账号无驾驶员信息");
        } else {
            Certificate certificate = iCertificateService.getOne(Wrappers.lambdaQuery(Certificate.class)
                    .eq(Certificate::getUserId, userId));
            if (Objects.isNull(certificate)) {
                throw new BizException("当前驾驶员无证书信息");
            } else {
                LocalDateTime expiryDate = certificate.getExpiryDate();
                if (expiryDate.isBefore(LocalDateTime.now())) {
                    throw new BizException("当前驾驶员合格证书已过期");
                }
            }
        }
    }

    /**
     * 判断驾驶员是否拥有有效的合格证书
     *
     * @param userId
     */
    public Boolean hasDriverAvailableCertificate(Long userId) {
        DriverInfo driverInfo = iDriverInfoService.getOne(Wrappers.lambdaQuery(DriverInfo.class)
                .eq(DriverInfo::getUserId, userId));
        if (Objects.isNull(driverInfo)) {
            return false;
        } else {
            Certificate certificate = iCertificateService.getOne(Wrappers.lambdaQuery(Certificate.class)
                    .eq(Certificate::getUserId, userId));
            if (Objects.isNull(certificate)) {
                return false;
            } else {
                LocalDateTime expiryDate = certificate.getExpiryDate();
                if (expiryDate.isBefore(LocalDateTime.now())) {
                    return false;
                }
            }
        }
        return true;
    }
}
