package com.bocloud.ims.service.task;

import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.ObjectRelation;
import com.bocloud.ims.interfaces.resource.CloudServerService;
import com.bocloud.ims.interfaces.resource.CloudVendorService;
import com.bocloud.ims.interfaces.resource.VMApplyService;
import com.bocloud.ims.service.internal.CosInternalService;
import com.bocloud.ims.service.internal.SmsSystemConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;

import java.util.Date;

/**
 * ecs到期处理任务
 *
 * @author wangyu
 * @version 1.0
 * @since 2020年5月12日
 */
public class EcsExpiredTask extends AbstractExpiredTask {

    private static Logger logger = LoggerFactory.getLogger(EcsExpiredTask.class);
    private CloudServerService cloudServerService;
    private VMApplyService vmApplyService;

    public EcsExpiredTask(ObjectRelation relation, SmsSystemConfigService smsSystemConfigService,
                          CosInternalService cosInternalService, CloudVendorService vendorService, AmqpTemplate amqpTemplate,
                          CloudServerService cloudServerService, VMApplyService vmApplyService) {
        super(relation, smsSystemConfigService, cosInternalService, vendorService, amqpTemplate);
        this.cloudServerService = cloudServerService;
        this.vmApplyService = vmApplyService;
    }

    @Override
    public NotifyMessage process(ObjectRelation relation) {
        try {
            BocloudResult result = cloudServerService.detail(relation.getResId());
            if (result.isFailed() || null == result.getData()) {
                return null;
            }
            CloudServer server = (CloudServer) result.getData();
            BocloudResult vendorResult = vendorService.detail(server.getVendorId());
            if (vendorResult.isFailed() || null == vendorResult.getData()) {
                return null;
            }
            CloudVendor vendor = (CloudVendor) vendorResult.getData();
            Long residueTime = relation.getExpiredTime().getTime() - System.currentTimeMillis();// 资源剩余时间
            String residue = "";
            if (residueTime < 0L) {
                residue = "资源已经到期!";
            } else if (residueTime % ONE_DAY == 0L) {
                residue = residueTime / ONE_DAY + "天";
            } else if (residueTime % ONE_DAY > 0L) {
                residue = residueTime / ONE_DAY + "天" + residueTime % ONE_DAY / (60 * 60 * 1000L) + "小时";
            }
            String subject = "云主机到期预警";
            String content = null;
            RequestContext context = null;
            // 首先判断资源是否已经超过最长保留时长(当前时间减去资源到期时间超过资源到期最长保留时长，则直接释放)
            context = new RequestContext(server.getCatalog(), relation.getTarget(), server.getTenantId(),
                    server.getProjectId(), null);
            if (System.currentTimeMillis() - relation.getExpiredTime().getTime() >= resourceExpireReservedMillis) {
                // 如果配置了自动释放，则删除资源
                if (autoDestroy) {
//                    // 如果机器是开机状态或者是vc下挂起的云主机，则先关机才能删除
//                    if ((CloudProvider.VMWARE.name().equalsIgnoreCase(vendor.getType())
//                            && BocloudStatus.Server.SUSPENDED.name().equals(server.getStatus()))
//                            || (BocloudStatus.Server.RUNNING.name().equals(server.getStatus()))) {
//
//                        cloudServerService.stop(server.getId(), context);
//                    }
//                    BocloudResult removeResult = cloudServerService.remove(server.getId(), null, context);
//                    if (removeResult.isSuccess()) {
//                        // 回滚配额
//                        List<ResourceQuota> quotas = new ArrayList<>();
//                        quotas.add(new ResourceQuota(vendor.getType().toLowerCase() + ".standard.server", 1L));
//                        quotas.add(new ResourceQuota("meta.cpu", Long.valueOf(server.getCpu())));
//                        quotas.add(new ResourceQuota("meta.mem", server.getMemory().longValue()));
//                        quotas.add(new ResourceQuota("meta.disk", Long.valueOf(server.getDisk())));
//                        gmsInternalService.updateQuotas(quotas, Action.Callback, server.getProjectId());
//                    }
//                    content = "云主机(" + server.getName() + ")已经到期，【" + resourceExpireReservedMillis / ONE_DAY
//                            + "】日内未进行延期，资源被释放，释放结果：【" + removeResult.getMessage() + "】";
                } else {
                    content = "云主机(" + server.getName() + ")已经到期，【" + resourceExpireReservedMillis / ONE_DAY
                            + "】日内未进行延期，请及时处理！";
                }
                // 如果资源到期时间还未超过资源到期最长保留时长，则放入回收站
            } else if (System.currentTimeMillis() - relation.getExpiredTime().getTime() < resourceExpireReservedMillis
                    && new Date().after(relation.getExpiredTime())) {
                // 放入回收站
                vmApplyService.recycle(server.getId(), context);
                content = "云主机(" + server.getName() + ")已经到期，云主机被放入回收站，请在【" + resourceExpireReservedMillis / ONE_DAY
                        + "】日内进行延期!";
            } else {
                content = "云主机(" + server.getName() + ")即将到期!剩余时间为：" + residue;
            }
            return new NotifyMessage(context, subject, content, true, false);
        } catch (Exception e) {
            logger.error("Get error message：{}", e.getMessage());
            return null;
        }
    }

}
