package com.ningdatech.carapi.irs.service;

import com.ningdatech.cache.redis.RedisOps;
import com.ningdatech.carapi.driver.service.IDriverInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 * AbstractLicenseGetByIrsService
 * </p>
 *
 * @author WendyYang
 * @since 2023/5/16
 **/
@RequiredArgsConstructor
public abstract class AbstractLicenseGetByIrsService {

    protected final IDriverInfoService driverInfoService;
    protected final RestTemplate restTemplate;
    protected final RefreshKeyService refreshKeyService;
    protected final RedisOps redisOps;
    protected final IDriversLicenseRawService driversLicenseRawService;

    public static final String RK_DRIVER_LICENSE = "DRIVER_LICENSE_IRS";
    public static final String RK_DRIVING_LICENSE = "DRIVING_LICENSE_IRS";

    protected static final int LIMIT_BY_DAY = 100;

    // 应用appKey
    protected static final String APP_KEY = "A330000100000202105003941";
    protected static final String APP_SECRET = "e07fd4471e92410d9860282d939b1217";

    protected static final Map<String, Future<?>> FUTURE_MAP = new ConcurrentHashMap<>();
    public static ScheduledExecutorService scheduler;

    protected static final int MINUTES_DAY = 24 * 60;
    protected static final int INIT_DELAY_MINUTES = 5;

    public static final int DELAY_MINUTES = 2;

    /**
     * 开启证件信息获取任务
     *
     * @param rk           证件类型
     * @param service      证件信息获取实现类
     * @param delayMinutes 延迟执行时间
     */
    protected void startLicensePullTask(String rk, PullLicenseByIrsService service, Integer delayMinutes) {
        if (scheduler == null || scheduler.isShutdown()) {
            scheduler = Executors.newScheduledThreadPool(2);
        }
        Future<?> future = scheduler.scheduleAtFixedRate(() -> {
            service.pullLicense();
            try {
                long leftCnt = service.getLeftCount();
                boolean status = service.runningStatus();
                if (!status && leftCnt == 0) {
                    Future<?> self = FUTURE_MAP.remove(rk);
                    if (self != null && !self.isCancelled()) {
                        self.cancel(true);
                    }
                    if (FUTURE_MAP.isEmpty()) {
                        scheduler.shutdown();
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, delayMinutes, MINUTES_DAY, TimeUnit.MINUTES);
        FUTURE_MAP.put(rk, future);
    }

}
