package com.muyu.vehiclegateway.utils;

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiHongDao
 * @name：InstanceUtil
 * @Date：2024/9/28 22:25
 */
@Component
public class InstanceUtil {


    /**
     * <b>description</b> :
     * <p>使用AK&amp;SK初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint 请参考 https://api.aliyun.com/product/Ecs
        config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }


    /**
     * 查询所有的实例ID
     * @return
     */
    public List<String> selectAllInstancesId() {
        ArrayList<String> list = new ArrayList<>();

        try {
            Client client = createClient();

            //创建运行时选择对象,用于配置运行时的选项参数
            RuntimeOptions runtimeOptions = new RuntimeOptions();

            DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
                    .setRegionId("cn-shanghai");
            //获取实例列表
            DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtimeOptions);

            //提取实例ID集合

            DescribeInstancesResponseBody body = describeInstancesResponse.getBody();

            for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : body.getInstances().getInstance()) {
                list.add(instance.getInstanceId());
            }

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

    }

}
