package controllers

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

type SysRoleController struct {
	BaseAuthController
}

// @Title 新增角色
// @Description 新增角色接口
// @Param	request	body system.SysRoleAddReq true "type json string"
// @Success 200 新增成功
// @router /role/add [post]
func (this *SysRoleController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysRoleAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RoleName == "" {
		br.Msg = "角色名称不能为空"
		return
	}
	count, err := system.GetSysRoleCount(req.RoleName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "角色已存在,请重新输入"
		return
	}
	item := new(system.SysRole)
	item.RoleName = req.RoleName
	item.RoleType = req.RoleType
	item.RoleTypeCode = services.GetRoleTypeCode(req.RoleType)
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	roleId, err := system.AddSysRole(item)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，Err:" + err.Error()
		return
	}

	// 同步角色缓存
	var syncData system.SyncRoleData
	syncData.Source = utils.SOURCE_CRM_FLAG
	syncData.RoleId = int(roleId)
	_ = utils.Rc.LPush(utils.CACHE_SYNC_ROLE, syncData)

	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// @Title 修改角色
// @Description  修改角色接口
// @Param	request	body system.SysRoleEditReq true "type json string"
// @Success 200 修改成功
// @router /role/edit [post]
func (this *SysRoleController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysRoleEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RoleId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,GroupId 小于等于0 "
		return
	}
	if req.RoleName == "" {
		br.Msg = "角色名称不能为空"
		return
	}
	item, err := system.GetSysRoleByName(req.RoleName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	if item != nil {
		if item.RoleId != req.RoleId {
			br.Msg = "名称已存在，请重新输入"
			return
		}
	}
	roleTypeCode := services.GetRoleTypeCode(req.RoleType)
	err = system.ModifySysRole(req.RoleName, req.RoleType, roleTypeCode, req.RoleId)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败，Err:" + err.Error()
		return
	}

	// 同步角色缓存
	var syncData system.SyncRoleData
	syncData.Source = utils.SOURCE_CRM_FLAG
	syncData.RoleId = item.RoleId
	_ = utils.Rc.LPush(utils.CACHE_SYNC_ROLE, syncData)

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "修改成功"
}

// @Title 删除角色
// @Description 删除角色接口
// @Param	request	body system.SysRoleDeleteReq true "type json string"
// @Success 200 删除成功
// @router /role/delete [post]
func (this *SysRoleController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysRoleDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RoleId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,GroupId 小于等于0 "
		return
	}

	role, e := system.GetSysRoleById(req.RoleId)
	if e != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "角色不存在, 请刷新页面"
			return
		}
		br.Msg = "删除失败"
		br.ErrMsg = "获取角色信息失败, Err: " + e.Error()
		return
	}

	err = system.DeleteSysRole(req.RoleId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败，Err:" + err.Error()
		return
	}

	// 同步角色缓存
	var syncData system.SyncRoleData
	syncData.Source = utils.SOURCE_CRM_FLAG
	syncData.RoleId = role.RoleId
	_ = utils.Rc.LPush(utils.CACHE_SYNC_ROLE, syncData)

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

// @Title 获取角色列表
// @Description 获取角色列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} system.SysRoleListResp
// @router /role/list [get]
func (this *SysRoleController) ListSysRole() {
	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"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND role_name LIKE '%` + keyWord + `%'  `
	}

	total, err := system.GetSysRoleListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	list, err := system.GetSysRoleList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(system.SysRoleListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 角色设置权限-菜单列表
// @Description 角色设置权限-菜单列表
// @Param   RoleId   query   int  true       "角色Id"
// @Success 200 {object} system.SysRoleListResp
// @router /role/menu/list [get]
func (this *SysRoleController) SysRoleMenusList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	roleId, err := this.GetInt("RoleId")
	if err != nil {
		br.Msg = "获取角色失败"
		br.ErrMsg = "获取角色失败，Err:" + err.Error()
		return
	}
	fmt.Println("roleId", roleId)
	list := make([]*system.RoleMenuList, 0)

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	list, err = system.GetRoleMenuList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	lenList := len(list)
	for i := 0; i < lenList; i++ {
		item := list[i]
		child, err := system.GetRoleMenuByParentId(item.MenuId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取子菜单数据失败，Err:" + err.Error()
			return
		}
		list[i].Child = child

		checkList := make([]int, 0)
		if roleId > 0 {
			checkItem, err := system.GetCheckListRoleMenu(roleId, item.MenuId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取选择数据失败，Err:" + err.Error()
				return
			}
			for _, v := range checkItem {
				checkList = append(checkList, v.MenuId)
			}
		}
		list[i].CheckList = checkList
	}
	resp := new(system.RoleMenuListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 角色设置权限
// @Description 角色设置权限
// @Param	request	body system.RoleMenusAddReq true "type json string"
// @Success 200 {object} system.SysRoleListResp
// @router /role/menu/add [post]
func (this *SysRoleController) SysRoleMenusAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.RoleMenusAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	roleId := req.RoleId
	if roleId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,RoleId 小于等于0 "
		return
	}
	if req.MenuIdStr == "" {
		br.Msg = "请选择菜单"
		br.ErrMsg = "请选择菜单，MenuIdStr IS Empty "
		return
	}
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	err = system.DeleteRoleMenuByRoleId(roleId)
	if err != nil {
		br.Msg = "设置失败"
		br.ErrMsg = "清空原有设置失败，Err:" + err.Error()
		return
	}
	menuArr := strings.Split(req.MenuIdStr, ",")
	for _, v := range menuArr {
		menuId, err := strconv.Atoi(v)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "menuId 解析失败，Err:" + err.Error()
			return
		}
		//item := new(system.SysRoleMenu)
		item := new(system.SysRoleMenuCrm)
		item.RoleId = roleId
		item.MenuId = menuId
		_, err = system.AddSysRoleMenuCrm(item)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "新增设置失败，Err:" + err.Error()
			return
		}
	}
	if req.MenuButtonIdStr != "" {
		err = system.DeleteSysRoleButton(roleId)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "删除已设置数据失败，Err:" + err.Error()
			return
		}
		buttonMap := make(map[string]string)
		buttonArr := strings.Split(req.MenuButtonIdStr, ",")
		for _, v := range buttonArr {
			if _, ok := buttonMap[v]; !ok {
				buttonId, err := strconv.Atoi(v)
				count, err := system.GetSysRoleButtonCount(roleId, buttonId)
				if err != nil {
					br.Msg = "判断设置失败存在失败"
					br.ErrMsg = "判断设置失败存在失败，Err:" + err.Error()
					return
				}
				if count <= 0 {
					button := new(system.SysRoleButton)
					button.RoleId = roleId
					button.MenuButtonId = buttonId
					button.CreateTime = time.Now()
					_, err = system.AddSysRoleButton(button)
					if err != nil {
						br.Msg = "设置失败"
						br.ErrMsg = "按钮权限设置失败，Err:" + err.Error()
						return
					}
				}
			}
			buttonMap[v] = v
		}
	} else {
		err = system.DeleteSysRoleButton(roleId)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "删除已设置数据失败，Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "设置成功"
}

// @Title 获取所有角色
// @Description 获取所有角色
// @Success 200 {object} system.SysRoleListResp
// @router /role/all [get]
func (this *SysRoleController) AllSysRole() {
	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"
		return
	}
	levelFlag := false
	roleLevel := this.GetString("RoleLevel")
	if roleLevel != "" {
		levelFlag = true
	}
	list, err := system.GetSysRoleAll(levelFlag)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(system.SysRoleAllResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
