package employee

import (
	"context"
	"time"
	"wechat-api/ent"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

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

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

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

func (l *CreateEmployeeLogic) CreateEmployee(req *types.EmployeeInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	// 开始事务
	tx, err := l.svcCtx.DB.Tx(context.Background())

	employee, err := tx.Employee.Create().
		SetNotNilTitle(req.Title).
		SetNotNilAvatar(req.Avatar).
		SetNotNilTags(req.Tags).
		SetNotNilHireCount(req.HireCount).
		SetNotNilServiceCount(req.ServiceCount).
		SetNotNilAchievementCount(req.AchievementCount).
		SetNotNilIntro(req.Intro).
		SetNotNilEstimate(req.Estimate).
		SetNotNilSkill(req.Skill).
		SetNotNilAbilityType(req.AbilityType).
		SetNotNilScene(req.Scene).
		SetNotNilSwitchIn(req.SwitchIn).
		SetNotNilVideoURL(req.VideoUrl).
		SetNotNilOrganizationID(&organizationId).
		SetNotNilCategoryID(req.CategoryId).
		SetNotNilAPIBase(req.ApiBase).
		SetNotNilAPIKey(req.ApiKey).
		SetNotNilChatURL(req.ChatUrl).
		Save(l.ctx)

	if err != nil {
		_ = tx.Rollback()
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 批量插入工作经历
	if len(req.WorkExperience) > 0 {
		bulkCreateWork := make([]*ent.WorkExperienceCreate, 0, len(req.WorkExperience))
		for _, work := range req.WorkExperience {
			var startDate, endDate *time.Time
			startDateStr, _ := time.Parse("2006-01-02 15:04:05", *work.StartDateStr)

			startDate = &startDateStr
			if work.EndDateStr != nil && *work.EndDateStr != "" {
				endDateStr, _ := time.Parse("2006-01-02 15:04:05", *work.EndDateStr)
				endDate = &endDateStr
			}

			bulkCreateWork = append(bulkCreateWork, tx.WorkExperience.Create().
				SetNotNilEmployeeID(&employee.ID).
				SetNotNilStartDate(startDate).
				SetNotNilEndDate(endDate).
				SetNotNilCompany(work.Company).
				SetNotNilOrganizationID(&organizationId).
				SetNotNilExperience(work.Experience),
			)
		}

		if len(bulkCreateWork) > 0 {
			err = tx.WorkExperience.CreateBulk(bulkCreateWork...).Exec(l.ctx)
			if err != nil {
				_ = tx.Rollback()
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
			}
		}
	}

	// 批量插入使用教程
	if len(req.Tutorial) > 0 {
		bulkCreateTutorial := make([]*ent.TutorialCreate, 0, len(req.Tutorial))
		for _, work := range req.Tutorial {
			bulkCreateTutorial = append(bulkCreateTutorial, tx.Tutorial.Create().
				SetNotNilEmployeeID(&employee.ID).
				SetNotNilOrganizationID(&organizationId).
				SetNotNilIndex(work.Index).
				SetNotNilTitle(work.Title).
				SetNotNilContent(work.Content),
			)
		}
		if len(bulkCreateTutorial) > 0 {
			err = tx.Tutorial.CreateBulk(bulkCreateTutorial...).Exec(l.ctx)
			if err != nil {
				_ = tx.Rollback()
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
			}
		}
	}

	_ = tx.Commit()

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