package employee

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"wechat-api/ent"
	"wechat-api/ent/allocagent"
	"wechat-api/ent/employee"
	"wechat-api/ent/employeeconfig"
	"wechat-api/ent/predicate"
	"wechat-api/internal/utils"
	"wechat-api/internal/utils/dberrorhandler"
	jwtutils "wechat-api/internal/utils/jwt"

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

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

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

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

func (l *GetEmployeeSearchLogic) GetEmployeeSearch(req *types.EmployeeListReq, tokenStr string) (*types.EmployeeListResp, error) {
	//organizationId := l.ctx.Value("organizationId").(uint64)

	var isLogin bool
	claims, err := jwtutils.ParseJwtToken(l.svcCtx.Config.Auth.AccessSecret, tokenStr)
	if err != nil {
		isLogin = false
	}

	var userId string
	var organizationID uint64
	if _, ok := claims["userId"]; ok {
		userId = claims["userId"].(string)
		if userId != "" {
			userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: userId})
			valid := utils.CheckGptLogin(userInfo.RoleIds)
			if valid {
				organizationID = *userInfo.DepartmentId
				isLogin = true
			}
		}
	}

	employeeIds := make([]uint64, 0)
	if isLogin {
		allocAgentItem, err := l.svcCtx.DB.AllocAgent.Query().Where(
			allocagent.UserIDEQ(userId),
		).Only(l.ctx)

		if err == nil && len(allocAgentItem.Agents) > 0 {
			employeeIds = append(employeeIds, allocAgentItem.Agents...)
		}

		if len(employeeIds) == 0 && organizationID > 0 {
			allocAgentItem, err = l.svcCtx.DB.AllocAgent.Query().Where(
				allocagent.OrganizationID(organizationID),
			).First(l.ctx)
			if err == nil && len(allocAgentItem.Agents) > 0 {
				employeeIds = append(employeeIds, allocAgentItem.Agents...)
			}
		}
	}

	var data *ent.EmployeePageList
	if !isLogin || len(employeeIds) == 0 {
		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)
		}
	} else {
		data, err = l.svcCtx.DB.Employee.Query().Where(employee.IDIn(employeeIds...)).WithEmWorkExperiences().WithEmTutorial().Page(l.ctx, req.Page, req.PageSize)
	}

	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 := getEmployeeConfig(l, v.Scene)
		//switchInList := getEmployeeConfig(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,
			})
	}

	return resp, nil
}

func getEmployeeConfig(l *GetEmployeeSearchLogic, 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
}
