package wxcardvisit

import (
	"context"
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent"
	"wechat-api/ent/employee"
	"wechat-api/ent/predicate"
	"wechat-api/ent/wxcard"
	"wechat-api/ent/wxcarduser"
	"wechat-api/ent/wxcardvisit"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *GetWxCardVisitListLogic) GetWxCardVisitList(req *types.WxCardVisitListReq) (*types.WxCardVisitListResp, error) {
	var predicates []predicate.WxCardVisit
	if req.BotType != nil && *req.BotType > 0 {
		predicates = append(predicates, wxcardvisit.BotType(*req.BotType))
	}

	if req.BotId != nil && *req.BotId > 0 {
		predicates = append(predicates, wxcardvisit.BotID(*req.BotId))
	}
	data, err := l.svcCtx.DB.WxCardVisit.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	wxIds, cardIds, agentIds := make([]uint64, 0), make([]uint64, 0), make([]uint64, 0)
	wxCardList := make(map[uint64]*ent.WxCard)
	wxAgentList := make(map[uint64]*ent.Employee)
	for _, v := range data.List {
		if v.BotType == 1 {
			wxIds = append(wxIds, v.BotID)
		} else if v.BotType == 2 {
			cardIds = append(cardIds, v.BotID)
		} else {
			agentIds = append(agentIds, v.BotID)
		}
	}
	if len(cardIds) > 0 {
		cardList, _ := l.svcCtx.DB.WxCard.Query().Where(wxcard.IDIn(cardIds...)).All(l.ctx)
		for _, val := range cardList {
			wxCardList[val.ID] = val
		}
	}
	if len(agentIds) > 0 {
		agentList, _ := l.svcCtx.DB.Employee.Query().Where(employee.IDIn(agentIds...)).All(l.ctx)
		for _, val := range agentList {
			wxAgentList[val.ID] = val
		}
	}

	for _, v := range data.List {
		cardInfo := types.WxCardSimpleInfo{}
		botType := ""
		if v.BotType == 1 {

		} else if v.BotType == 2 {
			if card, ok := wxCardList[v.BotID]; ok {
				cardInfo.Name = &card.Name
				cardInfo.Avatar = &card.Avatar
				botType = "名片"
				cardInfo.Type = &botType
			}
		} else {
			if agentItem, ok := wxAgentList[v.BotID]; ok {
				cardInfo.Name = &agentItem.Title
				cardInfo.Avatar = tea.String("")
				botType = "数字员工"
				cardInfo.Type = &botType
			}
		}
		userName := ""
		userInfo, _ := l.svcCtx.DB.WxCardUser.Query().Where(wxcarduser.ID(v.UserID)).First(l.ctx)
		if userInfo != nil {
			userName = userInfo.Nickname
		} else {
			userName = fmt.Sprintf("用户_%d", v.UserID)
		}
		resp.Data.Data = append(resp.Data.Data,
			types.WxCardVisitInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				UserId:   &v.UserID,
				UserName: &userName,
				BotId:    &v.BotID,
				BotType:  &v.BotType,
				CardInfo: cardInfo,
			})
	}

	return resp, nil
}
