package keyvalue

import (
	"strconv"
	"wechat-conf/models"
	"wechat-conf/models/model"
	"wechat-conf/utils"

	"github.com/go-xorm/xorm"
)

// KeyvalueDAO 当前数据库操作对象
type KeyvalueDAO struct {
	ctx *utils.Context
	db  *xorm.Session
}

// NewKeyvalueDAO New Inst
func NewKeyvalueDAO(ctx *utils.Context) *KeyvalueDAO {
	return &KeyvalueDAO{
		ctx: ctx,
		db:  ctx.DB,
	}
}

func (m *KeyvalueDAO) GetValueByKey(key string) (*model.TaWechatKeyValue, error) {
	var keyvalue []model.TaWechatKeyValue
	sql := `SELECT
	* 
FROM
	ta_wechat_key_value 
WHERE
	key_id = '` + key + `'
	and status > ` + strconv.Itoa(models.STATUS_DEL)
	err := m.db.Sql(sql).Find(&keyvalue)
	if len(keyvalue) > 0 {
		return &keyvalue[0], err
	}
	return nil, err
}

func (m *KeyvalueDAO) AddValueKey(valueKey model.TaWechatKeyValue) error {
	valueKey.Status = models.STATUS_NORMAL
	_, err := m.db.Insert(valueKey)
	return err
}
func (m *KeyvalueDAO) DeleteByOrgId(orgId string) error {
	_, err := m.db.Delete(&model.TaWechatKeyValue{OrgId: orgId})
	return err
}