package label_relationship

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

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

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

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

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

func (l *SetWhatsappContactBatchLabelLogic) SetWhatsappContactBatchLabel(req *types.BatchLabelRelationshipsInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	l.Logger.Errorf("contactIds=%v labelIds=%v updateType=%v\n", req.ContactIds, req.LabelIds, req.UpdateType)
	// 遍历所有联系人
	for _, contactId := range req.ContactIds {
		// 开始事务
		tx, err := l.svcCtx.DB.Tx(context.Background())
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		// 获取联系人信息
		_, err = tx.Contact.Query().Where(
			contact.ID(contactId),
			contact.OrganizationIDEQ(organizationId),
		).Only(l.ctx)

		// 获取联系人当前已关联的标签
		currentLabelRelationships, err := tx.LabelRelationship.Query().Where(labelrelationship.ContactID(contactId)).All(l.ctx)
		if err != nil {
			_ = tx.Rollback()
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}

		// 提取当前标签ID
		var currentLabelIds []uint64
		for _, relationship := range currentLabelRelationships {
			currentLabelIds = append(currentLabelIds, relationship.LabelID)
		}

		// 对比新旧标签ID，找出需要新增和移除的标签
		changeLabelIds, _ := compareLabelIdsForIncrement(req.LabelIds, currentLabelIds, req.UpdateType)
		l.Logger.Errorf("contactId=%v req.LabelIds=%v \n", contactId, req.LabelIds)
		l.Logger.Errorf("req.LabelIds=%v currentLabelIds=%v \n", req.LabelIds, currentLabelIds)
		l.Logger.Errorf("changeLabelIds=%v \n", changeLabelIds)
		// 如果 req.UpdateType 为空，或 req.UpdateType 的值为 “all” 时
		if req.UpdateType == -1 {
			// 删除需要移除的标签关系
			for _, id := range changeLabelIds {
				_, err := tx.LabelRelationship.
					Delete().
					Where(
						labelrelationship.ContactID(contactId),
						labelrelationship.LabelID(id),
					).
					Exec(l.ctx)
				if err != nil {
					_ = tx.Rollback()
					return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
				}
			}
		} else {
			// 创建需要新增的标签关系
			for _, id := range changeLabelIds {
				_, _ = tx.LabelRelationship.Create().
					SetLabelID(id).
					SetContactID(contactId).
					SetOrganizationID(organizationId).
					Save(l.ctx)
				//if err != nil {
				//	return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
				//}
			}
		}

		// 所有操作成功，提交事务
		_ = tx.Commit()

	}

	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
