package controllers

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/system"
	"eta/eta_api/utils"
	"fmt"
	"strings"
	"time"
)

// 系统设置
type SysDepartmentController struct {
	BaseAuthController
}

// @Title 新增部门
// @Description 新增部门接口
// @Param	request	body system.SysDepartmentAddReq true "type json string"
// @Success 200 新增成功
// @router /department/add [post]
func (this *SysDepartmentController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysDepartmentAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.DepartmentName == "" {
		br.Msg = "部门名称不能为空"
		return
	}
	count, err := system.GetSysDepartmentCount(req.DepartmentName)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败"
		return
	}
	if count > 0 {
		br.Msg = "部门名称已存在,请重新输入"
		return
	}
	item := new(system.SysDepartment)
	item.DepartmentName = req.DepartmentName
	item.CreateTime = time.Now()
	departmentId, err := system.AddSysDepartment(item)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，Err:" + err.Error()
		return
	}

	// 同步部门缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncDepartmentData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.DepartmentId = int(departmentId)
		_ = utils.Rc.LPush(utils.CACHE_SYNC_DEPARTMENT, syncData)
	}

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

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

	// 同步部门缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncDepartmentData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.DepartmentId = req.DepartmentId
		_ = utils.Rc.LPush(utils.CACHE_SYNC_DEPARTMENT, syncData)
	}

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

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

	// 同步部门缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncDepartmentData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.DepartmentId = req.DepartmentId
		_ = utils.Rc.LPush(utils.CACHE_SYNC_DEPARTMENT, syncData)
	}

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

// @Title 获取部门列表
// @Description 获取部门列表接口
// @Success 200 {object} system.SysDepartmentListResp
// @router /department/list [get]
func (this *SysDepartmentController) ListDepartment() {
	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
	}
	list, err := system.GetDepartmentList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	lenList := len(list)
	for i := 0; i < lenList; i++ {
		departmentId := list[i].DepartmentId
		groupList, err := system.GetSysGroupByDepartmentId(departmentId)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		list[i].Child = groupList
		list[i].IsDepartment = true
		for i2, sysGroup := range groupList {
			teamList, err := system.GetSysTeamByDepartmentId(sysGroup.GroupId)
			if err != nil {
				br.Msg = "获取数据失败"
				br.ErrMsg = "获取数据失败，Err:" + err.Error()
				return
			}
			groupList[i2].Child = teamList
			groupList[i2].IsGroup = true
		}
	}
	resp := new(system.SysDepartmentListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// DepartmentUserTree
// @Title 获取部门及分组用户树
// @Description 获取部门列表接口
// @Success 200 {object} system.DepartmentUserTree
// @router /department/user_tree [get]
func (this *SysDepartmentController) DepartmentUserTree() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	keywords := this.GetString("Keywords", "")
	keywords = strings.TrimSpace(keywords)

	// 获取部门/分组/用户
	departments, e := system.GetDepartmentList()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取部门失败，Err:" + e.Error()
		return
	}
	groups, e := system.GetFullGroup()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取分组失败，Err:" + e.Error()
		return
	}
	cond := ` AND enabled = 1`
	pars := make([]interface{}, 0)
	if keywords != "" {
		kw := fmt.Sprint("%", keywords, "%")
		cond += ` AND real_name LIKE ?`
		pars = append(pars, kw)
	}
	admins, e := system.GetSysAdminList(cond, pars, []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取用户失败，Err:" + e.Error()
		return
	}

	// 用户map
	departmentAdmins := make(map[int][]*system.DepartmentUserTree, 0)
	groupAdmins := make(map[int][]*system.DepartmentUserTree, 0)
	for _, v := range admins {
		t := new(system.DepartmentUserTree)
		t.NodeId = v.AdminId
		t.NodeType = 3
		t.NodeName = v.RealName
		t.Children = make([]*system.DepartmentUserTree, 0)
		if groupAdmins[v.GroupId] == nil {
			groupAdmins[v.GroupId] = make([]*system.DepartmentUserTree, 0)
		}
		groupAdmins[v.GroupId] = append(groupAdmins[v.GroupId], t)

		// 直属于部门
		if v.GroupId == 0 {
			if departmentAdmins[v.DepartmentId] == nil {
				departmentAdmins[v.DepartmentId] = make([]*system.DepartmentUserTree, 0)
			}
			departmentAdmins[v.DepartmentId] = append(departmentAdmins[v.DepartmentId], t)
		}
	}

	// 小组
	groupTeams := make(map[int][]*system.DepartmentUserTree, 0)
	for _, v := range groups {
		if v.ParentId == 0 {
			continue
		}
		// 关键词查询时不显示空组
		if keywords != "" && groupAdmins[v.GroupId] == nil {
			continue
		}
		t := new(system.DepartmentUserTree)
		t.NodeId = v.GroupId
		t.NodeName = v.GroupName
		t.NodeType = 2
		t.Children = make([]*system.DepartmentUserTree, 0)
		t.Children = groupAdmins[v.GroupId]
		if groupTeams[v.ParentId] == nil {
			groupTeams[v.ParentId] = make([]*system.DepartmentUserTree, 0)
		}
		groupTeams[v.ParentId] = append(groupTeams[v.ParentId], t)
	}

	// 大组
	departmentGroups := make(map[int][]*system.DepartmentUserTree, 0)
	for _, v := range groups {
		if v.ParentId > 0 {
			continue
		}
		// 关键词查询时不显示空组
		if keywords != "" && groupAdmins[v.GroupId] == nil && groupTeams[v.GroupId] == nil {
			continue
		}
		t := new(system.DepartmentUserTree)
		t.NodeId = v.GroupId
		t.NodeName = v.GroupName
		t.NodeType = 2
		t.Children = make([]*system.DepartmentUserTree, 0)
		if groupTeams[v.GroupId] != nil {
			t.Children = append(t.Children, groupTeams[v.GroupId]...)
		}
		if groupAdmins[v.GroupId] != nil {
			t.Children = append(t.Children, groupAdmins[v.GroupId]...)
		}
		if departmentGroups[v.DepartmentId] == nil {
			departmentGroups[v.DepartmentId] = make([]*system.DepartmentUserTree, 0)
		}
		departmentGroups[v.DepartmentId] = append(departmentGroups[v.DepartmentId], t)
	}

	// 部门
	list := make([]*system.DepartmentUserTree, 0)
	for _, v := range departments {
		// 关键词查询时不显示空部门
		if keywords != "" && departmentGroups[v.DepartmentId] == nil && departmentAdmins[v.DepartmentId] == nil {
			continue
		}
		t := new(system.DepartmentUserTree)
		t.NodeId = v.DepartmentId
		t.NodeType = 1
		t.NodeName = v.DepartmentName
		t.Children = make([]*system.DepartmentUserTree, 0)
		if departmentGroups[v.DepartmentId] != nil {
			t.Children = append(t.Children, departmentGroups[v.DepartmentId]...)
		}
		if departmentAdmins[v.DepartmentId] != nil {
			t.Children = append(t.Children, departmentAdmins[v.DepartmentId]...)
		}
		list = append(list, t)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}
