package wxcardvisit

import (
	"context"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/agent"
	"wechat-api/ent/wxcard"
	"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 GetWxCardVisitByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetWxCardVisitByIdLogic) GetWxCardVisitById(req *types.IDReq) (*types.WxCardVisitInfoResp, error) {
	data, err := l.svcCtx.DB.WxCardVisit.Query().Where(wxcardvisit.ID(req.Id)).Only(l.ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, errorx.NewInvalidArgumentError("记录不存在")
		}
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	var card types.WxCardSimpleInfo
	if data.BotType == 2 {
		acard, _ := l.svcCtx.DB.WxCard.Query().Where(wxcard.ID(data.BotID)).Only(l.ctx)
		card.Avatar = tea.String(acard.Avatar)
		card.Name = tea.String(acard.Name)
	} else if data.BotType == 3 {
		agent, _ := l.svcCtx.DB.Agent.Query().Where(agent.ID(data.BotID)).Only(l.ctx)
		card.Avatar = tea.String("")
		card.Name = tea.String(agent.Name)
	} else {

	}

	return &types.WxCardVisitInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.WxCardVisitInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			UserId:  &data.UserID,
			BotType: &data.BotType,
			BotId:   &data.BotID,
			CardInfo: types.WxCardSimpleInfo{
				Avatar: card.Avatar,
				Name:   card.Name,
			},
		},
	}, nil
}
