package aliyun

import (
	"encoding/json"
	"errors"
	"fmt"
	avatar20220130 "github.com/alibabacloud-go/avatar-20220130/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-common/utils/uuidx"
	"strconv"
	"strings"
	"wechat-api/internal/utils/jwt"
)

// CreateAvatarClient 使用AK&SK初始化账号Client
// @return Client
// @throws Exception
func CreateAvatarClient(accessKeyId, accessKeySecret string) (_result *avatar20220130.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/avatar
	config.Endpoint = tea.String("avatar.cn-zhangjiakou.aliyuncs.com")
	_result = &avatar20220130.Client{}
	_result, _err = avatar20220130.NewClient(config)
	return _result, _err
}

// StartInstance 启动数字人
func StartInstance(userId uint64, jsonData AiTypes) (*avatar20220130.StartInstanceResponseBodyData, error) {
	accessKeyId := jsonData.AccessKeyId
	accessKeySecret := jsonData.AccessKeySecret
	tenantId := jsonData.TenantId
	appId := jsonData.AppId
	bizId := GenerateBizID(userId)
	userIdStr := strconv.Itoa(int(userId))

	client, _err := CreateAvatarClient(accessKeyId, accessKeySecret)
	if _err != nil {
		return nil, _err
	}

	startInstanceRequest := &avatar20220130.StartInstanceRequest{
		TenantId: tea.Int64(int64(tenantId)),
		App: &avatar20220130.StartInstanceRequestApp{
			AppId: tea.String(appId),
		},
		User: &avatar20220130.StartInstanceRequestUser{
			UserId: tea.String(userIdStr),
		},
		BizId: tea.String(bizId),
	}

	_result, _err := client.StartInstance(startInstanceRequest)
	if _err != nil {
		return nil, _err
	}
	if *_result.Body.Success {
		//fmt.Println(_result.Body.Data)
		return _result.Body.Data, nil
	}
	return nil, errors.New(*_result.Body.Message)
}

// SendText 发送消息
func SendText(sessionId, text string, isStream bool, index int32, position string, jsonData AiTypes) (*avatar20220130.SendTextResponseBodyData, error) {
	accessKeyId := jsonData.AccessKeyId
	accessKeySecret := jsonData.AccessKeySecret
	tenantId := jsonData.TenantId

	client, _err := CreateAvatarClient(accessKeyId, accessKeySecret)
	if _err != nil {
		return nil, _err
	}

	unicodeCode := uuidx.NewUUID().String()
	sendTextRequest := &avatar20220130.SendTextRequest{
		TenantId:   tea.Int64(int64(tenantId)),
		SessionId:  &sessionId,
		UniqueCode: &unicodeCode,
		Text:       &text,
	}
	if isStream == true {
		sendTextRequest.StreamExtension = &avatar20220130.SendTextRequestStreamExtension{
			Index:    &index,
			Position: &position,
			IsStream: &isStream,
		}
	}

	_result, _err := client.SendText(sendTextRequest)
	if _err != nil {
		return nil, _err
	}
	if *_result.Body.Success {
		//fmt.Println(_result.Body.Data)
		return _result.Body.Data, nil
	}
	return nil, errors.New(*_result.Body.Message)
}

// StopInstance 停止数字人
func StopInstance(sessionId string, jsonData AiTypes) (*avatar20220130.StopInstanceResponseBodyData, error) {
	accessKeyId := jsonData.AccessKeyId
	accessKeySecret := jsonData.AccessKeySecret
	tenantId := jsonData.TenantId

	client, _err := CreateAvatarClient(accessKeyId, accessKeySecret)
	if _err != nil {
		return nil, _err
	}

	stopInstanceRequest := &avatar20220130.StopInstanceRequest{
		TenantId:  tea.Int64(int64(tenantId)),
		SessionId: &sessionId,
	}

	_result, _err := client.StopInstance(stopInstanceRequest)
	if _err != nil {
		return nil, _err
	}
	if *_result.Body.Success {
		//fmt.Println(_result.Body.Data)
		return _result.Body.Data, nil
	}
	return nil, errors.New(*_result.Body.Message)
}

// QueryRunningInstance 查询运行中的实例列表
func QueryRunningInstance(jsonData AiTypes) (*avatar20220130.QueryRunningInstanceResponseBody, error) {
	accessKeyId := jsonData.AccessKeyId
	accessKeySecret := jsonData.AccessKeySecret
	appId := jsonData.AppId
	tenantId := jsonData.TenantId

	client, _err := CreateAvatarClient(accessKeyId, accessKeySecret)
	if _err != nil {
		return nil, _err
	}

	queryRunningInstanceRequest := &avatar20220130.QueryRunningInstanceRequest{
		App: &avatar20220130.QueryRunningInstanceRequestApp{
			AppId: tea.String(appId),
		},
		TenantId: tea.Int64(int64(tenantId)),
	}

	_result, _err := client.QueryRunningInstance(queryRunningInstanceRequest)
	if _err != nil {
		return nil, _err
	}
	if *_result.Body.Success {
		//fmt.Println(_result.Body.Data)
		return _result.Body, nil
	}
	return nil, errors.New(*_result.Body.Message)
}

func _main(args []*string) (_err error) {
	client, _err := CreateAvatarClient("", "")
	if _err != nil {
		return _err
	}

	sendMessageRequest := &avatar20220130.SendMessageRequest{
		SessionId: tea.String("your_value"),
		TenantId:  tea.Int64(1),
		Feedback:  tea.Bool(false),
	}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		_, _err = client.SendMessageWithOptions(sendMessageRequest, &util.RuntimeOptions{})
		if _err != nil {
			return _err
		}

		return nil
	}()

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

// GenerateBizID 业务请求id，最大支持 64 位字符
// （注意 可以使用该字段做业务启动数字人的幂等，服务端确保同一个 bizId 多次调用只会开启一路实例）
// 鉴于以上原因这里确保每个用户只启动一个实例
func GenerateBizID(userId uint64) string {
	return jwt.HashidsEncode(int(userId))
}

// GetAccessKeyId 获取AccessKeyId
func GetAccessKeyId() string {
	return "LTAI5tET2mMQVTcMDftuM8Cp"
}

// GetAccessKeySecret 获取AccessKeySecret
func GetAccessKeySecret() string {
	return "AmGsD8VzwEuj8njZpUCUYnK7uUBTJa"
}

// GetAppId 获取AppId
func GetAppId() string {
	return "3dt553bl52"
}

// GetTenantId 租户ID
func GetTenantId() int64 {
	return int64(27174)
}

//func main() {
//	err := _main(tea.StringSlice(os.Args[1:]))
//	if err != nil {
//		panic(err)
//	}
//}
