package com.muyu.car.instance;

import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
import com.aliyun.ecs20140526.models.RunInstancesResponseBody;
import com.aliyun.tea.*;
import com.aliyun.teautil.models.RuntimeOptions;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Set;

/**
 * 项目关闭清除实例
 * @Author：蓬叁
 * @Package：com.muyu.car.domain
 * @Project：cloud-server-8
 * @name：DelInstance
 * @Date：2024/9/29 上午10:42
 */
@Log4j2
@Component
@Tag(name = "程序停止删除实例")
public class DelInstance implements DisposableBean {

    public static void delInstance() throws Exception {
        // 创建ECS客户端对象，用于后续调用ECS相关API
        com.aliyun.ecs20140526.Client client = CreateClient.createClient();
        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
                .setRegionId("cn-hangzhou");
        //创建运行时选择对象,用于配置运行时的选项参数
        RuntimeOptions runtimeOptions = new RuntimeOptions();

        //获取实例列表
        DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtimeOptions);

        //提取实例ID集合
        ArrayList<String> list = new ArrayList<>();
        DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
        for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : body.getInstances().getInstance()) {
            list.add(instance.getInstanceId());
        }
        log.info("Instance IDs: " + list);
        // 创建删除实例请求对象，并设置请求参数
        com.aliyun.ecs20140526.models.DeleteInstancesRequest deleteInstancesRequest = new com.aliyun.ecs20140526.models.DeleteInstancesRequest()
                //设置地域ID，指定删除实例的地域
                .setRegionId("cn-hangzhou")
                // 设置DryRun为true,用于验证请求是否可以成功，但不实际执行删除操作
                .setDryRun(false)
                // 设置Force为true，表示即使实例有正在运行的任务，也强制删除实例
                .setForce(true)
                // 设置TerminateSubscription为true，表示删除按订阅付费的实例时终止订阅
                .setTerminateSubscription(true)
                .setInstanceId(list);

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

    }

    @Override
    public void destroy() throws Exception {
        log.info("===============>开始执行删除实例方法");
        delInstance();
        // 连接到Redis服务器
        Jedis jedis = new Jedis("159.75.188.178", 6379);
        // 指定要删除的文件夹（命名空间）
        String namespace = "InstanceIdKey:";
        // 获取所有以namespace为前缀的键
        Set<String> keys = jedis.keys(namespace + "*");
        // 如果存在键，则删除它们
        if (keys.size() > 0) {
            jedis.del(keys.toArray(new String[0]));
        }
        // 关闭连接
        jedis.close();
    }
}
