// Code generated by goctl. DO NOT EDIT!

package model

import (
	"context"
	"database/sql"
	"fmt"
	"strings"

	"reflect"
	"time"

	"qnc-server/common/globalkey"

	"github.com/Masterminds/squirrel"
	"github.com/google/uuid"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/builder"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/core/stringx"
)

var (
	agentFieldNames          = builder.RawFieldNames(&Agent{})
	agentRows                = strings.Join(agentFieldNames, ",")
	agentRowsExpectAutoSet   = strings.Join(stringx.Remove(agentFieldNames, "`create_time`", "`update_time`"), ",")
	agentRowsWithPlaceHolder = strings.Join(stringx.Remove(agentFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"

	cacheQncAgentIdPrefix        = "cache:qnc:agent:id:"
	cacheQncAgentAgentCodePrefix = "cache:qnc:agent:agentCode:"
	cacheQncAgentUserIdPrefix    = "cache:qnc:agent:userId:"
)

type (
	agentModel interface {
		Insert(ctx context.Context, session sqlx.Session, data *Agent) (sql.Result, error)
		FindOne(ctx context.Context, id string) (*Agent, error)
		FindOneByAgentCode(ctx context.Context, agentCode int64) (*Agent, error)
		FindOneByUserId(ctx context.Context, userId string) (*Agent, error)
		Update(ctx context.Context, session sqlx.Session, data *Agent) (sql.Result, error)
		UpdateWithVersion(ctx context.Context, session sqlx.Session, data *Agent) error
		Trans(ctx context.Context, fn func(context context.Context, session sqlx.Session) error) error
		SelectBuilder() squirrel.SelectBuilder
		DeleteSoft(ctx context.Context, session sqlx.Session, data *Agent) error
		FindSum(ctx context.Context, sumBuilder squirrel.SelectBuilder, field string) (float64, error)
		FindCount(ctx context.Context, countBuilder squirrel.SelectBuilder, field string) (int64, error)
		FindAll(ctx context.Context, rowBuilder squirrel.SelectBuilder, orderBy string) ([]*Agent, error)
		FindPageListByPage(ctx context.Context, rowBuilder squirrel.SelectBuilder, page, pageSize int64, orderBy string) ([]*Agent, error)
		FindPageListByPageWithTotal(ctx context.Context, rowBuilder squirrel.SelectBuilder, page, pageSize int64, orderBy string) ([]*Agent, int64, error)
		FindPageListByIdDESC(ctx context.Context, rowBuilder squirrel.SelectBuilder, preMinId, pageSize int64) ([]*Agent, error)
		FindPageListByIdASC(ctx context.Context, rowBuilder squirrel.SelectBuilder, preMaxId, pageSize int64) ([]*Agent, error)
		Delete(ctx context.Context, session sqlx.Session, id string) error
	}

	defaultAgentModel struct {
		sqlc.CachedConn
		table string
	}

	Agent struct {
		Id           string         `db:"id"`
		UserId       string         `db:"user_id"`
		AgentCode    int64          `db:"agent_code"` // 代理编码（从16800开始递增）
		Level        int64          `db:"level"`      // 代理等级：1=普通，2=黄金，3=钻石
		Region       sql.NullString `db:"region"`     // 区域（可选）
		Mobile       string         `db:"mobile"`     // 手机号（加密）
		WechatId     sql.NullString `db:"wechat_id"`  // 微信号
		TeamLeaderId sql.NullString `db:"team_leader_id"`
		InviteCodeId sql.NullString `db:"invite_code_id"`
		CreateTime   time.Time      `db:"create_time"` // 创建时间
		UpdateTime   time.Time      `db:"update_time"` // 更新时间
		DeleteTime   sql.NullTime   `db:"delete_time"` // 删除时间
		DelState     int64          `db:"del_state"`   // 删除状态：0=未删除，1=已删除
		Version      int64          `db:"version"`     // 版本号（乐观锁）
	}
)

func newAgentModel(conn sqlx.SqlConn, c cache.CacheConf) *defaultAgentModel {
	return &defaultAgentModel{
		CachedConn: sqlc.NewConn(conn, c),
		table:      "`agent`",
	}
}

func (m *defaultAgentModel) Insert(ctx context.Context, session sqlx.Session, data *Agent) (sql.Result, error) {
	data.DelState = globalkey.DelStateNo
	m.insertUUID(data)
	qncAgentAgentCodeKey := fmt.Sprintf("%s%v", cacheQncAgentAgentCodePrefix, data.AgentCode)
	qncAgentIdKey := fmt.Sprintf("%s%v", cacheQncAgentIdPrefix, data.Id)
	qncAgentUserIdKey := fmt.Sprintf("%s%v", cacheQncAgentUserIdPrefix, data.UserId)
	return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, agentRowsExpectAutoSet)
		if session != nil {
			return session.ExecCtx(ctx, query, data.Id, data.UserId, data.AgentCode, data.Level, data.Region, data.Mobile, data.WechatId, data.TeamLeaderId, data.InviteCodeId, data.DeleteTime, data.DelState, data.Version)
		}
		return conn.ExecCtx(ctx, query, data.Id, data.UserId, data.AgentCode, data.Level, data.Region, data.Mobile, data.WechatId, data.TeamLeaderId, data.InviteCodeId, data.DeleteTime, data.DelState, data.Version)
	}, qncAgentAgentCodeKey, qncAgentIdKey, qncAgentUserIdKey)
}
func (m *defaultAgentModel) insertUUID(data *Agent) {
	t := reflect.TypeOf(data).Elem()
	v := reflect.ValueOf(data).Elem()
	for i := 0; i < t.NumField(); i++ {
		sf := t.Field(i)
		if sf.Tag.Get("db") == "id" {
			f := v.Field(i)
			if f.IsValid() && f.CanSet() && f.Kind() == reflect.String {
				if f.String() == "" {
					f.SetString(uuid.NewString())
				}
			}
			break
		}
	}
}

func (m *defaultAgentModel) FindOne(ctx context.Context, id string) (*Agent, error) {
	qncAgentIdKey := fmt.Sprintf("%s%v", cacheQncAgentIdPrefix, id)
	var resp Agent
	err := m.QueryRowCtx(ctx, &resp, qncAgentIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", agentRows, m.table)
		return conn.QueryRowCtx(ctx, v, query, id, globalkey.DelStateNo)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultAgentModel) FindOneByAgentCode(ctx context.Context, agentCode int64) (*Agent, error) {
	qncAgentAgentCodeKey := fmt.Sprintf("%s%v", cacheQncAgentAgentCodePrefix, agentCode)
	var resp Agent
	err := m.QueryRowIndexCtx(ctx, &resp, qncAgentAgentCodeKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
		query := fmt.Sprintf("select %s from %s where `agent_code` = ? and del_state = ? limit 1", agentRows, m.table)
		if err := conn.QueryRowCtx(ctx, &resp, query, agentCode, globalkey.DelStateNo); err != nil {
			return nil, err
		}
		return resp.Id, nil
	}, m.queryPrimary)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultAgentModel) FindOneByUserId(ctx context.Context, userId string) (*Agent, error) {
	qncAgentUserIdKey := fmt.Sprintf("%s%v", cacheQncAgentUserIdPrefix, userId)
	var resp Agent
	err := m.QueryRowIndexCtx(ctx, &resp, qncAgentUserIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
		query := fmt.Sprintf("select %s from %s where `user_id` = ? and del_state = ? limit 1", agentRows, m.table)
		if err := conn.QueryRowCtx(ctx, &resp, query, userId, globalkey.DelStateNo); err != nil {
			return nil, err
		}
		return resp.Id, nil
	}, m.queryPrimary)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultAgentModel) Update(ctx context.Context, session sqlx.Session, newData *Agent) (sql.Result, error) {
	data, err := m.FindOne(ctx, newData.Id)
	if err != nil {
		return nil, err
	}
	qncAgentAgentCodeKey := fmt.Sprintf("%s%v", cacheQncAgentAgentCodePrefix, data.AgentCode)
	qncAgentIdKey := fmt.Sprintf("%s%v", cacheQncAgentIdPrefix, data.Id)
	qncAgentUserIdKey := fmt.Sprintf("%s%v", cacheQncAgentUserIdPrefix, data.UserId)
	return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, agentRowsWithPlaceHolder)
		if session != nil {
			return session.ExecCtx(ctx, query, newData.UserId, newData.AgentCode, newData.Level, newData.Region, newData.Mobile, newData.WechatId, newData.TeamLeaderId, newData.InviteCodeId, newData.DeleteTime, newData.DelState, newData.Version, newData.Id)
		}
		return conn.ExecCtx(ctx, query, newData.UserId, newData.AgentCode, newData.Level, newData.Region, newData.Mobile, newData.WechatId, newData.TeamLeaderId, newData.InviteCodeId, newData.DeleteTime, newData.DelState, newData.Version, newData.Id)
	}, qncAgentAgentCodeKey, qncAgentIdKey, qncAgentUserIdKey)
}

func (m *defaultAgentModel) UpdateWithVersion(ctx context.Context, session sqlx.Session, newData *Agent) error {

	oldVersion := newData.Version
	newData.Version += 1

	var sqlResult sql.Result
	var err error

	data, err := m.FindOne(ctx, newData.Id)
	if err != nil {
		return err
	}
	qncAgentAgentCodeKey := fmt.Sprintf("%s%v", cacheQncAgentAgentCodePrefix, data.AgentCode)
	qncAgentIdKey := fmt.Sprintf("%s%v", cacheQncAgentIdPrefix, data.Id)
	qncAgentUserIdKey := fmt.Sprintf("%s%v", cacheQncAgentUserIdPrefix, data.UserId)
	sqlResult, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where `id` = ? and version = ? ", m.table, agentRowsWithPlaceHolder)
		if session != nil {
			return session.ExecCtx(ctx, query, newData.UserId, newData.AgentCode, newData.Level, newData.Region, newData.Mobile, newData.WechatId, newData.TeamLeaderId, newData.InviteCodeId, newData.DeleteTime, newData.DelState, newData.Version, newData.Id, oldVersion)
		}
		return conn.ExecCtx(ctx, query, newData.UserId, newData.AgentCode, newData.Level, newData.Region, newData.Mobile, newData.WechatId, newData.TeamLeaderId, newData.InviteCodeId, newData.DeleteTime, newData.DelState, newData.Version, newData.Id, oldVersion)
	}, qncAgentAgentCodeKey, qncAgentIdKey, qncAgentUserIdKey)
	if err != nil {
		return err
	}
	updateCount, err := sqlResult.RowsAffected()
	if err != nil {
		return err
	}
	if updateCount == 0 {
		return ErrNoRowsUpdate
	}

	return nil
}

func (m *defaultAgentModel) DeleteSoft(ctx context.Context, session sqlx.Session, data *Agent) error {
	data.DelState = globalkey.DelStateYes
	data.DeleteTime = sql.NullTime{Time: time.Now(), Valid: true}
	if err := m.UpdateWithVersion(ctx, session, data); err != nil {
		return errors.Wrapf(errors.New("delete soft failed "), "AgentModel delete err : %+v", err)
	}
	return nil
}

func (m *defaultAgentModel) FindSum(ctx context.Context, builder squirrel.SelectBuilder, field string) (float64, error) {

	if len(field) == 0 {
		return 0, errors.Wrapf(errors.New("FindSum Least One Field"), "FindSum Least One Field")
	}

	builder = builder.Columns("IFNULL(SUM(" + field + "),0)")

	query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).ToSql()
	if err != nil {
		return 0, err
	}

	var resp float64
	err = m.QueryRowNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return 0, err
	}
}

func (m *defaultAgentModel) FindCount(ctx context.Context, builder squirrel.SelectBuilder, field string) (int64, error) {

	if len(field) == 0 {
		return 0, errors.Wrapf(errors.New("FindCount Least One Field"), "FindCount Least One Field")
	}

	builder = builder.Columns("COUNT(" + field + ")")

	query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).ToSql()
	if err != nil {
		return 0, err
	}

	var resp int64
	err = m.QueryRowNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return 0, err
	}
}

func (m *defaultAgentModel) FindAll(ctx context.Context, builder squirrel.SelectBuilder, orderBy string) ([]*Agent, error) {

	builder = builder.Columns(agentRows)

	if orderBy == "" {
		builder = builder.OrderBy("id DESC")
	} else {
		builder = builder.OrderBy(orderBy)
	}

	query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).ToSql()
	if err != nil {
		return nil, err
	}

	var resp []*Agent
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultAgentModel) FindPageListByPage(ctx context.Context, builder squirrel.SelectBuilder, page, pageSize int64, orderBy string) ([]*Agent, error) {

	builder = builder.Columns(agentRows)

	if orderBy == "" {
		builder = builder.OrderBy("id DESC")
	} else {
		builder = builder.OrderBy(orderBy)
	}

	if page < 1 {
		page = 1
	}
	offset := (page - 1) * pageSize

	query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).Offset(uint64(offset)).Limit(uint64(pageSize)).ToSql()
	if err != nil {
		return nil, err
	}

	var resp []*Agent
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultAgentModel) FindPageListByPageWithTotal(ctx context.Context, builder squirrel.SelectBuilder, page, pageSize int64, orderBy string) ([]*Agent, int64, error) {

	total, err := m.FindCount(ctx, builder, "id")
	if err != nil {
		return nil, 0, err
	}

	builder = builder.Columns(agentRows)

	if orderBy == "" {
		builder = builder.OrderBy("id DESC")
	} else {
		builder = builder.OrderBy(orderBy)
	}

	if page < 1 {
		page = 1
	}
	offset := (page - 1) * pageSize

	query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).Offset(uint64(offset)).Limit(uint64(pageSize)).ToSql()
	if err != nil {
		return nil, total, err
	}

	var resp []*Agent
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, total, nil
	default:
		return nil, total, err
	}
}

func (m *defaultAgentModel) FindPageListByIdDESC(ctx context.Context, builder squirrel.SelectBuilder, preMinId, pageSize int64) ([]*Agent, error) {

	builder = builder.Columns(agentRows)

	if preMinId > 0 {
		builder = builder.Where(" id < ? ", preMinId)
	}

	query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).OrderBy("id DESC").Limit(uint64(pageSize)).ToSql()
	if err != nil {
		return nil, err
	}

	var resp []*Agent
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultAgentModel) FindPageListByIdASC(ctx context.Context, builder squirrel.SelectBuilder, preMaxId, pageSize int64) ([]*Agent, error) {

	builder = builder.Columns(agentRows)

	if preMaxId > 0 {
		builder = builder.Where(" id > ? ", preMaxId)
	}

	query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).OrderBy("id ASC").Limit(uint64(pageSize)).ToSql()
	if err != nil {
		return nil, err
	}

	var resp []*Agent
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultAgentModel) Trans(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error {

	return m.TransactCtx(ctx, func(ctx context.Context, session sqlx.Session) error {
		return fn(ctx, session)
	})

}

func (m *defaultAgentModel) SelectBuilder() squirrel.SelectBuilder {
	return squirrel.Select().From(m.table)
}
func (m *defaultAgentModel) Delete(ctx context.Context, session sqlx.Session, id string) error {
	data, err := m.FindOne(ctx, id)
	if err != nil {
		return err
	}

	qncAgentAgentCodeKey := fmt.Sprintf("%s%v", cacheQncAgentAgentCodePrefix, data.AgentCode)
	qncAgentIdKey := fmt.Sprintf("%s%v", cacheQncAgentIdPrefix, id)
	qncAgentUserIdKey := fmt.Sprintf("%s%v", cacheQncAgentUserIdPrefix, data.UserId)
	_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
		if session != nil {
			return session.ExecCtx(ctx, query, id)
		}
		return conn.ExecCtx(ctx, query, id)
	}, qncAgentAgentCodeKey, qncAgentIdKey, qncAgentUserIdKey)
	return err
}
func (m *defaultAgentModel) formatPrimary(primary interface{}) string {
	return fmt.Sprintf("%s%v", cacheQncAgentIdPrefix, primary)
}
func (m *defaultAgentModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
	query := fmt.Sprintf("select %s from %s where `id` = ? and del_state = ? limit 1", agentRows, m.table)
	return conn.QueryRowCtx(ctx, v, query, primary, globalkey.DelStateNo)
}

func (m *defaultAgentModel) tableName() string {
	return m.table
}
