package system

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strings"
	"time"
)

type AdminItem struct {
	AdminId                 int    `description:"系统用户id"`
	AdminName               string `description:"系统用户名称"`
	RealName                string `description:"系统用户姓名"`
	Password                string
	LastUpdatedPasswordTime string `json:"-"`
	Enabled                 int    `description:"1:有效，0:禁用"`
	Email                   string `description:"系统用户邮箱"`
	LastLoginTime           string
	CreatedTime             time.Time
	LastUpdatedTime         string
	Role                    string `description:"系统用户角色"`
	Mobile                  string `description:"手机号"`
	RoleType                int    `description:"角色类型:1需要录入指标,0:不需要"`
	RoleId                  int    `description:"角色id"`
	RoleName                string `description:"角色名称"`
	RoleTypeCode            string `description:"角色编码"`
	DepartmentId            int    `description:"部门id"`
	DepartmentName          string `json:"-" description:"部门名称"`
	TeamId                  int    `description:"三级id"`
	GroupId                 int    `description:"分组id"`
	GroupName               string `json:"-" description:"分组名称"`
	Authority               int    `description:"管理权限，0：无，1：部门负责人，2：小组负责人,或者ficc销售主管，4:ficc销售组长"`
	Position                string `description:"职位"`
	DepartmentGroup         string `description:"部门分组"`
	LabelVal                int    `description:"标签:1:超级管理员，2：管理员，3：部门经理，4：组长，5：ficc销售主管"`
	ResearchGroupName       string `description:"研究方向分组名称"`
	Province                string `description:"省"`
	ProvinceCode            string `description:"省编码"`
	City                    string `description:"市"`
	CityCode                string `description:"市编码"`
	EmployeeId              string `description:"员工工号(钉钉/每刻报销)"`
	TelAreaCode             string `description:"手机区号"`
	IsLdap                  int    `description:"是否为域用户：0-系统账户；1-域用户"`
}

func GetSysuserList(condition string, pars []interface{}, startSize, pageSize int) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += `ORDER BY enabled DESC, last_updated_time DESC, created_time DESC LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func GetSysuserListCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM admin WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

type AdminRespItem struct {
	AdminId                 int    `description:"系统用户id"`
	AdminName               string `description:"系统用户名称"`
	RealName                string `description:"系统用户姓名"`
	Password                string
	LastUpdatedPasswordTime string `json:"-"`
	Enabled                 int    `description:"1:有效，0:禁用"`
	Email                   string `description:"系统用户邮箱"`
	LastLoginTime           string
	CreatedTime             time.Time
	LastUpdatedTime         string
	Role                    string `description:"系统用户角色"`
	Mobile                  string `description:"手机号"`
	RoleType                int    `description:"角色类型:1需要录入指标,0:不需要"`
	RoleId                  int    `description:"角色id"`
	RoleName                string `description:"角色名称"`
	RoleTypeCode            string `description:"角色编码"`
	DepartmentId            int    `description:"部门id"`
	DepartmentName          string `json:"-" description:"部门名称"`
	parentId                int    `description:"父级id"`
	GroupId                 int    `description:"分组id"`
	GroupName               string `json:"-" description:"分组名称"`
	Authority               int    `description:"管理权限，0：无，1：部门负责人，2：小组负责人,或者ficc销售主管，4:ficc销售组长"`
	Position                string `description:"职位"`
	DepartmentGroup         string `description:"部门分组"`
	LabelVal                int    `description:"标签:1:超级管理员，2：管理员，3：部门经理，4：组长，5：ficc销售主管"`
}

type SysuserListResp struct {
	List   []*AdminItem
	Paging *paging.PagingItem `description:"分页数据"`
}

type SysuserAddReq struct {
	AdminName    string `description:"系统用户名称"`
	AdminAvatar  string `description:"用户头像"`
	RealName     string `description:"系统用户姓名"`
	Password     string `description:"密码"`
	Mobile       string `description:"手机号"`
	RoleId       int    `description:"角色id"`
	DepartmentId int    `description:"部门id"`
	GroupId      int    `description:"分组id"`
	TeamId       int    `description:"小组id"`
	//Authority    int    `description:"管理权限，0：无，1：部门负责人，2：小组负责人"`
	Position         string `description:"职位"`
	ResearchGroupIds string `description:"研究方向分组IDs"`
	Province         string `description:"省"`
	ProvinceCode     string `description:"省编码"`
	City             string `description:"市"`
	CityCode         string `description:"市编码"`
	EmployeeId       string `description:"员工工号(钉钉/每刻报销)"`
	Email            string `description:"邮箱"`
	TelAreaCode      string `description:"手机区号"`
	IsLdap           int    `description:"是否为域用户：0-系统账户；1-域用户"`
}

func GetSysAdminCount(adminName string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM admin WHERE admin_name=? `
	o := orm.NewOrm()
	err = o.Raw(sql, adminName).QueryRow(&count)
	return
}

func GetSysAdminByName(adminName string) (item *Admin, err error) {
	sql := `SELECT * FROM admin WHERE admin_name=? `
	o := orm.NewOrm()
	err = o.Raw(sql, adminName).QueryRow(&item)
	return
}

func GetSysAdminById(adminId int) (item *Admin, err error) {
	sql := `SELECT * FROM admin WHERE admin_id=? `
	o := orm.NewOrm()
	err = o.Raw(sql, adminId).QueryRow(&item)
	return
}

func AddAdmin(item *Admin) (err error) {
	o := orm.NewOrm()
	adminId, err := o.Insert(item)
	item.AdminId = int(adminId)
	return
}

type SysuserEditReq struct {
	AdminId          int    `description:"系统用户id"`
	AdminName        string `description:"系统用户名称"`
	RealName         string `description:"系统用户姓名"`
	Mobile           string `description:"手机号"`
	RoleId           int    `description:"角色id"`
	Enabled          int    `description:"1:有效，0:禁用"`
	Position         string `description:"职位"`
	ResearchGroupIds string `description:"研究方向分组IDs"`
	Province         string `description:"省"`
	ProvinceCode     string `description:"省编码"`
	City             string `description:"市"`
	CityCode         string `description:"市编码"`
	EmployeeId       string `description:"员工工号(钉钉/每刻报销)"`
	Email            string `description:"邮箱"`
	TelAreaCode      string `description:"手机区号"`
	IsLdap           int    `description:"是否为域用户：0-系统账户；1-域用户"`
}

type SysUserMoveReq struct {
	AdminId      int `description:"系统用户id"`
	DepartmentId int `description:"部门id"`
	GroupId      int `description:"分组id"`
	TeamId       int `description:"小组id"`
}

type SysUserResetPassReq struct {
	AdminId    int    `description:"系统用户id"`
	Password   string `description:"密码"`
	RePassword string `description:"重复密码"`
}

// SysuserEditEnabledReq 用户状态编辑
type SysuserEditEnabledReq struct {
	AdminId int `description:"系统用户id"`
	Enabled int `description:"1:有效，0:禁用"`
}

// 变更状态
func EditAdminEnabled(item *Admin) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE admin
			SET
			  last_updated_time = NOW(),enabled=? WHERE admin_id = ? `
	_, err = o.Raw(sql, item.Enabled, item.AdminId).Exec()
	return
}

// DisableAdmin 禁用用户
func DisableAdmin(adminId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE admin
			SET
			  last_updated_time = NOW(),disable_time=now(),enabled=0 WHERE admin_id = ? `
	_, err = o.Raw(sql, adminId).Exec()
	return
}

type SysuserDeleteReq struct {
	AdminId int `description:"系统用户id"`
}

func DeleteSysuser(adminId int) (err error) {
	sql := `DELETE FROM admin WHERE admin_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, adminId).Exec()
	return
}

// GetSysAdminCountByMobile 查询系统中是否存在该手机号（如果有传入用户id，那么排除该用户）
func GetSysAdminCountByMobile(mobile string, adminId int) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM admin WHERE mobile=? `
	if adminId > 0 {
		sql += ` AND admin_id != ` + fmt.Sprint(adminId)
	}
	o := orm.NewOrm()
	err = o.Raw(sql, mobile).QueryRow(&count)
	return
}

func GetSysUserItems(condition string, pars []interface{}) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += `ORDER BY last_updated_time DESC `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// GetGroupSysUserList 根据分组id获取系统用户列表
func GetGroupSysUserList(groupId int) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE group_id=? ORDER BY created_time DESC `
	_, err = o.Raw(sql, groupId).QueryRows(&items)
	return
}

// GetDepartmentGroupSysUserList 根据部门id和分组id获取系统用户列表
func GetDepartmentGroupSysUserList(departmentId, groupId int, roleTypeCodes string) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE department_id = ? and group_id=? and enabled=1 `
	if roleTypeCodes != "" {
		sql += ` and role_type_code in (` + roleTypeCodes + `) `
	}
	sql += ` ORDER BY created_time asc `
	_, err = o.Raw(sql, departmentId, groupId).QueryRows(&items)
	return
}

// GetGrooupsysUserList 根据大组id和小组id获取系统用户列表
func GetGrooupsysUserList(groupId int, roleTypeCodes string, enabled int) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE group_id = ? `
	if roleTypeCodes != "" {
		sql += ` and role_type_code in (` + roleTypeCodes + `) `
	}
	if enabled >= 0 {
		sql += fmt.Sprint(` AND enabled=`, enabled, ` `)
	}
	sql += ` ORDER BY created_time asc `
	_, err = o.Raw(sql, groupId).QueryRows(&items)
	return
}

// GetSysAdminByIdSlice 根据账户id列表获取账户信息列表
func GetSysAdminByIdSlice(adminIdList []string) (items []*Admin, err error) {
	if len(adminIdList) <= 0 {
		return
	}
	sql := `SELECT * FROM admin WHERE admin_id in (` + strings.Join(adminIdList, ",") + `) `
	o := orm.NewOrm()
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// GetTeamSysUserList 根据小组id获取系统用户列表
func GetTeamSysUserList(teamId, enabled int) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE group_id=? `
	if enabled >= 0 {
		sql += fmt.Sprint(` AND enabled=`, enabled, ` `)
	}
	sql += ` ORDER BY created_time DESC `
	_, err = o.Raw(sql, teamId).QueryRows(&items)
	return
}

func GetGroupIdByParentId(groupId int) (items []*string, err error) {
	o := orm.NewOrm()
	sql := `SELECT group_id FROM sys_group WHERE parent_id=? ORDER BY create_time DESC `
	_, err = o.Raw(sql, groupId).QueryRows(&items)
	return
}

func GetAdminByGroupId(groupId int) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE group_id=? ORDER BY created_time DESC`
	_, err = o.Raw(sql, groupId).QueryRows(&items)
	return
}

type OpenIdList struct {
	OpenId  string
	AdminId int
}

// GetRaiAdmin 获取权益内部人员(技术组+私募组)
func GetRaiAdmin() (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				admin_id,
				real_name,
				mobile
			FROM
				admin
			WHERE
				role_type_code LIKE '%rai%'
			AND group_id NOT IN (19, 10)
			AND enabled = 1
			OR (
				department_name = '产品技术部'
				AND enabled = 1
			)`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// SyncRoleData 同步角色数据
type SyncRoleData struct {
	Source int `description:"来源: 1-CRM; 2-ETA"`
	RoleId int `description:"角色ID"`
}

// SyncAdminData 同步用户数据
type SyncAdminData struct {
	Source    int    `description:"来源: 1-CRM; 2-ETA"`
	AdminName string `description:"用户名"`
}

// SyncDepartmentData 同步部门数据
type SyncDepartmentData struct {
	Source       int `description:"来源: 1-CRM; 2-ETA"`
	DepartmentId int `description:"部门ID"`
}

// SyncGroupData 同步分组数据
type SyncGroupData struct {
	Source  int `description:"来源: 1-CRM; 2-ETA"`
	GroupId int `description:"分组ID"`
}

// GetSysAdminList 获取admin列表
func GetSysAdminList(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*Admin, err error) {
	fields := "*"
	if len(fieldArr) > 0 {
		fields = strings.Join(fieldArr, ",")
	}
	order := `enabled DESC, last_updated_time DESC`
	if orderRule != "" {
		order = orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM admin WHERE 1=1 %s ORDER BY %s`, fields, condition, order)
	o := orm.NewOrm()
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}
