package fastgpt

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"time"
	team_members "wechat-api/mongo_model/team_members"
	teams "wechat-api/mongo_model/teams"
	users "wechat-api/mongo_model/users"

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

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

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

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

func (l *CreateFastgptLogic) CreateFastgpt(req *types.CreateInfo) (resp *types.BaseMsgResp, err error) {
	//创建 fastgpt 用户
	user_info := &users.Users{
		Status:        "active",
		Username:      req.UserName,
		Password:      "838b0ad79fa89e8b3a0cfdc6eab90ac24d20e30ca862855b93a4c736f8cdfedf",
		Avatar:        "/icon/human.svg",
		Balance:       int32(200000),
		PromotionRate: int32(15),
		Timezone:      "Asia/Shanghai",
	}
	err = l.svcCtx.MongoModel.UsersModel.Insert(context.TODO(), user_info)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("fastgpt create failed " + err.Error())
	}

	// 创建团队
	teams_info := &teams.Teams{
		Name:              *req.Title,
		OwnerID:           user_info.ID,
		DefaultPermission: int32(0),
		Avatar:            "/icon/logo.svg",
		CreateTime:        time.Date(2024, 7, 10, 12, 0, 18, 197000000, time.UTC),
		Balance:           int32(999900000),
	}

	err = l.svcCtx.MongoModel.TeamsModel.Insert(context.TODO(), teams_info)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("fastgpt create failed " + err.Error())
	}

	// 创建团队关系
	team_members_info := &team_members.TeamMembers{
		TeamID:      teams_info.ID,
		UserID:      user_info.ID,
		Name:        "Owner",
		Role:        "owner",
		Status:      "active",
		CreateTime:  time.Date(2024, 7, 10, 12, 0, 18, 197000000, time.UTC),
		DefaultTeam: true,
		Version:     int32(0),
	}

	err = l.svcCtx.MongoModel.TeamMembersModel.Insert(context.TODO(), team_members_info)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("fastgpt create failed " + err.Error())
	}

	return &types.BaseMsgResp{Msg: errormsg.Success}, nil
}
