package system

import (
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/utils"
	"time"
)

type SysRoleAdmin struct {
	Id         int       `orm:"column(id);pk" description:"自增ID"`
	AdminId    int       `orm:"column(admin_id);" description:"系统用户id"`
	RoleId     int       `orm:"column(role_id);" description:"角色ID"`
	CreateTime time.Time `orm:"column(create_time);" description:"创建时间"`
}

type RoleAdminItem struct {
	SysRoleAdminId  int    `description:"管理员账号和角色映射表id"`
	AdminId         int    `description:"系统用户id"`
	AdminName       string `description:"系统用户名称"`
	RealName        string `description:"系统用户姓名"`
	Enabled         int    `description:"1:有效，0:禁用"`
	Mobile          string `description:"手机号"`
	RoleId          int    `description:"角色Id"`
	RoleTypeCode    string `description:"角色编码"`
	DepartmentId    int    `description:"部门id"`
	DepartmentName  string `description:"部门名称"`
	DepartmentGroup string `description:"部门分组"`
	TeamId          int    `description:"小组id"`
	GroupId         int    `description:"分组id"`
	GroupName       string `description:"分组名称"`
	Authority       int    `description:"管理权限，0：无，1：部门负责人，2：小组负责人,或者ficc销售主管，4:ficc销售组长"`
	LabelVal        int    `description:"标签:1:超级管理员，2：管理员，3：部门经理，4：组长，5：ficc销售主管"`
}

func (sa *SysRoleAdmin) TableName() string {
	return "sys_role_admin"
}

// GetRoleIdsByAdminId 根据管理员账号查询角色ID
func GetRoleIdsByAdminId(adminId int) (items []*SysRoleAdmin, err error) {
	sql := `SELECT * from sys_role_admin where admin_id = ?`
	_, err = orm.NewOrm().Raw(sql, adminId).QueryRows(&items)
	return
}

// GetRoleIdsByAdminIdRoleId 根据管理员账号和角色查询
func GetRoleIdsByAdminIdRoleId(adminId int, roleId int) (item *SysRoleAdmin, err error) {
	sql := `SELECT * from sys_role_admin where admin_id = ? and role_id=?`
	err = orm.NewOrm().Raw(sql, adminId, roleId).QueryRow(&item)
	return
}

// GetRoleAdminList 查询对应角色绑定的管理员列表
func GetRoleAdminList(condition string, pars []interface{}, startSize, pageSize int) (list []*RoleAdminItem, err error) {
	sql := `SELECT
	s.id as sys_role_admin_id,
	a.admin_id,
	a.admin_name,
	a.real_name,
	a.mobile,
	a.department_id,
	a.department_name,
	a.enabled,
	a.role_id,
	a.role_type_code ,
	a.group_id,
	a.authority,
	a.group_name
FROM
	sys_role_admin s
	INNER JOIN admin a ON s.admin_id = a.admin_id 
where 1=1`
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY s.id DESC limit ?, ?`
	_, err = orm.NewOrm().Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}

// GetRoleAdminListTotal 查询对应角色绑定的管理员列表总数
func GetRoleAdminListTotal(condition string, pars []interface{}) (total int64, err error) {
	sql := `SELECT
	count(*)
FROM
	sys_role_admin s
	INNER JOIN admin a ON s.admin_id = a.admin_id 
where 1=1`
	if condition != "" {
		sql += condition
	}
	err = orm.NewOrm().Raw(sql, pars).QueryRow(&total)
	return
}

// CheckRoleAdminByAdminIds 判断是否已经绑定过该角色
func CheckRoleAdminByAdminIds(adminIds string, roleId int) (list []*SysRoleAdmin, err error) {
	sql := `SELECT
	s.*
FROM
	sys_role_admin s
	LEFT JOIN admin a ON s.admin_id = a.admin_id 
where s.role_id=? and s.admin_id in (` + adminIds + `)`
	_, err = orm.NewOrm().Raw(sql, roleId).QueryRows(&list)
	return
}

// AddRoleAdminBatch 批量新增留言版管理员
func AddRoleAdminBatch(admins []*SysRoleAdmin) (err error) {
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(admins), admins)
	return
}

// DeleteRoleAdmin 删除管理员和角色的绑定
func DeleteRoleAdmin(SysRoleAdminId int) (err error) {
	sql := `DELETE FROM sys_role_admin WHERE id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, SysRoleAdminId).Exec()
	return
}

// GetRoleAdminById 根据ID查询绑定记录
func GetRoleAdminById(SysRoleAdminId int) (item *SysRoleAdmin, err error) {
	sql := `SELECT
	*
FROM
	sys_role_admin 
where id=?`
	err = orm.NewOrm().Raw(sql, SysRoleAdminId).QueryRow(&item)
	return
}

// GetEnglishAuthRoleAdminList 查询英文权限管理员列表
func GetEnglishAuthRoleAdminList(condition string, pars []interface{}, startSize, pageSize int) (total int, list []*RoleAdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				s.id as sys_role_admin_id,
				a.admin_id,
				a.admin_name,
				a.real_name,
				a.mobile,
				a.department_id,
				a.department_name,
				a.enabled,
				a.role_id,
				a.role_type_code ,
				a.group_id,
				a.authority,
				a.group_name
			FROM
				sys_role_admin AS s
			JOIN sys_role AS r ON s.role_id = r.role_id
			JOIN admin AS a ON s.admin_id = a.admin_id
			WHERE
				1 = 1 `
	sql += condition
	sql += ` GROUP BY s.admin_id `

	totalSQl := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSQl, pars).QueryRow(&total); err != nil {
		return
	}

	sql += ` ORDER BY s.create_time DESC,s.admin_id ASC LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}

// DeleteRoleAdminByAdminIdAndRoleIds 通过管理员ID及角色IDs删除绑定
func DeleteRoleAdminByAdminIdAndRoleIds(adminId int, roleIds []int) (err error) {
	if len(roleIds) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `DELETE FROM sys_role_admin WHERE admin_id = ? AND role_id IN (` + utils.GetOrmInReplace(len(roleIds)) + `) `
	_, err = o.Raw(sql, adminId, roleIds).Exec()
	return
}

// CheckEnglishAuthRoleAdminByAdminIds 通过管理员IDs判断是否已经绑定过英文权限角色
func CheckEnglishAuthRoleAdminByAdminIds(adminIds []int, roleCodes []string) (list []*SysRoleAdmin, err error) {
	if len(adminIds) == 0 || len(roleCodes) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT
				s.*
			FROM
				sys_role_admin AS s
			JOIN sys_role AS r ON s.role_id = r.role_id
			JOIN admin AS a ON s.admin_id = a.admin_id
			WHERE
				s.admin_id IN (` + utils.GetOrmInReplace(len(adminIds)) + `) AND r.role_type_code IN (` + utils.GetOrmInReplace(len(roleCodes)) + `)
			GROUP BY
				s.admin_id`
	_, err = o.Raw(sql, adminIds, roleCodes).QueryRows(&list)
	return
}

// EnglishAuthRoleDetail 英文权限角色详情
type EnglishAuthRoleDetail struct {
	AdminId      int    `description:"用户ID"`
	RoleTypeCode string `description:"角色类型编码"`
}

// GetAdminEnglishAuthRoleDetail 获取用户英文权限详情
func GetAdminEnglishAuthRoleDetail(adminId int, roleCodes []string) (list []*EnglishAuthRoleDetail, err error) {
	if len(roleCodes) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT
				s.admin_id, r.role_type_code
			FROM
				sys_role_admin AS s
			JOIN sys_role AS r ON s.role_id = r.role_id
			JOIN admin AS a ON s.admin_id = a.admin_id
			WHERE
				s.admin_id = ? AND r.role_type_code IN (` + utils.GetOrmInReplace(len(roleCodes)) + `)`
	_, err = o.Raw(sql, adminId, roleCodes).QueryRows(&list)
	return
}

// EditEnglishAuthRoleAdmin 编辑管理员英文权限
func EditEnglishAuthRoleAdmin(adminId int, englishRoleIds []int, roleAdmins []*SysRoleAdmin) (err error) {
	o := orm.NewOrm()
	tx, e := o.Begin()
	if e != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 删除原绑定关系
	sql := `DELETE FROM sys_role_admin WHERE admin_id = ? AND role_id IN (` + utils.GetOrmInReplace(len(englishRoleIds)) + `)`
	_, err = tx.Raw(sql, adminId, englishRoleIds).Exec()
	if err != nil {
		return
	}

	// 新增绑定关系
	_, err = o.InsertMulti(len(roleAdmins), roleAdmins)
	return
}
