package whatsapp_channel

import (
	"context"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"

	"wechat-api/ent/predicate"
	"wechat-api/ent/whatsappchannel"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetWhatsappChannelListLogic) GetWhatsappChannelList(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))
	}
	if !isAdmin {
		predicates = append(predicates, whatsappchannel.OrganizationID(organizationId))
	}
	if req.WaName != nil && *req.WaName != "" {
		predicates = append(predicates, whatsappchannel.WaNameContains(*req.WaName))
	}
	if req.WaID != nil && *req.WaID != "" {
		predicates = append(predicates, whatsappchannel.WaID(*req.WaID))
	}
	if req.WabaId != nil {
		predicates = append(predicates, whatsappchannel.WabaID(*req.WabaId))
	}
	if req.VerifyAccount != nil && *req.VerifyAccount != "" {
		predicates = append(predicates, whatsappchannel.VerifyAccount(*req.VerifyAccount))
	}
	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
}
