package com.muyu.car.instance;

import com.aliyun.ecs20140526.models.*;
import com.aliyun.tea.TeaException;
import com.muyu.car.domain.example.ExampleInformation;
import com.muyu.common.redis.service.RedisService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

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

/**
 * 项目启动创建实例
 * @Author：蓬叁
 * @Package：com.muyu.car.domain
 * @Project：cloud-server-8
 * @name：GenerateInstance
 * @Date：2024/9/29 上午10:42
 */
@Component
@Log4j2
@Tag(name = "启动时创建实例")
public class GenerateInstance implements ApplicationRunner {

    @Autowired private RedisService redisService;

    /**
     * 启动自动创建实例
     * @throws Exception
     */
    public static List<String> generateInstance() throws Exception {

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

        com.aliyun.ecs20140526.models.RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new com.aliyun.ecs20140526.models.RunInstancesRequest.RunInstancesRequestSystemDisk()
                .setSize("40")
                .setCategory("cloud_essd");
        com.aliyun.ecs20140526.models.RunInstancesRequest runInstancesRequest = new com.aliyun.ecs20140526.models.RunInstancesRequest()
                // 设置地域ID
                .setRegionId("cn-hangzhou")
                // 设置镜像ID
                .setImageId("m-bp1hkxfctk751s62jqhq")
                // 设置实例类型
                .setInstanceType("ecs.t6-c1m1.large")
                // 设置安全组ID
                .setSecurityGroupId("sg-bp1a7fk8js5pn3fw9p2m")
                // 设置虚拟交换机ID
                .setVSwitchId("vsw-bp193np7r01vssqxhh24e")
                // 设置实例名称
                .setInstanceName("server-mqtt")
                // 设置实例付费类型为后付费按量付费
                .setInstanceChargeType("PostPaid")
                // 设置互联网最大出带宽为1 Mbps
                .setInternetMaxBandwidthOut(1)
                // 设置系统盘配置
                .setSystemDisk(systemDisk)
                // 设置主机名
                .setHostName("root")
                // 设置实例密码
                .setPassword("EightGroup123.")
                // 设置创建实例的数量
                .setAmount(2);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RunInstancesResponse runInstancesResponse = client.runInstancesWithOptions(runInstancesRequest, runtime);
            // 获取body返回值对象
            RunInstancesResponseBody body = runInstancesResponse.getBody();
            ArrayList<String> list = new ArrayList<>();
            // 得到实例ID数组
            for (String instance : body.getInstanceIdSets().getInstanceIdSet()) {
                list.add(instance);
            }
            log.info("实例ID:{}",list);
            return list;
        } 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);
        }
        return null;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> InstanceIds = generateInstance();
        log.info("创建实例成功");
        log.info("正在加载实例");
        Thread.sleep(30000);
        List<ExampleInformation> exampleInformations = QueryInstance.queryInstance(InstanceIds);
        log.info("加载成功");
        ArrayList<String> list = new ArrayList<>();
        for (ExampleInformation exampleInformation : exampleInformations) {
            redisService.setCacheObject("InstanceIdKey:"+exampleInformation.getInstanceId(),exampleInformation);
            list.add(exampleInformation.getIpAddress());
        }
        redisService.setCacheList("ipList",list);
        log.info("实例信息:{}",exampleInformations);
    }

}

