// This file is auto-generated, don't edit it. Thanks.
package com.muyu.vehiclegateway.instance;

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DeleteInstancesRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.muyu.common.redis.service.RedisService;
import com.muyu.vehiclegateway.utils.InstanceUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

@Log4j2
@Component
public class DelInstance implements ApplicationListener<ContextClosedEvent> {

    @Autowired
    private RedisService redisService;

    @Autowired
    private InstanceUtil instanceUtil;


    public void delInstance() throws Exception {

        // 创建ECS客户端对象，用于后续调用ECS相关API
        Client client = instanceUtil.createClient();

        List<String> list = redisService.getCacheList("instanceIds");



        // 创建删除实例请求对象，并设置请求参数
        DeleteInstancesRequest deleteInstancesRequest = new DeleteInstancesRequest()
                // 设置地域ID，指定删除实例的地域
                .setRegionId("cn-shanghai")
                // 设置DryRun为true，用于验证请求是否可以成功，但不实际执行删除操作
                .setDryRun(false)
                // 设置Force为true，表示即使实例有正在运行的任务，也强制删除实例
                .setForce(true)
                // 设置TerminateSubscription为true，表示删除按订阅付费的实例时终止订阅
                .setTerminateSubscription(true)
                .setInstanceId(list);

        // 创建运行时选项对象，用于配置运行时的选项参数
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.deleteInstancesWithOptions(deleteInstancesRequest, runtime);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error(error.getMessage());
            // 诊断地址
            log.error(error.getData().get("Recommend"));
            Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error(error.getMessage());
            // 诊断地址
            log.error(error.getData().get("Recommend"));
            Common.assertAsString(error.message);
        }
    }





    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        try {
            log.info("====>删除实例");
            delInstance();
            redisService.deleteObject("instanceIds");
            redisService.deleteObject("instanceList");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
