package user

import (
	"eta/eta_mini_ht_api/models"
	"gorm.io/gorm"
	"time"
)

const (
	NotDeleted = 0
	Deleted    = 1
)

type TemplateUser struct {
	Id           int       `gorm:"column:id;primaryKey;autoIncrement:'id'"`
	Username     string    `gorm:"column:username;type:varchar(20);comment:用户名"`
	Mobile       string    `gorm:"column:mobile;type:varchar(15);comment:手机号"`
	OpenId       string    `gorm:"column:open_id;type:varchar(50);comment:open_id"`
	GzhOpenId    string    `gorm:"column:gzh_open_id;type:varchar(255);comment:gzh_open_id"`
	UnionId      string    `gorm:"column:union_id;type:varchar(50);comment:union_id"`
	ReadCount    int       `gorm:"column:read_count;type:int(11);comment:阅读次数"`
	FollowingGzh int       `gorm:"column:following_gzh;type:int(1);comment:是否关注公众号"`
	LastReadTime time.Time `gorm:"column:last_read_time;type:timestamps;comment:最后阅读时间"`
	IsDeleted    int       `gorm:"column:is_deleted;type:int(11);comment:是否删除"`
	CreatedTime  time.Time `gorm:"column:created_time;type:timestamps;comment:创建时间"`
	UpdatedTime  time.Time `gorm:"column:updated_time;type:timestamps;comment:更新时间"`
}

func (t *TemplateUser) BeforeCreate(tx *gorm.DB) (err error) {
	t.CreatedTime = time.Now()
	t.IsDeleted = NotDeleted
	return
}

func GetUserByMobile(mobile string) (user TemplateUser, err error) {
	return queryByColumn("mobile", mobile)
}
func GetUserByIdAndCountReadTimes(userId int) (err error) {
	return models.Main().Model(&TemplateUser{}).Where("id = ?", userId).Update("read_count", gorm.Expr("read_count + ?", 1)).Error
}

func GetUserByOpenId(openId string) (user TemplateUser, err error) {
	return queryByColumn("open_id", openId)
}

func GetUserByUnionId(unionId string) (user TemplateUser, err error) {
	return queryByColumn("union_id", unionId)
}

func queryByColumn(column string, value string) (user TemplateUser, err error) {
	err = models.Main().Unscoped().Where(column, value).First(&user).Error
	return
}
func RegisterTemplateUser(user *TemplateUser) (err error) {
	err = models.Main().Create(&user).Error
	return
}

func BindMobile(userId int, mobile string) (err error) {
	err = models.Main().Table("template_users").Where("id = ?", userId).Updates(map[string]interface{}{"mobile": mobile, "updated_time": time.Now()}).Error
	return
}

func BindXcxOpenId(userId int, xcxOpenId string) (err error) {
	err = models.Main().Table("template_users").Where("id = ?", userId).Updates(map[string]interface{}{"open_id": xcxOpenId, "updated_time": time.Now()}).Error
	return
}

func BindGzhOpenId(userId int, gzhOpenId string, followingGzh int) (err error) {
	err = models.Main().Table("template_users").Where("id = ?", userId).Updates(map[string]interface{}{"gzh_open_id": gzhOpenId, "following_gzh": followingGzh, "updated_time": time.Now()}).Error
	return
}

func GetUserByGzhOpenId(gzhOpenId string) (user TemplateUser, err error) {
	return queryByColumn("gzh_open_id", gzhOpenId)
}
