package com.bcxin.signature.scheduling;

import com.bcxin.signature.components.DocumentPushProvider;
import com.bcxin.signature.service.SignatureService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.UUID;

/**
 * 政务网业务流程:
 * --> 读取FTP-->亮证-->如果出现证书已存在-> 自动废止 --> 重新亮证
 * --> 认为废止(业务上: 人为废止或者注销证书) -> 调用废止功能
 */
@Component
public class CertificateScheduleJob extends ScheduleJobAbstract {
    private static final Logger logger = LoggerFactory.getLogger(CertificateScheduleJob.class);

    private final SignatureService signatureService;
    private final DocumentPushProvider documentPushProvider;

    public CertificateScheduleJob(SignatureService signatureService, DocumentPushProvider documentPushProvider) {
        this.signatureService = signatureService;
        this.documentPushProvider = documentPushProvider;
    }

    /**
     * 资格证亮证
     */
    @Scheduled(fixedRate = 3 * 60 * 1000)
    public void step1_push() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String traceId = UUID.randomUUID().toString();
        logger.error("{} begin to execute step1_push", traceId);
        try {
            this.documentPushProvider.push(DocumentPushProvider.DocumentType.Certificate);
        } finally {
            stopWatch.stop();
            logger.error("{} done for executing step1_push, cost {} seconds", traceId, stopWatch.getTotalTimeSeconds());
        }
    }


    /**
     * 文书亮证
     */
    @Scheduled(fixedRate = 3 * 60 * 1000)
    public void signatureJTLZDocument() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String traceId = UUID.randomUUID().toString();
        logger.error("{} begin to execute signatureJTLZDocument", traceId);
        try {
            this.documentPushProvider.push(DocumentPushProvider.DocumentType.Document);
        } finally {
            stopWatch.stop();
            logger.error("{} done for executing signatureJTLZDocument, cost {} seconds", traceId, stopWatch.getTotalTimeSeconds());
        }
    }


    /**
     * 文书、资格证的废止操作(discard)
     */
    //@Scheduled(cron = "${myapps.signature.scheduled.jtlztiming}")

    /**
     * 一般为:
     */
    @Deprecated
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void signatureJTLZ_FZ() {
        StopWatch stopWatch = new StopWatch();

        stopWatch.start();
        String traceId = UUID.randomUUID().toString();
        logger.error("{} begin to execute cancel_push", traceId);
        try {
            this.documentPushProvider.cancel_push();
        } finally {
            stopWatch.stop();
            logger.error("{} done for executing cancel_push, cost {} seconds", traceId, stopWatch.getTotalTimeSeconds());
        }
    }
}
