package avatar

import (
	"context"
	"encoding/json"
	"fmt"
	avatar20220130 "github.com/alibabacloud-go/avatar-20220130/v2/client"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent/wxcard"
	"wechat-api/hook/aliyun"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetApiAvatarConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetApiAvatarConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApiAvatarConfigLogic {
	return &GetApiAvatarConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetApiAvatarConfigLogic) GetApiAvatarConfig(req *types.AvatarConfigReq) (*types.AvatarConfigResp, error) {
	userId := l.ctx.Value("userId").(uint64)

	card, err := l.svcCtx.DB.WxCard.Query().Where(wxcard.ID(*req.CardId)).Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	if card.AiInfo == "" {
		return nil, errorx.NewInvalidArgumentError("AiInfo is empty")
	}

	var jsonData aliyun.AiTypes
	err = json.Unmarshal([]byte(card.AiInfo), &jsonData)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError(err.Error())
	}

	var aiData *avatar20220130.StartInstanceResponseBodyData
	if jsonData.AiType == 1 { // 阿里云数字人
		aiData, err = aliyun.StartInstance(userId, jsonData)
		fmt.Printf("aliData=%v error=%v \n", aiData, err)
		if err != nil {
			return nil, errorx.NewInternalError(err.Error())
		}

		// 开启的数字人信息入库
		bizId := aliyun.GenerateBizID(userId)
		_, err := l.svcCtx.DB.AliyunAvatar.Create().
			SetNotNilUserID(&userId).
			SetNotNilBizID(&bizId).
			SetNotNilAccessKeyID(&jsonData.AccessKeyId).
			SetNotNilAccessKeySecret(&jsonData.AccessKeySecret).
			SetNotNilAppID(&jsonData.AppId).
			SetNotNilTenantID(tea.Uint64(uint64(jsonData.TenantId))).
			SetNotNilSessionID(aiData.SessionId).
			SetResponse(aiData.String()).
			SetNotNilToken(aiData.Token).
			Save(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
	} else if jsonData.AiType == 2 { //TODO 小冰

	}

	return &types.AvatarConfigResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.AvatarInfo{
			RequestId: aiData.RequestId,
			SessionId: aiData.SessionId,
			Token:     aiData.Token,
			Channel: types.Channel{
				ChannelId:         aiData.Channel.ChannelId,
				Token:             aiData.Channel.Token,
				Type:              aiData.Channel.Type,
				ExpiredTime:       aiData.Channel.ExpiredTime,
				Nonce:             aiData.Channel.Nonce,
				UserId:            aiData.Channel.UserId,
				AppId:             aiData.Channel.AppId,
				UserInfoInChannel: aiData.Channel.UserInfoInChannel,
				Gslb:              aiData.Channel.Gslb,
			},
		},
	}, nil
}
