package models

import (
	"fmt"
	"time"

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

type Rank struct {
	Id             int       `orm:"column(id);auto"`
	CompanyId      int       `orm:"column(company_id)" description:"公司编号 表company.id"`
	RankTypeId     int       `orm:"column(rank_type_id)" description:"榜单类型编号"`
	RankRangeId    int       `orm:"column(rank_range_id)" description:"榜单范围编号"`
	RankPeriodId   int       `orm:"column(rank_period_id)" description:"赛季周期编号"`
	RelationId     int64     `orm:"column(relation_id)" description:"用户编号/部门编号"`
	TotalScore     float64   `orm:"column(total_score);null;digits(4);decimals(1)" description:"总分"`
	DiscoveryScore float64   `orm:"column(discovery_score);null;digits(4);decimals(1)" description:"发现得分"`
	GraspScore     float64   `orm:"column(grasp_score);null;digits(4);decimals(1)" description:"把握分"`
	DiscoveryTotal int       `orm:"column(discovery_total);null" description:"发现数量"`
	CommentTotal   int       `orm:"column(comment_total);null" description:"评论数量"`
	CreateAt       time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
	UpdateAt       time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
	EnableStatus   int8      `orm:"column(enable_status);null" description:"有效状态 0:无效 1:有效 "`
	Type           int8      `orm:"column(type);null" description:"1:所有员工 2:指定员工 3:所有部门 4:指定部门"`
}

func (t *Rank) TableName() string {
	return "rank"
}

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

// AddRank insert a new Rank into database and returns
// last inserted Id on success.
func AddRank(m *Rank) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

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

// UpdateRank updates Rank by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankById(m *Rank) (err error) {
	o := orm.NewOrm()
	v := Rank{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 GetRank(companyId, rankTypeId, rankRangeId, rankPeriodId int, relationId int64) (v *Rank, err error) {
	o := orm.NewOrm()
	sql := "select * from rank where company_id=? and rank_type_id=? and rank_period_id=? and relation_id=?"
	if err = o.Raw(sql, companyId, rankTypeId, rankRangeId, rankPeriodId, relationId).QueryRow(v); err == nil {
		return v, nil
	}
	return nil, err
}