package userMgr

import (
	"gdsm/models/ec"
	"github.com/astaxie/beego"
	"strings"
	"wb/cc"
	"wb/cs"
	"wb/om"
	"wb/st"
)

//func Get(sn string) (string, map[string]interface{}) {
//    params := t.Params{
//        s.Sn: sn,
//    }
//    return svc.Get(s.User, params)
//}

func GetUser(queryParams om.Params) (string, cs.MObject) {
	if s, v := om.Table(ec.Tbl.User).Get(queryParams); s == st.Success {
		delete(v, ec.Col.Password)
		return s, v
	}
	return om.Table(ec.Tbl.User).Get(queryParams)
}
func GetValidUser(queryParams om.Params) (string, User) {
	if stat, valueMap := GetUser(queryParams); stat == st.Success {
		if valueMap.GetString(ec.Col.Flag) == cc.FlagAvailable {
			return st.Success, ValueMap2User(valueMap)
		} else {
			return st.ItemNotFound, User{}
		}
	} else {
		return stat, User{}
	}
}
func ValueMap2User(valueMap cs.MObject) User {
	user := User{}
	user.Sn = valueMap.GetString(cc.Col.Sn)
	user.UserName = valueMap.GetString(ec.Col.UserName)
	user.Name = valueMap.GetString(ec.Col.Name)
	user.Role = valueMap.GetString(cc.Col.Role)
	user.Flag = valueMap.GetString(ec.Col.Flag)
	return user
}
func GetUsersByDepartment(department string) []User {
	queryParams := om.Params{
		ec.Col.Department: department,
	}
	return getUsers(queryParams)
}
func GetUsersByRole(manager string) []User {
	queryParams := om.Params{
		ec.Col.Role: manager,
	}
	return getUsers(queryParams)
}

func GetUserDict(onlyAvailable bool) map[string]cs.MObject {
	queryParams := om.Params{}
	if onlyAvailable {
		queryParams[cc.Col.Flag] = cc.FlagAvailable
	}
	userDict := make(map[string]cs.MObject)
	if code, userMaps := om.Table(ec.Tbl.User).QueryAll(queryParams); code == st.Success {
		for _, userMap := range userMaps {
			delete(userMap, ec.Col.Password)
			sn := userMap.GetString(ec.Col.Sn)
			if sn == "" {
				continue
			}
			userDict[sn] = userMap
		}
	}
	return userDict
}
func GetDepartmentDict(onlyAvailable bool) map[string]cs.MObject {
	queryParams := om.Params{}
	if onlyAvailable {
		queryParams[cc.Col.Flag] = cc.FlagAvailable
	}
	depDict := make(map[string]cs.MObject)
	if code, depMaps := om.Table(ec.Tbl.Department).QueryAll(queryParams); code == st.Success {
		for _, depMap := range depMaps {
			str := depMap.GetString(ec.Col.String)
			if str == "" {
				continue
			}
			depDict[str] = depMap
		}
	}
	return depDict
}
func getUsers(queryParams om.Params) []User {
	orderParams := om.OrderParams{
		cc.Col.Name: cc.Asc,
	}
	if code, userMaps := om.Table(ec.Tbl.User).Query(queryParams, om.Params{}, om.LimitParams{}, orderParams); strings.EqualFold(code, st.Success) {
		userList := make([]User, 0)
		for _, userMap := range userMaps {
			userList = append(userList, ValueMap2User(userMap))
		}
		return userList
	} else {
		beego.Error("getUsers error")
		return make([]User, 0)
	}
}
