package employee

import (
	"context"
	"github.com/spf13/cast"
	"strings"
	"wechat-api/ent/employee"
	"wechat-api/ent/employeeconfig"

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

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

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetEmployeeByIdLogic) GetEmployeeById(req *types.IDReq) (*types.EmployeeInfoResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	data, err := l.svcCtx.DB.Employee.Query().WithEmWorkExperiences().WithEmTutorial().Where(employee.ID(req.Id), employee.OrganizationIDEQ(organizationId)).Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	workExperience := make([]types.WorkExperienceInfo, 0, len(data.Edges.EmWorkExperiences))
	for _, work := range data.Edges.EmWorkExperiences {
		workExperience = append(workExperience, types.WorkExperienceInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &work.ID,
				CreatedAt: pointy.GetPointer(work.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(work.UpdatedAt.UnixMilli()),
			},
			EmployeeId:   &work.EmployeeID,
			Company:      &work.Company,
			StartDate:    pointy.GetPointer(work.StartDate.UnixMilli()),
			StartDateStr: pointy.GetPointer(work.StartDate.Format("2006-01-02 15:04:05")),
			EndDate:      pointy.GetPointer(work.EndDate.UnixMilli()),
			EndDateStr:   pointy.GetPointer(work.EndDate.Format("2006-01-02 15:04:05")),
			Experience:   &work.Experience,
		})
	}

	tutorial := make([]types.TutorialInfo, 0, len(data.Edges.EmTutorial))
	for _, tt := range data.Edges.EmTutorial {
		tutorial = append(tutorial, types.TutorialInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &tt.ID,
				CreatedAt: pointy.GetPointer(tt.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(tt.UpdatedAt.UnixMilli()),
			},
			EmployeeId: &tt.EmployeeID,
			Content:    &tt.Content,
			Title:      &tt.Title,
			Index:      &tt.Index,
		})
	}

	// 分别获得 scene 和 switch_in 的列表
	sceneList := getEmployeeConfigList(l, data.Scene)
	switchInList := getEmployeeConfigList(l, data.SwitchIn)

	return &types.EmployeeInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.EmployeeInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Title:            &data.Title,
			Avatar:           &data.Avatar,
			Tags:             &data.Tags,
			HireCount:        &data.HireCount,
			ServiceCount:     &data.ServiceCount,
			AchievementCount: &data.AchievementCount,
			Intro:            &data.Intro,
			Estimate:         &data.Estimate,
			Skill:            &data.Skill,
			AbilityType:      &data.AbilityType,
			Scene:            &data.Scene,
			SceneList:        sceneList,
			Tutorial:         tutorial,
			SwitchIn:         &data.SwitchIn,
			SwitchInList:     switchInList,
			VideoUrl:         &data.VideoURL,
			WorkExperience:   workExperience,
			CategoryId:       &data.CategoryID,
			ApiBase:          &data.APIBase,
			ApiKey:           &data.APIKey,
		},
	}, nil
}

func FormatIds(str string) []uint64 {
	str = strings.Trim(str, " ")
	idsArray := strings.Split(str, ",")
	idArray := make([]uint64, 0, len(idsArray))
	for _, idstr := range idsArray {
		idArray = append(idArray, cast.ToUint64(idstr))
	}

	return idArray
}

func getEmployeeConfigList(l *GetEmployeeByIdLogic, ids string) []types.EmployeeConfigInfo {
	sceneList := make([]types.EmployeeConfigInfo, 0)

	sceneIds := FormatIds(ids)

	if len(sceneIds) == 0 {
		return sceneList
	}

	employeeConfigList, err := l.svcCtx.DB.EmployeeConfig.Query().Where(
		employeeconfig.IDIn(sceneIds...),
	).All(l.ctx)

	if err == nil && len(employeeConfigList) > 0 {
		for _, val := range employeeConfigList {
			sceneList = append(sceneList, types.EmployeeConfigInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &val.ID,
					CreatedAt: pointy.GetPointer(val.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(val.UpdatedAt.UnixMilli()),
				},
				Stype: &val.Stype,
				Title: &val.Title,
				Photo: &val.Photo,
			})
		}
	}

	return sceneList
}