package contact

import (
	"context"
	"wechat-api/ent"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *CreateContactLogic) CreateContact(req *types.ContactInfo) (*types.BaseMsgResp, error) {
	tx, err := l.svcCtx.DB.Tx(l.ctx)
	if err != nil {
		return nil, err
	}
	organizationId := l.ctx.Value("organizationId").(uint64)
	contact, err := tx.Contact.Create().
		SetNotNilStatus(req.Status).
		SetNotNilWxWxid(req.WxWxid).
		SetNotNilType(req.Type).
		SetNotNilWxid(req.Wxid).
		SetNotNilAccount(req.Account).
		SetNotNilNickname(req.Nickname).
		SetNotNilMarkname(req.Markname).
		SetNotNilHeadimg(req.Headimg).
		SetNotNilSex(req.Sex).
		SetNotNilStarrole(req.Starrole).
		SetNotNilDontseeit(req.Dontseeit).
		SetNotNilDontseeme(req.Dontseeme).
		SetNotNilLag(req.Lag).
		SetNotNilGid(req.Gid).
		SetNotNilGname(req.Gname).
		SetNotNilV3(req.V3).
		SetOrganizationID(organizationId).
		SetNotNilCtype(req.Ctype).
		SetNotNilCname(req.Cname).
		SetNotNilCarea(req.Carea).
		SetNotNilCage(req.Cage).
		SetNotNilCbirthday(req.Cbirthday).
		SetNotNilCbirtharea(req.Cbirtharea).
		SetNotNilCc(req.Cc).
		SetNotNilPhone(req.Phone).
		SetNotNilCidcardNo(req.CidcardNo).
		SetNotNilCtitle(req.Ctitle).
		Save(l.ctx)

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

	err = CreateContactFields(l.ctx, tx, contact.ID, req.CustomFields)

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

	_ = tx.Commit()
	return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
}

func CreateContactFields(ctx context.Context, tx *ent.Tx, contact_id uint64, fields []types.ContactFieldTemplate) error {
	for _, field := range fields {
		//f, err := tx.ContactField.Query().Where(contactfield.ContactID(contact_id), contactfield.FormID(*field.Id)).First(l.ctx)
		if field.Label != nil && len(field.Value) > 0 {
			_, err := tx.ContactField.Create().
				SetContactID(contact_id).
				SetFormID(*field.Id).
				SetValue(field.Value).
				Save(ctx)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
