package com.bocloud.ims.service.scheduler.scheduler;

import com.bocloud.cmp.driver.common.TaskMsgDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.TaskMsgModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.interfaces.resource.SyncService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.service.core.CurrentService;
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 org.springframework.util.Assert;

import java.util.List;

/**
 * @Author: lxy
 * @Description: 定时更新平台实时任务（5分钟一次）
 * @Date 2021/8/31 10:35
 **/
@Component
public class VendorTaskMsgScheduler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CurrentService service;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private TaskMsgDriver taskMsgDriver;
    @Autowired
    private SyncService syncService;

    @Scheduled(cron = "${vendor.taskmsg.scheduler:0 0/5 * * * ?}")
    void updateTaskMsg() {
        if (!service.isLeader()) {
            return;
        }
        List<CloudVendor> vendors = cloudVendorRepository.listByType(CloudProvider.VMWARE.name());
        if (vendors.isEmpty()) {
            return;
        }

        long begin = System.currentTimeMillis();
        logger.info("开始定时更新vc平台实时任务...");
        for (CloudVendor vendor : vendors) {
            Assert.notNull(vendor, "云平台不存在");
            try {
                BocloudResult<List<TaskMsgModel>> result = taskMsgDriver.list(vendor.getUuid());
                if (result.isSuccess() && null != result.getData()) {
                    logger.info("Start sync VendorTaskMsg : " + vendor.getName());
                    syncService.syncVendorTaskMsg(result.getData(), vendor.getId());
                    logger.info("End sync VendorTaskMsg : " + vendor.getName());
                }
            } catch (Exception e) {
                logger.error("VendorTask Msg同步失败：" + e);
            }
        }

        long cost = (System.currentTimeMillis() - begin) / 1000;
        logger.info("定时更新vc平台实时任务完成，耗时{}秒", cost);
    }
}
