package employee

import (
	"context"
	"wechat-api/ent/employeeconfig"

	"wechat-api/ent/employee"
	"wechat-api/ent/predicate"
	"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 GetEmployeeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetEmployeeListLogic) GetEmployeeList(req *types.EmployeeListReq) (*types.EmployeeListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	var predicates []predicate.Employee
	predicates = append(predicates, employee.OrganizationIDEQ(organizationId))

	if req.Title != nil && *req.Title != "" {
		predicates = append(predicates, employee.TitleContains(*req.Title))
	}
	if req.CategoryId != nil && *req.CategoryId > 0 {
		predicates = append(predicates, employee.CategoryIDEQ(*req.CategoryId))
	}
	data, err := l.svcCtx.DB.Employee.Query().Where(predicates...).WithEmWorkExperiences().WithEmTutorial().Page(l.ctx, req.Page, req.PageSize)

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

	resp := &types.EmployeeListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		workExperience := make([]types.WorkExperienceInfo, 0, len(v.Edges.EmWorkExperiences))
		for _, work := range v.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(v.Edges.EmTutorial))
		for _, tt := range v.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,
			})
		}

		sceneList := getEmployeeConfigListByIds(l, v.Scene)
		switchInList := getEmployeeConfigListByIds(l, v.SwitchIn)

		resp.Data.Data = append(resp.Data.Data,
			types.EmployeeInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Title:            &v.Title,
				Avatar:           &v.Avatar,
				Tags:             &v.Tags,
				HireCount:        &v.HireCount,
				ServiceCount:     &v.ServiceCount,
				AchievementCount: &v.AchievementCount,
				Intro:            &v.Intro,
				Estimate:         &v.Estimate,
				Skill:            &v.Skill,
				AbilityType:      &v.AbilityType,
				Scene:            &v.Scene,
				SceneList:        sceneList,
				SwitchIn:         &v.SwitchIn,
				SwitchInList:     switchInList,
				Tutorial:         tutorial,
				VideoUrl:         &v.VideoURL,
				WorkExperience:   workExperience,
				CategoryId:       &v.CategoryID,
				ApiBase:          &v.APIBase,
				ApiKey:           &v.APIKey,
				ChatUrl:          &v.ChatURL,
			})
	}

	return resp, nil
}

func getEmployeeConfigListByIds(l *GetEmployeeListLogic, 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
}
