package data_manage

import (
	"encoding/json"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/data_manage"
	"hongze/hz_crm_api/models/data_manage/request"
	"hongze/hz_crm_api/models/data_manage/response"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services/data"
	"hongze/hz_crm_api/utils"
)

// EdbNoPermissionList
// @Title 获取指标无权限用户列表数据接口
// @Description 获取指标无权限用户列表数据接口
// @Param   EdbInfoId   query   int  true       "指标id"
// @Success 200 {object} response.EdbNoPermissionAdminResp
// @router /edb_no_permission/list [get]
func (this *EdbInfoController) EdbNoPermissionList() {
	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
	}

	edbInfoId, _ := this.GetInt("EdbInfoId")
	if edbInfoId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}

	resp := response.EdbNoPermissionAdminResp{}
	list := make([]response.Admin, 0)

	obj := data_manage.EdbInfoNoPermissionAdmin{}
	tmpList, err := obj.GetAllListByEdbInfoId(edbInfoId)
	if err != nil {
		//br.Success = true
		br.Msg = "获取失败"
		br.ErrMsg = "获取配置失败,Err:" + err.Error()
		return
	}
	if len(tmpList) > 0 {
		adminIdList := make([]int, 0)
		for _, v := range tmpList {
			adminIdList = append(adminIdList, v.AdminId)
		}
		adminList, err := system.GetAdminListByIdList(adminIdList)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取用户列表失败,Err:" + err.Error()
		}

		// 查询所有的分组，避免下面多次操作数据库
		groupMap := make(map[int]*system.SysFullGroup)
		if len(adminList) > 0 {
			groupList, err := system.GetFullGroup()
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "查询分组失败，err：" + err.Error()
				return
			}
			for _, v := range groupList {
				groupMap[v.GroupId] = v
			}
		}

		for _, v := range adminList {
			var secondName string
			if v.GroupId != 0 {
				if fullGroup, ok := groupMap[v.GroupId]; ok {
					secondName = fullGroup.ParentGroupName
				}
			}

			departmentGroup := ``
			if v.DepartmentName != "" {
				if v.GroupName == "" {
					departmentGroup = v.DepartmentName
				} else if secondName != `` {
					departmentGroup = v.DepartmentName + "/" + secondName + "/" + v.GroupName
				} else {
					departmentGroup = v.DepartmentName + "/" + v.GroupName
				}
			}
			list = append(list, response.Admin{
				AdminId:         v.AdminId,
				RealName:        v.RealName,
				RoleName:        v.RoleName,
				DepartmentGroup: departmentGroup,
			})
		}
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ModifyNoPermissionAdmin
// @Title 修改指标无权限用户数据接口（覆盖）
// @Description 修改指标无权限用户数据接口（覆盖）
// @Param	request	body request.ModifyEdbNoPermissionAdminReq true "type json string"
// @Success 200 Ret=200 配置成功
// @router /edb_no_permission/modify [post]
func (this *EdbInfoController) ModifyNoPermissionAdmin() {
	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.ModifyEdbNoPermissionAdminReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.EdbInfoId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	if len(req.AdminIdList) <= 0 {
		br.Msg = "请选择用户"
		br.IsSendEmail = false
		return
	}

	edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
	if err != nil {
		br.Msg = "修改失败"
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "找不到该指标"
			br.IsSendEmail = false
		}
		br.ErrMsg = "修改失败,Err：" + err.Error()
		return
	}
	obj := data_manage.EdbInfoNoPermissionAdmin{}
	err = obj.ModifyByEdbInfoId(edbInfo.EdbInfoId, req.AdminIdList)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败,Err：" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "配置成功"
}

// DelNoPermissionAdmin
// @Title 删除指标无权限用户数据配置接口
// @Description 删除指标无权限用户数据配置接口
// @Param	request	body request.DelEdbNoPermissionAdminReq true "type json string"
// @Success 200 Ret=200 配置成功
// @router /edb_no_permission/delete [post]
func (this *EdbInfoController) DelNoPermissionAdmin() {
	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.DelEdbNoPermissionAdminReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.EdbInfoId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	if req.AdminId <= 0 {
		br.Msg = "请选择用户"
		br.IsSendEmail = false
		return
	}

	edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
	if err != nil {
		br.Msg = "删除失败"
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "找不到该指标"
			br.IsSendEmail = false
		}
		br.ErrMsg = "删除失败,Err：" + err.Error()
		return
	}
	obj := data_manage.EdbInfoNoPermissionAdmin{}
	err = obj.DeleteByEdbInfoIdAndAdminId(edbInfo.EdbInfoId, req.AdminId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err：" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// BatchAddNoPermissionAdmin
// @Title 批量添加指标无权限用户数据接口（新增）
// @Description 批量添加指标无权限用户数据接口（新增）
// @Param	request	body request.ModifyEdbNoPermissionAdminReq true "type json string"
// @Success 200 Ret=200 配置成功
// @router /edb_no_permission/batch_add [post]
func (this *EdbInfoController) BatchAddNoPermissionAdmin() {
	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.BatchAddEdbNoPermissionAdminReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if len(req.EdbInfoIdList) <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	if len(req.AdminIdList) <= 0 {
		br.Msg = "请选择用户"
		br.IsSendEmail = false
		return
	}

	err = data.BatchAddNoPermissionAdmin(req.EdbInfoIdList, req.AdminIdList)
	if err != nil {
		br.Msg = "配置失败"
		br.ErrMsg = "配置失败,Err：" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "配置成功"
}
