package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/models/system/request"
	"hongze/hz_crm_api/models/system/response"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

type SysRoleAdminController struct {
	BaseAuthController
}

// List
// @Title 获取特定角色下的管理员列表
// @Description 获取特定角色下的管理员列表
// @Param   RoleTypeCode        query   string    false		"角色类型编码"
// @Success 200 {object}  response.RoleAdminItemResp
// @router /role/admin/list [get]
func (this *SysRoleAdminController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	roleTypeCode := this.GetString("RoleTypeCode")
	if roleTypeCode == "" {
		br.Msg = "请输入查询的角色类型"
		br.ErrMsg = "请输入查询的角色类型"
		return
	}
	//根据搜索条件查询账号列表
	// 查询留言管理员的角色ID:yb_comment_admin
	roleInfo, err := system.GetSysRoleByRoleTypeCode(roleTypeCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该角色不存在！"
			br.ErrMsg = "该角色不存在，Err:" + err.Error()
			return
		} else {
			br.Msg = "查询角色信息失败！"
			br.ErrMsg = "查询角色信息失败，Err:" + err.Error()
			return
		}
	}

	var pars []interface{}
	condition := " and s.role_id = ? "
	pars = append(pars, roleInfo.RoleId)

	reqKeyword := this.GetString("Keyword")
	if reqKeyword != "" {
		reqKeyword = "%" + reqKeyword + "%"
		condition += " AND (a.real_name LIKE ? OR a.mobile LIKE ?)"
		pars = append(pars, reqKeyword, reqKeyword)
	}
	adminList, err := system.GetRoleAdminList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取管理账号列表失败！"
		br.ErrMsg = "获取管理账号列表失败，Err:" + err.Error()
		return
	}
	//查询分组信息
	departmentGroupNameMap := make(map[int]string)
	departmentNameMap := make(map[int]string)
	groupList, err := system.GetFullGroup()
	if err != nil {
		br.Msg = "查询分组信息失败！"
		br.ErrMsg = "查询分组信息失败，Err:" + err.Error()
		return
	}
	departmentList, err := system.GetDepartmentList()
	if err != nil {
		br.Msg = "查询部门信息失败！"
		br.ErrMsg = "查询部门信息失败，Err:" + err.Error()
		return
	}
	for _, d := range departmentList {
		departmentNameMap[d.DepartmentId] = d.DepartmentName
	}
	for _, g := range groupList {
		if g.ParentGroupName != "" {
			departmentGroupNameMap[g.GroupId] = g.DepartmentName + "/" + g.ParentGroupName + "/" + g.GroupName
		} else {
			departmentGroupNameMap[g.GroupId] = g.DepartmentName + "/" + g.GroupName
		}
	}
	// 查询角色信息
	roles, err := system.GetSysRoleAll(false)
	if err != nil {
		br.Msg = "查询角色信息失败！"
		br.ErrMsg = "查询角色信息失败，Err:" + err.Error()
		return
	}
	rolesNameMap := make(map[int]string)
	for _, v := range roles {
		rolesNameMap[v.RoleId] = v.RoleName
	}
	var list []*response.RoleAdminItemResp
	for _, v := range adminList {
		item := new(response.RoleAdminItemResp)
		item.SysRoleAdminId = v.SysRoleAdminId
		item.AdminId = v.AdminId
		item.Mobile = v.Mobile
		item.RealName = v.RealName
		item.Enabled = v.Enabled
		if v.GroupId > 0 {
			if departmentGroup, ok := departmentGroupNameMap[v.GroupId]; ok {
				item.DepartmentGroup = departmentGroup
			}
		} else {
			if departmentName, ok := departmentNameMap[v.DepartmentId]; ok {
				item.DepartmentGroup = departmentName
			}
		}

		// 整理角色名称
		item.RoleId = v.RoleId
		if rolesName, ok := rolesNameMap[v.RoleId]; ok {
			item.RoleName = rolesName
		}
		// 整理标签
		if v.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
			item.LabelVal = 1
		} else if v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
			v.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			item.LabelVal = 2
		} else {
			if v.Authority == 1 {
				item.LabelVal = 3
			} else if v.Authority == 2 && v.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
				item.LabelVal = 4
			} else if v.Authority == 2 && v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
				item.LabelVal = 5
			} else if v.Authority == 4 {
				item.LabelVal = 4
			}
		}

		list = append(list, item)
	}

	// 获取列表分页总数
	total, err := system.GetRoleAdminListTotal(condition, pars)
	if err != nil {
		br.Msg = "获取留言列表总数失败！"
		br.ErrMsg = "获取留言列表总数失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, int(total))
	resp := response.RoleAdminListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
	return
}

// AddAdmin
// @Title 新增留言管理管理员
// @Description 新增留言管理管理员
// @Param	request	body request.AddRoleAdminReq true "type json string"
// @Success Ret=200 操作成功
// @router /role/admin/add [post]
func (this *SysRoleAdminController) AddAdmin() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req request.AddRoleAdminReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	// 校验参数
	sliceAdmin := strings.Split(req.AdminIds, ",")
	if len(sliceAdmin) > 0 {
		for _, v := range sliceAdmin {
			_, tErr := strconv.Atoi(v)
			if tErr != nil {
				br.Msg = "请先选择用户！"
				br.ErrMsg = "参数解析异常，Err:" + tErr.Error()
				return
			}
		}
	}

	if req.RoleTypeCode == "" {
		br.Msg = "请输入角色类型"
		br.ErrMsg = "请输入角色类型"
		return
	}
	// 查询留言管理员的角色ID
	roleInfo, err := system.GetSysRoleByRoleTypeCode(req.RoleTypeCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该角色不存在！"
			br.ErrMsg = "该角色不存在，Err:" + err.Error()
			return
		} else {
			br.Msg = "查询角色信息失败！"
			br.ErrMsg = "查询角色信息失败，Err:" + err.Error()
			return
		}
	}

	// 查询已绑定的管理员账号
	var unBindAdminIds []int
	bindAdminMap := make(map[int]bool)
	hasBindList, err := system.CheckRoleAdminByAdminIds(req.AdminIds, roleInfo.RoleId)
	if err != nil {
		br.Msg = "查询已有的账号失败！"
		br.ErrMsg = "查询已有的账号失败，Err:" + err.Error()
		return
	}
	for _, v := range hasBindList {
		bindAdminMap[v.AdminId] = true
	}
	for _, v := range sliceAdmin {
		adminId, _ := strconv.Atoi(v)
		if _, ok := bindAdminMap[adminId]; !ok {
			unBindAdminIds = append(unBindAdminIds, adminId)
		}
	}
	if len(unBindAdminIds) == 0 {
		br.Msg = "账号已绑定，无需重复绑定"
		br.ErrMsg = "账号已绑定，无需重复绑定"
		return
	}
	//组装批量新增的信息
	admins := make([]*system.SysRoleAdmin, 0)
	for _, v := range unBindAdminIds {
		adminAdd := &system.SysRoleAdmin{
			AdminId:    v,
			RoleId:     roleInfo.RoleId,
			CreateTime: time.Now(),
		}
		admins = append(admins, adminAdd)
	}
	err = system.AddRoleAdminBatch(admins)
	if err != nil {
		br.Msg = "绑定操作失败"
		br.ErrMsg = "绑定操作失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	return
}

// DeleteAdmin
// @Title 删除留言管理管理员
// @Description 删除留言管理管理员
// @Param	request	body request.DelCommentAdminReq true "type json string"
// @Success Ret=200 操作成功
// @router /role/admin/del [post]
func (this *SysRoleAdminController) DeleteAdmin() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req request.DelRoleAdminReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.SysRoleAdminId <= 0 {
		br.Msg = "请输入需要删除的绑定ID！"
		br.ErrMsg = "请输入需要删除的绑定ID！"
		return
	}

	err = system.DeleteRoleAdmin(req.SysRoleAdminId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	return
}

// SellerList
// @Title 获取未配置权限的管理员（根据部门、分组）
// @Description 获取未配置权限的管理员（根据部门、分组）接口
// @Success 200 {object} response.DepartmentGroupSellersResp
// @router /role/seller/list [get]
func (this *SysRoleAdminController) SellerList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	departmentList, err := system.GetDepartmentList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取部门失败,Err:" + err.Error()
		return
	}
	departmentMap := make(map[int]*system.SysDepartmentList)
	for _, v := range departmentList {
		departmentMap[v.DepartmentId] = v
	}
	fullGroups, err := system.GetFullGroup()
	if err != nil {
		br.Msg = "获取分组失败"
		br.ErrMsg = "获取分组失败,Err:" + err.Error()
		return
	}
	fullGroupMap := make(map[int]*system.SysFullGroup)
	for _, v := range fullGroups {
		fullGroupMap[v.GroupId] = v
	}
	var list []response.DepartmentGroupSellers
	departmentListMap := make(map[int][]response.DepartmentGroupSellers)
	groupListMap := make(map[int][]response.DepartmentGroupSellers)
	teamListMap := make(map[int][]response.DepartmentGroupSellers)
	departmentHasMap := make(map[int]bool)
	groupHasMap := make(map[int]bool)
	teamHasMap := make(map[int]bool)

	condition := " and enabled = 1 "
	sellerList, err := system.GetSysUserItems(condition, []interface{}{})
	if err != nil {
		br.Msg = "获取管理账号失败"
		br.ErrMsg = "获取管理账号失败,Err:" + err.Error()
		return
	}
	for _, v := range sellerList {
		tmp := response.DepartmentGroupSellers{
			AdminId:  strconv.Itoa(v.AdminId),
			RealName: v.RealName,
		}
		if v.GroupId > 0 {
			if groupInfo, ok := fullGroupMap[v.GroupId]; ok {
				if groupInfo.ParentId > 0 {
					teamListMap[v.GroupId] = append(teamListMap[v.GroupId], tmp)
				} else {
					groupListMap[groupInfo.GroupId] = append(groupListMap[groupInfo.GroupId], tmp)
				}
			}
		} else {
			departmentListMap[v.DepartmentId] = append(departmentListMap[v.DepartmentId], tmp)
		}
	}
	for _, groupInfo := range fullGroups {
		var team1 response.DepartmentGroupSellers
		//处理小组
		if groupInfo.ParentId > 0 {
			if _, ok2 := teamHasMap[groupInfo.GroupId]; !ok2 {
				if len(teamListMap[groupInfo.GroupId]) > 0 {
					team1 = response.DepartmentGroupSellers{
						AdminId:      "team_" + strconv.Itoa(groupInfo.GroupId),
						RealName:     groupInfo.GroupName,
						ChildrenList: teamListMap[groupInfo.GroupId],
					}
					teamHasMap[groupInfo.GroupId] = true
					groupListMap[groupInfo.ParentId] = append(groupListMap[groupInfo.ParentId], team1)
				}
			}
		}
	}

	for _, groupInfo := range fullGroups {
		var group1 response.DepartmentGroupSellers
		//处理大组
		if groupInfo.ParentId == 0 {
			if _, ok2 := groupHasMap[groupInfo.GroupId]; !ok2 {
				if len(groupListMap[groupInfo.GroupId]) > 0 {
					group1 = response.DepartmentGroupSellers{
						AdminId:      "group_" + strconv.Itoa(groupInfo.GroupId),
						RealName:     groupInfo.GroupName,
						ChildrenList: groupListMap[groupInfo.GroupId],
					}
					groupHasMap[groupInfo.GroupId] = true
					departmentListMap[groupInfo.DepartmentId] = append(departmentListMap[groupInfo.DepartmentId], group1)
				}
			}
		}
	}

	for _, groupInfo := range departmentList {
		var department1 response.DepartmentGroupSellers
		//处理部门
		if _, ok1 := departmentHasMap[groupInfo.DepartmentId]; !ok1 {
			if len(departmentListMap[groupInfo.DepartmentId]) > 0 {
				department1 = response.DepartmentGroupSellers{
					AdminId:      "department_" + strconv.Itoa(groupInfo.DepartmentId),
					RealName:     groupInfo.DepartmentName,
					ChildrenList: departmentListMap[groupInfo.DepartmentId],
				}
				departmentHasMap[groupInfo.DepartmentId] = true
				list = append(list, department1)
			}
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = response.DepartmentGroupSellersResp{
		List: list,
	}
	return
}
