package models

import (
	"eta/eta_mini_api/utils"
	"fmt"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// UserRecord 用户表
type UserRecord struct {
	UserRecordId  int       `orm:"column(user_record_id);pk"`
	UserId        int       `description:"用户ID"`
	OpenId        string    `description:"open_id"`
	UnionId       string    `description:"用户统一标识"`
	Subscribe     int       `description:"公众号关注状态:0-未关注;1-已关注"`
	SubscribeTime time.Time `description:"公众号关注/取消关注时间"`
	NickName      string    `description:"用户昵称"`
	RealName      string    `description:"用户姓名"`
	Gender        int       `description:"性别"`
	Avatar        string    `description:"用户头像"`
	//SessionKey    string    `description:"微信小程序会话密钥"`
	CreateTime time.Time `description:"创建时间"`
	ModifyTime time.Time `description:"更新时间"`
}

func (m *UserRecord) TableName() string {
	return "user_record"
}

type UserRecordCols struct {
	PrimaryId     string
	UserId        string
	OpenId        string
	UnionId       string
	Subscribe     string
	SubscribeTime string
	NickName      string
	RealName      string
	Gender        string
	Avatar        string
	SessionKey    string
	CreateTime    string
	ModifyTime    string
}

func (m *UserRecord) Cols() UserRecordCols {
	return UserRecordCols{
		PrimaryId:     "user_record_id",
		UserId:        "user_id",
		OpenId:        "open_id",
		UnionId:       "union_id",
		Subscribe:     "subscribe",
		SubscribeTime: "subscribe_time",
		NickName:      "nick_name",
		RealName:      "real_name",
		Gender:        "gender",
		Avatar:        "avatar",
		SessionKey:    "session_key",
		CreateTime:    "create_time",
		ModifyTime:    "modify_time",
	}
}

func (m *UserRecord) Create() (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.UserRecordId = int(id)
	return
}

func (m *UserRecord) CreateMulti(items []*UserRecord) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *UserRecord) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m, cols...)
	return
}

func (m *UserRecord) Remove() (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	_, err = o.Raw(sql, m.UserRecordId).Exec()
	return
}

func (m *UserRecord) MultiRemove(ids []int) (err error) {
	if len(ids) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.Cols().PrimaryId, utils.GetOrmInReplace(len(ids)))
	_, err = o.Raw(sql, ids).Exec()
	return
}

func (m *UserRecord) RemoveByCondition(condition string, pars []interface{}) (err error) {
	if condition == "" {
		return
	}
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), condition)
	_, err = o.Raw(sql, pars).Exec()
	return
}

func (m *UserRecord) GetItemById(id int) (item *UserRecord, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *UserRecord) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *UserRecord, err error) {
	o := orm.NewOrm()
	order := ``
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s %s LIMIT 1`, m.TableName(), condition, order)
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *UserRecord) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *UserRecord) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*UserRecord, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *UserRecord) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*UserRecord, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}