package com.muyu.cargateway.utils;

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DeleteInstanceRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ Tool：IntelliJ IDEA
 * @ Author：CHX
 * @ Date：2024-10-02-16:04
 * @ Version：1.0
 * @ Description：ecs实例工具类
 * @author Lenovo
 */
@Log4j2
public class ECSTool {

    public static final String ACCESS_KEY_ID = "LTAI5tDH3FyRx4PRr6anx2TL";
    public static final String ACCESS_KEY_SECRET = "xdQnX2tDattY50raNkUWmHzE2tondP";

    public static Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(ACCESS_KEY_ID)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        // Endpoint 请参考 https://api.aliyun.com/product/Ecs
        config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }
    public static void runEcsInstance(String regionId, String launchTemplateId) throws Exception {
        Client client = ECSTool.createClient();
        RunInstancesRequest request = new RunInstancesRequest();
        request.setRegionId(regionId)
                .setLaunchTemplateId(launchTemplateId);
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        try{
            client.runInstancesWithOptions(request, runtimeOptions);
        }catch (Exception error){
            // 处理API调用过程中出现的异常
            System.out.println(error.getMessage());
            if (error instanceof TeaException) {
                // 处理特定类型的异常，如TeaException
                TeaException teaError = (TeaException) error;
                // 打印诊断推荐链接
                System.out.println(teaError.getData().get("Recommend"));
                // 断言错误信息
                Common.assertAsString(teaError.getMessage());
            } else {
                // 处理其他类型的异常
                System.out.println(error.getMessage());
            }
        }
    }

    /**
     *销毁实例
     */
    public static void runEcsRemove(String instanceId) throws Exception {
        Client client = ECSTool.createClient();
        DeleteInstanceRequest deleteInstancesRequest = new DeleteInstanceRequest();
        deleteInstancesRequest.setInstanceId(instanceId);
        RuntimeOptions runtimeOptions = new RuntimeOptions();

        try {
            // 复制代码运行请自行打印 API 的返回值
            client.deleteInstanceWithOptions(deleteInstancesRequest, runtimeOptions);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            Common.assertAsString(error.message);
        }
    }

    /**
     * 查询实例列表
     * @param regionId 地域ID
     */
    public static List<String> findInstance(String regionId) throws Exception {
        Client client = ECSTool.createClient();
        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
        describeInstancesRequest.setRegionId(regionId);
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        List<String> stringArrayList = new ArrayList<>();
        try {
            DescribeInstancesResponse response = client.describeInstancesWithOptions(describeInstancesRequest, runtimeOptions);
            List<List<String>> ipListList = response.getBody().instances.getInstance().stream().map(instance -> instance.publicIpAddress.ipAddress).collect(Collectors.toList());
            for (List<String> strings : ipListList) {
                for (String ip : strings) {
                    stringArrayList.add(ip);
                }
                return stringArrayList;
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
          Common.assertAsString(error.message);
        }
        return null;
    }
}
