package contact

import (
	"context"
	"wechat-api/ent"
	"wechat-api/ent/contact"
	"wechat-api/ent/contactfield"
	"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 UpdateContactLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdateContactLogic) UpdateContact(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)
	cage := 0
	if req.Cage != nil && *req.Cage > 0 {
		cage = *req.Cage
	}
	err = tx.Contact.UpdateOneID(*req.Id).
		Where(contact.OrganizationID(organizationId)).
		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).
		SetNotNilCname(req.Cname).
		SetNotNilCarea(req.Carea).
		SetNotNilCage(&cage).
		SetNotNilCbirthday(req.Cbirthday).
		SetNotNilCbirtharea(req.Cbirtharea).
		SetNotNilCc(req.Cc).
		SetNotNilPhone(req.Phone).
		SetNotNilCidcardNo(req.CidcardNo).
		SetNotNilCtitle(req.Ctitle).
		Exec(l.ctx)

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

	err = UpdateContactFields(l.ctx, tx, *req.Id, req.CustomFields)

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

	_ = tx.Commit()

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

func UpdateContactFields(ctx context.Context, tx *ent.Tx, contact_id uint64, fields []types.ContactFieldTemplate) error {
	for _, field := range fields {
		f, _ := tx.ContactField.Query().Where(contactfield.ContactID(contact_id), contactfield.FormID(*field.Id)).First(ctx)
		if f == nil {
			if field.Value != 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
				}
			}
		} else {
			if field.Value != nil {
				if len(field.Value) == 0 {
					field.Value = []string{""}
				}
			} else {
				field.Value = []string{""}
			}
			_, err := tx.ContactField.UpdateOneID(f.ID).
				SetValue(field.Value).
				Save(ctx)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
