package com.tax.sign.job;


import com.tax.sign.model.SignDateInfo;
import com.tax.sign.model.SignDateInfoExample;
import com.tax.sign.service.api.SignDateInfoService;
import com.yxcheng.token.common.cache.distributelock.ScheduledControll;
import com.yxcheng.token.constants.RedisContants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;


@Component
public class SynGetServerDate4ZoneJob {

    private static final Logger logger = LoggerFactory.getLogger(SynGetServerDate4ZoneJob.class);

    @Autowired
    private SignDateInfoService signDateInfoService;

    @Autowired
    SynTaskService synTaskService;


    private CountDownLatch latch = null;

    @Autowired
    private ScheduledControll scheduledControll;




    @Scheduled(cron = "${service.sync.getServerDate4Zone}")
    public void InvoiceSyncTask() {
        if(!scheduledControll.getScheduledLock(RedisContants.SYN_GET_SERVERDATE_SCHEDULED_LOCK,RedisContants.SYN_GET_SERVERDATE_SCHEDULED_EXPIRE)){
            logger.info("SyncTaxnoServiceJob未能获取锁，不执行");
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        String syncTime = sdf.format(new Date());

        logger.info("InvoiceTask.SynGetServerDate4ZoneJob ----> 开始执行定时任务："+syncTime);
        SignDateInfoExample example = new SignDateInfoExample();
        List<SignDateInfo> signDateInfos = signDateInfoService.selectByExample(example);
        Date date = new Date();

        if(signDateInfos!=null && signDateInfos.size()>0){
            latch = new CountDownLatch(signDateInfos.size());
            for(SignDateInfo signDateInfo : signDateInfos){
                synTaskService.getServerDate(latch,signDateInfo,signDateInfoService,date);
            }
        }
        try {
            if(latch!=null){
                latch.await();
                latch = null;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("InvoiceTask.SynGetServerDate4ZoneJob ----> 结束执行定时任务：时间--》"+ sdf.format(new Date()));
    }




}
