package label_relationship

import (
	"context"
	"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 SetWhatsappContactLabelLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *SetWhatsappContactLabelLogic) SetWhatsappContactLabel(req *types.LabelRelationshipsInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	resp := types.BaseMsgResp{}

	// 开始事务
	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(*req.ContactId),
		contact.OrganizationIDEQ(organizationId),
	).Only(l.ctx)

	// 获取联系人当前已关联的标签
	currentLabelRelationships, err := tx.LabelRelationship.Query().Where(labelrelationship.ContactID(*req.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，找出需要新增和移除的标签
	addLabelIds, removeLabelIds := diffLabelIds(req.LabelIds, currentLabelIds)
	l.Logger.Infof("req.LabelIds=%v, currentLabelIds=%v\n", req.LabelIds, currentLabelIds)
	l.Logger.Infof("addLabelIds=%v, removeLabelIds=%v\n", addLabelIds, removeLabelIds)

	// 如果 req.UpdateType 为空，或 req.UpdateType 的值为 “all” 时
	// 删除需要移除的标签关系
	l.Logger.Errorf("------------------------removeLabelIds--------------------------- %+v\n", removeLabelIds)
	for _, id := range currentLabelIds {
		_, err := tx.LabelRelationship.
			Delete().
			Where(
				labelrelationship.ContactID(*req.ContactId),
				labelrelationship.LabelID(id),
			).
			Exec(l.ctx)
		if err != nil {
			_ = tx.Rollback()
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
	}

	// 创建需要新增的标签关系
	l.Logger.Errorf("------------------------addLabelIds--------------------------- %+v\n", addLabelIds)
	for _, id := range req.LabelIds {
		_, _ = tx.LabelRelationship.Create().
			SetLabelID(id).
			SetContactID(*req.ContactId).
			SetOrganizationID(organizationId).
			Save(l.ctx)
		//if err != nil {
		//	return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		//}
	}
	_ = tx.Commit()

	return &resp, nil
}

func diffLabelIds(newLabelIds []uint64, currentLabelIds []uint64) (addLabelIds []uint64, removeLabelIds []uint64) {

	for _, v := range newLabelIds {
		if !inArray(v, currentLabelIds) {
			addLabelIds = append(addLabelIds, v)
		}
	}
	for _, v := range currentLabelIds {
		if !inArray(v, newLabelIds) {
			removeLabelIds = append(removeLabelIds, v)
		}
	}

	return
}

func inArray(ele uint64, array []uint64) bool {
	for _, v := range array {
		if ele == v {
			return true
		}
	}
	return false
}
