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

import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.common.enums.BoCloudExchange;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.common.utils.DateUtils;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.interfaces.resource.CloudServerService;
import com.bocloud.ims.interfaces.resource.ObjectRelationService;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.service.internal.SmsSystemConfigService;
import com.bocloud.nms.enums.ResourceCategory;
import com.bocloud.service.core.CurrentService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 资源到期后的通知定时任务
 *
 * @author wangyu
 * @Date 2020-8-1 10:29:00
 */
@Component
public class ResourceNoticeScheduler {

    private static Logger logger = LoggerFactory.getLogger(ResourceNoticeScheduler.class);
    @Autowired
    private CurrentService service;
    @Autowired
    private ObjectRelationService objectRelationService;
    @Autowired
    private CloudServerService cloudServerService;
    @Autowired
    private CloudServerRepository cloudServerRepository;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private SmsSystemConfigService smsSystemConfigService;
    /**
     * 一天时间毫秒数
     */
    public static final Long ONE_DAY = 24 * 60 * 60 * 1000L;
    /**
     * 资源到期最长保留时长
     */
    protected Long resourceExpireReservedMillis = 30L * ONE_DAY.intValue();

    /**
     * 资源即将到期
     */
    protected Long resourceExpireMillis = 7L * ONE_DAY.intValue();

    /**
     * 初始化相关配置
     */
    private void initConfig() {
        String reservedConfig = smsSystemConfigService.getByCode("ResourceExpireReservedDays");
        if (!StringUtils.isEmpty(reservedConfig)) {
            resourceExpireReservedMillis = Long.valueOf(reservedConfig) * ONE_DAY.intValue();
        }
    }

    /**
     *
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    protected void warn() {
        if (service.isLeader()) {
            // 初始化配置
            this.initConfig();
            ResourceCategory[] values = ResourceCategory.values();
            for (ResourceCategory resourceCategory : values) {
                RequestContext context = null;
                String content = null;
                String subject = "资源到期通知";
                switch (resourceCategory) {
                    case Computer:
                        // 查询全部tenantId不为空的云主机
                        List<CloudServer> allCloudServers = cloudServerRepository.listByTenants();
                        if (ListTool.isEmpty(allCloudServers)) {
                            return;
                        }
                        for (CloudServer cloudServer : allCloudServers) {
                            Date expiredTime = cloudServer.getExpiredTime();
                            if (null == expiredTime) {
                                continue;
                            }
                            if (System.currentTimeMillis() - expiredTime.getTime() >= resourceExpireReservedMillis) {
                                context = new RequestContext(cloudServer.getCatalog(), cloudServer.getOwnerId(),
                                        cloudServer.getTenantId(), cloudServer.getProjectId(), null);
                                cloudServerService.stop(cloudServer.getId(), context);
                                content = "云主机(" + cloudServer.getName() + ")已经到期【"
                                        + resourceExpireReservedMillis / ONE_DAY + "】日，资源已经关闭！";
                            }
                        }
                        break;
                    default:
                        break;
                }
                if (null != content) {
                    amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), "event.notice.queue",
                            new NotifyMessage(context, subject, content, true, false));
                }
            }
        }
    }

    /**
     * 资源到期前 消息提醒
     */
    @Scheduled(cron = "0 0 0 * * ?")
    protected void resourceNotice() {
        if (service.isLeader()) {
            // 初始化配置
            ResourceCategory[] values = ResourceCategory.values();
            for (ResourceCategory resourceCategory : values) {
                RequestContext context = null;
                String content = null;
                String subject = "资源到期通知";
                switch (resourceCategory) {
                    case Computer:
                        // 查询全部tenantId不为空的云主机
                        List<CloudServer> allCloudServers = cloudServerRepository.listByTenants();
                        if (ListTool.isEmpty(allCloudServers)) {
                            return;
                        }
                        for (CloudServer cloudServer : allCloudServers) {
                            Date expiredTime = cloudServer.getExpiredTime();
                            if (null == expiredTime) {
                                continue;
                            }
                            if ((expiredTime.getTime() - System.currentTimeMillis() <= resourceExpireMillis)
                                    && (expiredTime.getTime() - System.currentTimeMillis() > 0)) {
                                context = new RequestContext(cloudServer.getCatalog(), cloudServer.getOwnerId(),
                                        cloudServer.getTenantId(), cloudServer.getProjectId(), null);
                                content = "云主机(" + cloudServer.getName() + ")即将在【" + DateUtils.dateToString(expiredTime, "yyyy-MM-dd HH:mm:ss")
                                        + "】到期，请及时关注！";
                                break;
                            }
                        }
                        break;
                    default:
                        break;
                }
                if (null != content) {
                    amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), "event.notice.queue",
                            new NotifyMessage(context, subject, content, true, false));
                }
            }
        }
    }

}
