package whatsapp_channel

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/predicate"
	"wechat-api/ent/whatsappchannel"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *GetWhatsappChannelSearchLogic) GetWhatsappChannelSearch(req *types.WhatsappChannelListReq) (*types.WhatsappChannelListResp, error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)
	organizationId := l.ctx.Value("organizationId").(uint64)

	var predicates []predicate.WhatsappChannel

	if isAdmin && req.OrganizationId != nil {
		predicates = append(predicates, whatsappchannel.OrganizationID(*req.OrganizationId))
	} else {
		predicates = append(predicates, whatsappchannel.OrganizationID(organizationId))
	}

	data, err := l.svcCtx.DB.WhatsappChannel.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: v.OrganizationID})
		if err != nil {
			l.Error("获取部门信息失败", err)
		}

		resp.Data.Data = append(resp.Data.Data,
			types.WhatsappChannelInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:           &v.Status,
				Ak:               &v.Ak,
				Sk:               &v.Sk,
				WaId:             &v.WaID,
				WaName:           &v.WaName,
				WabaId:           &v.WabaID,
				BusinessId:       &v.BusinessID,
				OrganizationId:   &v.OrganizationID,
				OrganizationName: departmentInfo.Name,
				VerifyAccount:    &v.VerifyAccount,
			})
	}

	return resp, nil
}
