package employee

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent/employee"
	"wechat-api/ent/predicate"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *GetApiEmployeeListLogic) GetApiEmployeeList(req *types.EmployeeListReq) (*types.EmployeeListResp, error) {
	var predicates []predicate.Employee
	if req.CategoryId != nil && *req.CategoryId > 0 {
		predicates = append(predicates, employee.CategoryID(*req.CategoryId))
	}
	data, err := l.svcCtx.DB.Employee.Query().Where(predicates...).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 {
		var showChat, isVip bool
		if v.APIKey != "" && v.APIBase != "" {
			showChat = true
		}
		if v.IsVip != 0 {
			isVip = true
		}

		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,
				SwitchIn:         &v.SwitchIn,
				VideoUrl:         &v.VideoURL,
				CategoryId:       &v.CategoryID,
				ShowChat:         &showChat,
				IsVip:            &isVip,
			})
	}

	return resp, nil
}
