package department

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

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

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

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

func (l *CreateDepartmentLogic) CreateDepartment(req *types.DepartmentInfo) (resp *types.BaseMsgResp, err error) {
	department_info, err := l.svcCtx.CoreRpc.CreateDepartment(l.ctx, &core.DepartmentInfo{
		Id:        req.Id,
		Sort:      req.Sort,
		Name:      req.Name,
		Ancestors: req.Ancestors,
		Leader:    req.Leader,
		Phone:     req.Phone,
		Email:     req.Email,
		Remark:    req.Remark,
		ParentId:  req.ParentId,
	})
	if err != nil {
		return nil, err
	}

	//创建 fastgpt 用户
	user_info := &users.Users{
		Status:        "active",
		Username:      fmt.Sprintf("%d", department_info.Id),
		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.Name,
		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
}
