package models

import (
	"fmt"
	"opp/internal/utils"
	"time"

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

type Rank struct {
	Id             int64     `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 int64) (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_range_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
}

//排行列表-用户
func GetRanksByUser(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, pageIndex, pageSize int, v interface{}) (total int, err error) {
	//var filterDepartment string = getFilterSqlByDIds(dIds)
	pageIndex, pageSize = utils.GetPageInfo(pageIndex, pageSize)
	sql := fmt.Sprintf(`select (@rowno:=@rowno+1) as ranking,a.*,b.nick_name name from
(
select  score,relation_id,user_id from(
select a.%v score,a.relation_id,user_id from rank a inner join user_company c on a.relation_id=c.id
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
) a,(select @rowno:=%v) b
limit %v,%v
)a inner join user b on a.user_id = b.id
`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, pageIndex, pageIndex, pageSize)

	sqlCount := fmt.Sprintf(`
select count(0) from rank 
where company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v
`, companyId, rankTypeId, rankRangeId, rankPeriodId)
	if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
		return
	}
	if v != nil {
		if err = utils.ExecuteQueryAll(v, sql); err != nil {
			return
		}
	}
	return
}

//排行榜列表-用户-自己的排名
func GetRanksByUserSelf(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, relationId int64, v interface{}) (err error) {
	//var filterDepartment string = getFilterSqlByDIds(dIds)
	sql := fmt.Sprintf(`

select a.*,b.nick_name name from
(
select  score,relation_id,user_id,(@rowno:=@rowno+1) as ranking from(
select a.%v score,a.relation_id,user_id from rank a inner join user_company c on a.relation_id=c.id
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
) a,(select @rowno:=0 ) b
)a inner join user b on a.user_id = b.id
where relation_id=%v

`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, relationId)

	if v != nil {
		if err = utils.ExecuteQueryOne(v, sql); err != nil {
			if err == orm.ErrNoRows {
				err = nil
			}
			return
		}
	}
	return
}

//排行榜列表-部门
func GetRanksByDepartment(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, pageIndex, pageSize int, v interface{}) (total int, err error) {
	//var filterDepartment string = getFilterSqlByDIds(dIds)
	pageIndex, pageSize = utils.GetPageInfo(pageIndex, pageSize)
	sql := fmt.Sprintf(`
select a.*,(@rowno:=@rowno+1) as ranking from
(
select a.%v score,a.relation_id,c.name 
from rank a inner join department c on a.relation_id=c.id
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
)a,(select (@rowno:=%v)) b
limit %v,%v
`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, pageIndex, pageIndex, pageSize)

	sqlCount := fmt.Sprintf(`
select count(0) from rank 
where company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v
`, companyId, rankTypeId, rankRangeId, rankPeriodId)
	if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
		return
	}
	if v != nil {
		if err = utils.ExecuteQueryAll(v, sql); err != nil {
			if err == orm.ErrNoRows {
				err = nil
			}
			return
		}
	}
	return
}

//排行榜列表-部门-用户所属部门排名
func GetRanksByDepartmentSelf(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, relationId int64, v interface{}) (err error) {
	sql := fmt.Sprintf(`select * from (
select a.*,(@rowno:=@rowno+1) as ranking from (
select a.%v score,a.relation_id,c.name from rank a inner join department c on a.relation_id=c.id 
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
) a,(select (@rowno:=0)) b
)a
where a.relation_id=%v

`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, relationId)

	if v != nil {
		if err = utils.ExecuteQueryOne(v, sql); err != nil {
			if err == orm.ErrNoRows {
				err = nil
			}
			return
		}
	}
	return
}