// 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.*;
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.domain.Instance;
import com.muyu.vehiclegateway.utils.InstanceUtil;
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;

@Log4j2
@Component
public class GenerateInstance implements ApplicationRunner {


    @Autowired
    private RedisService redisTemplate;

    @Autowired
    private InstanceUtil instanceUtil;

    /**
     * 本程序的入口点
     * 主要功能是创建阿里云ECS实例
     *
     * @throws Exception 如果执行过程中发生错误则抛出异常
     */
    public  void generateInstance() throws Exception {

        // 创建阿里云ECS客户端
        Client client = instanceUtil.createClient();
        // 配置系统盘参数
        RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk()
                .setSize("20") // 设置系统盘大小为40GB
                .setCategory("cloud_essd"); // 设置系统盘类型为cloud_essd
        // 创建创建实例请求对象并设置参数
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
                .setRegionId("cn-shanghai") // 设置地域ID
                .setImageId("m-uf65fhjzbd3nq22twh8j") // 设置镜像ID
                .setInstanceType("ecs.t6-c1m1.large") // 设置实例类型
                .setSecurityGroupId("sg-uf68j9psn6catmhhgda9") // 设置安全组ID
                .setVSwitchId("vsw-uf609yqm5q5j15nvpfmjs") // 设置虚拟交换机ID
                .setInstanceName("server-mqtt") // 设置实例名称
                .setInstanceChargeType("PostPaid") // 设置实例付费类型为后付费按量付费
                .setSystemDisk(systemDisk) // 设置系统盘配置
                .setHostName("root") // 设置主机名
                .setPassword("TwoGroup123.") // 设置实例密码
                .setAmount(2) // 设置创建实例的数量
                // 设置互联网计费类型为按流量计费
                .setInternetChargeType("PayByTraffic")
                // 设置互联网最大出带宽为1 Mbps
                .setInternetMaxBandwidthOut(1);



        // 创建运行时选项对象
        RuntimeOptions runtime = new RuntimeOptions();

        // 尝试执行创建实例请求
        try {

            RunInstancesResponse runInstancesResponse = client.runInstancesWithOptions(runInstancesRequest, runtime);
            RunInstancesResponseBody body = runInstancesResponse.getBody();
            RunInstancesResponseBody.RunInstancesResponseBodyInstanceIdSets instanceIdSets = body.getInstanceIdSets();

            List<Instance> instanceList = new ArrayList<>();
            List<String> instanceIds = new ArrayList<>();

            for (String instanceId : instanceIdSets.instanceIdSet) {
                instanceIds.add(instanceId);
            }

            Thread.sleep(20000);

            DescribeInstancesResponse describeInstancesResponse = queryInstanceDetails(client);
            log.info("====>创建的实例id:"+instanceIds);
            // 获取实例的ID、公网IP和状态

            List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> bodyInstancesInstances = describeInstancesResponse.getBody().getInstances().getInstance();
            for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : bodyInstancesInstances) {
                String id = instance.getInstanceId();
                String ipAddress = instance.getPublicIpAddress().getIpAddress().toString();
                String status = instance.getStatus();
                Instance instance1 = new Instance(id,ipAddress,status);
                instanceList.add(instance1);
            }


            log.info("====>创建的实例集合:"+instanceList);



            redisTemplate.setCacheList("instanceList",instanceList);
            redisTemplate.setCacheList("instanceIds",instanceIds);

//            List<ConnectWeight> weightArrayList = new ArrayList<>();
//
//            for (String instanceId : instanceIds) {
//                processIp(instanceId,weightArrayList)
//            }



        } 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);
        }
    }


    private static DescribeInstancesResponse queryInstanceDetails(Client client) {

        // 创建查询实例请求对象并设置参数
        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
                .setInstanceName("server-mqtt")
                .setRegionId("cn-shanghai"); // 设置地域ID // 设置实例ID
        // 创建运行时选项对象
        RuntimeOptions runtime = new RuntimeOptions();

        // 尝试执行查询实例请求
        try {
            return client.describeInstancesWithOptions(describeInstancesRequest, runtime);
        } catch (TeaException e) {
            // 捕获特定的TeaException并打印详细信息
            log.info("TeaException occurred: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            // 捕获其他所有异常
            log.info("An error occurred: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("===============>开始执行创建实例方法");

        generateInstance();

    }







}
