package alipay

import (
	"encoding/json"
	"errors"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/google/uuid"
	"strings"
)

var (
	_client         *ecs20140526.Client
	RegionId        = "cn-hangzhou"
	AccessKeyId     = "LTAI5tS5pSkUwm6VURuaetxs"
	AccessKeySecret = "iQFIO4MFa7tZ7HbHs0OXOaMDvMozM5"
)

func CreateClient() (_result *ecs20140526.Client, _err error) {
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
	// 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html。
	config := &openapi.Config{
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
		AccessKeyId: tea.String(AccessKeyId),
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
		AccessKeySecret: tea.String(AccessKeySecret),
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Ecs
	config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
	_result = &ecs20140526.Client{}
	_result, _err = ecs20140526.NewClient(config)
	return _result, _err
}

func UpdateAliIp(groupId, ruleId, ip string) (_err error) {
	if _client == nil {
		client, e := CreateClient()
		if e != nil {
			return e
		}
		_client = client
	}

	newUUID, _ := uuid.NewUUID()
	modifySecurityGroupRuleRequest := &ecs20140526.ModifySecurityGroupRuleRequest{
		RegionId:            tea.String(RegionId),
		ClientToken:         tea.String(newUUID.String()),
		SecurityGroupId:     tea.String(groupId),
		SecurityGroupRuleId: tea.String(ruleId),
		SourceCidrIp:        tea.String(ip),
	}
	runtime := &util.RuntimeOptions{}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		_, _err = _client.ModifySecurityGroupRuleWithOptions(modifySecurityGroupRuleRequest, runtime)
		if _err != nil {
			return _err
		}

		return nil
	}()

	if tryErr != nil {
		var err = &tea.SDKError{}
		var _t *tea.SDKError
		if errors.As(tryErr, &_t) {
			err = _t
		}
		// 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
		// 错误 message
		fmt.Println(tea.StringValue(err.Message))
		// 诊断地址
		var data interface{}
		d := json.NewDecoder(strings.NewReader(tea.StringValue(err.Data)))
		e := d.Decode(&data)
		if e != nil {
			return e
		}
		if m, ok := data.(map[string]interface{}); ok {
			recommend, _ := m["Recommend"]
			fmt.Println(recommend)
		}
		_, _err = util.AssertAsString(err.Message)
		if _err != nil {
			return _err
		}
	}
	return _err
}
