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:"手机区号"`
}

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:"手机区号"`
}

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:"手机区号"`
}

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:"重复密码"`
}

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

func EditAdmin(item *Admin) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE admin
			SET
			  admin_name= ?,
			  real_name = ?,
			  password = ?,
			  last_updated_password_time = NOW(),
			  email = ?,
			  last_updated_time = NOW(),
			  mobile = ?,
			  role_type = ?,
			  role_id = ?,
			  role_name = ?,
			  department_id = ?,
			  department_name = ?,
			  group_id = ?,
			  group_name = ?,
			  authority = ?,
			  position = ?,
			  role_type_code=?,
			  enabled=?,
			  admin_avatar = ?,
			  province=?,
			  province_code=?,
			  city=?,
			  city_code=?,
			  employee_id = ?
			WHERE admin_id = ? `
	_, err = o.Raw(sql, item.AdminName, item.RealName, item.Password, item.Email, item.Mobile, item.RoleType, item.RoleId, item.RoleName, item.DepartmentId, item.DepartmentName,
		item.GroupId, item.GroupName, item.Authority, item.Position, item.RoleTypeCode, item.Enabled, item.AdminAvatar, item.Province, item.ProvinceCode, item.City, item.CityCode, item.EmployeeId, item.AdminId).Exec()
	return
}

// 变更状态
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
}

func GetSysUserItemsOrderByCreated(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 created_time DESC `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}
func GetSysUserItemsList(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 created_time DESC limit ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}
func GetSysUserItemsTotal(condition string, pars []interface{}) (total int64, err error) {
	o := orm.NewOrm()
	sql := `SELECT count(*) FROM admin WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&total)
	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
}

// GetTeamSysUserList 根据小组id获取系统用户列表
func GetTeamSysUserListByIds(ids string) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE group_id IN (` + ids + `) ORDER BY created_time DESC `
	_, err = o.Raw(sql).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
}

// GetSysUserByParentIdGroupId 查询主管下的所有组员
func GetSysUserByParentIdGroupId(groupId int) (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `select real_name, role_id, role_type_code, group_id, admin_id from admin where group_id in (SELECT group_id from sys_group where parent_id=?) OR group_id=?`
	_, err = o.Raw(sql, groupId, 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
}

// GetSysAdminByIds 根据主键集合获取管理员信息
func GetSysAdminByIds(adminIds string) (items []*Admin, err error) {
	if adminIds == "" {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT * FROM admin WHERE admin_id IN (` + adminIds + `)`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type OpenIdList struct {
	OpenId  string
	AdminId int
}

// GetAdminOpenIdListByMobile 根据手机号获取用户的openid列表
func GetAdminOpenIdListByMobile(mobile string) (items []*OpenIdList, err error) {
	sql := `SELECT admin_id, open_id FROM admin 
          WHERE open_id != "" and mobile=? `
	_, err = orm.NewOrm().Raw(sql, mobile).QueryRows(&items)
	return
}

// ResearcherAdminAndUser 研究员admin信息及wx_user信息
type ResearcherAdminAndUser struct {
	UserId    int    `description:"用户ID"`
	UserName  string `description:"用户名称"`
	AdminId   int    `description:"管理员ID"`
	AdminName string `description:"管理员姓名"`
	OpenId    string `description:"openid"`
}

// GetResearcherAdminAndWxUserByAdminId 通过adminId获取研究员admin及user信息
func GetResearcherAdminAndWxUserByAdminId(adminId int) (item *ResearcherAdminAndUser, err error) {
	sql := `SELECT
				a.admin_id,
				a.real_name AS admin_name,
				a.open_id,
				b.user_id,
				b.real_name AS user_name
			FROM
				admin AS a
			JOIN wx_user AS b ON a.mobile = b.mobile
			WHERE
				a.admin_id = ? AND a.open_id != ""`
	err = orm.NewOrm().Raw(sql, adminId).QueryRow(&item)
	return
}

// 获取本组的销售ID
func GetSelleridWhichGroup(companyId, productId int) (adminId string, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT admin_id SEPARATOR ',' ) AS adminId
			FROM
			admin
			WHERE
			group_id IN (
			SELECT
			a.group_id
			FROM
			company_product AS a
			INNER JOIN admin AS b ON a.seller_id = b.admin_id
			WHERE
			a.company_id = ?
			AND a.product_id = ?
)`
	err = o.Raw(sql, companyId, productId).QueryRow(&adminId)
	return
}

// GetSysuserRaiList 获取权益销售
func GetSysuserRaiList() (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			real_name,
			mobile,
			group_name 
		FROM
			admin 
		WHERE
			role_type_code LIKE '%rai%' 
			AND group_id NOT IN ( 19, 10, 17 ) 
			AND enabled = 1 
			OR real_name IN ( '沈涛', '张传星' )  
			OR mobile IN ( '15011263967', '18935318900' , '15600639653', '18010097689', '13520990566') ` // 先写死，看情况要不要改
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetSellerIdsByDepId(depId int) (ids []string, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	admin_id
FROM
	admin 
WHERE
	department_id = ?  `
	_, err = o.Raw(sql, depId).QueryRows(&ids)
	return
}

// 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
}

// GetFiccEnterScoreAdmin 获取Ficc需要录分的研究员
func GetFiccEnterScoreAdmin() (items []*AdminItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT   *  FROM admin_cygx WHERE group_name  IN('宏观组','建材组','有色组','能化组','海外组')  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"`
}
