package avatar

import (
	"context"
	"encoding/json"
	"fmt"
	avatar20220130 "github.com/alibabacloud-go/avatar-20220130/v2/client"
	"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 SendApiAvatarTextLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *SendApiAvatarTextLogic) SendApiAvatarText(req *types.SendTextReq) (*types.SendTextResp, error) {
	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.SendTextResponseBodyData
	aiData, err = aliyun.SendText(*req.SessionId, *req.Text, *req.IsStream, *req.Index, *req.Position, jsonData)
	fmt.Printf("aliData=%v error=%v \n", aiData, err)
	if err != nil {
		return nil, errorx.NewInternalError(err.Error())
	}

	return &types.SendTextResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.SendText{
			UniqueCode: aiData.UniqueCode,
			SessionId:  aiData.SessionId,
		},
	}, nil
}
