package models

import (
	"errors"
	"fmt"
	"time"

	"github.com/astaxie/beego/orm"
)

type User struct {
	Id            int64     `orm:"column(id);pk" description:"用户id"`
	NickName      string    `orm:"column(nick_name);size(100)" description:"昵称"`
	Phone         string    `orm:"column(phone);size(40)" description:"手机号码"`
	Passwd        string    `orm:"column(passwd);size(128)" description:"密码"`
	Icon          string    `orm:"column(icon);size(255)" description:"头像"`
	CsAccount     int64     `orm:"column(cs_account)" description:"客服有话说ID"`
	IsKefu        int8      `orm:"column(is_kefu)" description:"是否是客服 0:否 1:是"`
	ImToken       string    `orm:"column(im_token);size(128)" description:"网易云token"`
	LastLoginTime time.Time `orm:"column(last_login_time);type(timestamp)" description:"最后一次登录时间"`
	CreateAt      time.Time `orm:"column(create_at);type(timestamp);auto_now_add" description:"创建时间"`
	EnableStatus  int8      `orm:"column(enable_status)" description:"是否有效"`
	DeleteAt      time.Time `orm:"column(delete_at);type(timestamp)"`
}

func (t *User) TableName() string {
	return "user"
}

//用户是否有效
const (
	USER_ENABLE_YES int8 = 1 //有效
	USER_ENABLE_NO  int8 = 2 //无效
)

func (t *User) IsEnable() bool {
	switch t.EnableStatus {
	case USER_ENABLE_YES:
		return true
	case USER_ENABLE_NO:
		return false
	}
	return false
}

func init() {
	orm.RegisterModel(new(User))
}

// AddUser insert a new User into database and returns
// last inserted Id on success.
func AddUser(m *User, om ...orm.Ormer) (id int64, err error) {
	var o orm.Ormer
	if len(om) > 0 {
		o = om[0]
	} else {
		o = orm.NewOrm()
	}

	id, err = o.Insert(m)
	return
}

// GetUserById retrieves User by Id. Returns error if
// Id doesn't exist
func GetUserById(id int64) (v *User, err error) {
	o := orm.NewOrm()
	v = &User{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateUser updates User by Id and returns error if
// the record to be updated doesn't exist
func UpdateUserById(m *User) (err error) {
	o := orm.NewOrm()
	v := User{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func GetUserByPhone(phone string) (v *User, err error) {
	o := orm.NewOrm()
	v = &User{Phone: phone}
	if err = o.Read(v, "Phone"); err == nil {
		return v, nil
	}
	if v.DeleteAt.Unix() > 0 {
		return nil, errors.New("user is deleted")
	}
	return nil, err
}

func getUserNameByIds(ids []int64) ([]User, error) {
	var (
		users []User
		err   error
	)
	if len(ids) == 0 {
		return users, nil
	}
	o := orm.NewOrm()
	_, err = o.QueryTable(&User{}).
		Filter("id__in", ids).
		Filter("delete_at", time.Unix(0, 0)).All(&users)

	if err == orm.ErrNoRows {
		return users, nil
	}
	return users, err
}

func GetUserNameByIds(ids []int64) ([]User, error) {
	return getUserNameByIds(ids)
}