package employee

import (
	"context"
	"time"
	"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 UpdateEmployeeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdateEmployeeLogic) UpdateEmployee(req *types.EmployeeInfo) (*types.BaseMsgResp, error) {
	// 开始事务
	tx, err := l.svcCtx.DB.Tx(context.Background())

	_, err = tx.Employee.UpdateOneID(*req.Id).
		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).
		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 {
		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
			}

			_, err = tx.WorkExperience.UpdateOneID(*work.Id).
				SetNotNilStartDate(startDate).
				SetNotNilEndDate(endDate).
				SetNotNilCompany(work.Company).
				SetNotNilExperience(work.Experience).
				Save(l.ctx)

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

	// 批量修改使用教程
	if len(req.Tutorial) > 0 {
		for _, tt := range req.Tutorial {
			_, err = tx.Tutorial.UpdateOneID(*tt.Id).
				SetNotNilIndex(tt.Index).
				SetNotNilTitle(tt.Title).
				SetNotNilContent(tt.Content).
				Save(l.ctx)

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

	_ = tx.Commit()

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