package contact_field_template

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent"
	"wechat-api/ent/contactfieldtemplate"
	"wechat-api/ent/custom_types"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

func (l *GetContactFieldTemplateByIdLogic) GetContactFieldTemplateById() (resp *types.ContactFieldTemplateInfoResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	data, err := l.svcCtx.DB.ContactFieldTemplate.Query().Where(contactfieldtemplate.OrganizationID(organizationId)).First(l.ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return &types.ContactFieldTemplateInfoResp{
				BaseDataInfo: types.BaseDataInfo{
					Code: 0,
					Msg:  errormsg.Success,
				},
			}, nil
		} else {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
		}
	}

	template := ConvertCustomToInternal(data.Template)

	return &types.ContactFieldTemplateInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: template,
	}, nil
}

func ConvertCustomToInternal(src []custom_types.ContactFieldTemplate) []types.ContactFieldTemplate {
	var result []types.ContactFieldTemplate
	for _, s := range src {
		var options []types.ContactFieldTemplateOptions
		for _, o := range s.Options {
			options = append(options, types.ContactFieldTemplateOptions{
				Label: o.Label,
				Value: o.Value,
			})
		}
		result = append(result, types.ContactFieldTemplate{
			Type:    s.Type,
			Id:      s.Id,
			Label:   s.Label,
			Options: options,
		})
	}
	return result
}
