package data_manage_permission

import (
	"encoding/json"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	data_manage_permissionModel "eta/eta_mobile/models/data_manage/data_manage_permission"
	"eta/eta_mobile/services/data/data_manage_permission"
	"eta/eta_mobile/utils"
	"github.com/rdlucklib/rdluck_tools/paging"
)

// EdbChartClassifyList
// @Title 获取指标/图表分类列表数据接口
// @Description 获取指标/图表分类列表数据接口
// @Param   Source   query   int  false       "来源 ：1：手工数据指标 2：上海钢联数据库 3：ETA指标库 4：ETA预测指标 5：图库 6：ETA表格"
// @Param   SubSource   query   int  false       "子来源 ：ETA表格中的各种表格类型，以及图表的来源（这个是后续的扩展方向）"
// @Success 200 {object} data_manage.ChartListResp
// @router /edb_chart/classify [get]
func (c *DataMangePermissionController) EdbChartClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	source, _ := c.GetInt("Source")
	if source <= 0 || source > 6 {
		br.Msg = "错误的来源"
		br.IsSendEmail = false
		return
	}

	// 子来源（目前作用于ETA表格，2024-3-26 14:12:09）
	subSource, _ := c.GetInt("SubSource")
	if source == 6 && (subSource <= utils.EXCEL_DEFAULT || subSource > utils.CUSTOM_ANALYSIS_TABLE) {
		br.Msg = "错误的子来源"
		br.IsSendEmail = false
		return
	}

	list, err := data_manage_permission.GetEdbChartClassifyList(source, subSource)
	if err != nil {
		//br.Success = true
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

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

// SecretEdbChartClassifyList
// @Title 获取涉密的指标/图表分类列表数据接口
// @Description 获取指标/图表分类列表数据接口
// @Param   Source   query   int  false       "来源 ：1：手工数据指标 2：上海钢联数据库 3：ETA指标库 4：ETA预测指标 5：图库 6：ETA表格"
// @Param   SubSource   query   int  false       "子来源 ：ETA表格中的各种表格类型，以及图表的来源（这个是后续的扩展方向）"
// @Success 200 {object} data_manage.ChartListResp
// @router /edb_chart/classify/secret [get]
func (c *DataMangePermissionController) SecretEdbChartClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	source, _ := c.GetInt("Source")
	if source <= 0 || source > 6 {
		br.Msg = "错误的来源"
		br.IsSendEmail = false
		return
	}

	// 子来源（目前作用于ETA表格，2024-3-26 14:12:09）
	subSource, _ := c.GetInt("SubSource")
	if source == 6 && (subSource <= utils.EXCEL_DEFAULT || subSource > utils.CUSTOM_ANALYSIS_TABLE) {
		br.Msg = "错误的子来源"
		br.IsSendEmail = false
		return
	}

	resp, err := data_manage_permission.GetEdbChartClassifyList(source, subSource)
	if err != nil {
		//br.Success = true
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	resp.List = removeNodesWithNoJoinPermissionAndEmptyChildRecursively(resp.List)

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

func removeNodesWithNoJoinPermissionAndEmptyChildRecursively(nodes []*data_manage.EdbChartClassify) []*data_manage.EdbChartClassify {
	var newListNode []*data_manage.EdbChartClassify

	for _, node := range nodes {
		if node.Child != nil {
			node.Child = removeNodesWithNoJoinPermissionAndEmptyChildRecursively(node.Child)
		}

		if node.IsJoinPermission != 0 || (node.Child != nil && len(node.Child) > 0) {
			newListNode = append(newListNode, node)
		}
	}

	return newListNode
}

// MoveEdbChartList
// @Title 获取指标/图表创建人列表数据接口
// @Description 获取指标/图表创建人列表数据接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Source   query   int  false       "来源 ：1：手工数据指标 2：上海钢联数据库 3：ETA指标库 4：ETA预测指标 5：图库 6：ETA表格"
// @Param   SubSource   query   int  false       "子来源 ：目前作用于ETA表格，2024-3-26 14:12:09"
// @Param   Keyword   query   string  false       "关键字，code或者名称"
// @Param   Classify   query   string  false       "分类id"
// @Param   UserId   query   int  false       "创建人id"
// @Success 200 {object} data_manage.ChartListResp
// @router /edb_chart/list [get]
func (c *DataMangePermissionController) MoveEdbChartList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	source, _ := c.GetInt("Source")
	if source <= 0 || source > 6 {
		br.Msg = "错误的来源"
		br.IsSendEmail = false
		return
	}

	// 子来源（目前作用于ETA表格，2024-3-26 14:12:09）
	subSource, _ := c.GetInt("SubSource")
	if source == 6 && (subSource <= utils.EXCEL_DEFAULT || subSource > utils.CUSTOM_ANALYSIS_TABLE) {
		br.Msg = "错误的子来源"
		br.IsSendEmail = false
		return
	}

	userId, _ := c.GetInt("UserId")
	keyword := c.GetString("Keyword")
	classify := c.GetString("Classify")
	pageSize, _ := c.GetInt("PageSize")
	currentIndex, _ := c.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	resp := data_manage.MoveEdbChartListResp{}
	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)
	defaultList := make([]data_manage.MoveEdbChartList, 0)
	resp.List = defaultList
	resp.Paging = page
	// 没有传入条件，那就默认自动返回
	//if userId <= 0 && keyword == `` && classify == `` {
	//	br.Ret = 200
	//	br.Success = true
	//	br.Msg = "获取成功"
	//	br.Data = resp
	//	return
	//}

	list, total, err := data_manage_permission.GetMoveEdbChartList(source, subSource, userId, keyword, classify, startSize, pageSize)
	if err != nil {
		//br.Success = true
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	if list == nil {
		list = defaultList
	}

	page = paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.IsAddLog = false
	br.Data = resp
}

// MoveEdbChartUser
// @Title 指标/图表创建人变更接口
// @Description 指标/图表创建人变更接口
// @Param	request	body data_manage_permissionModel.MoveEdbChartReq true "type json string"
// @Success 200 {object} data_manage.ChartListResp
// @router /edb_chart/change_user [post]
func (c *DataMangePermissionController) MoveEdbChartUser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req data_manage_permissionModel.MoveEdbChartReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.Source <= 0 || req.Source > 6 {
		br.Msg = "错误的来源"
		br.IsSendEmail = false
		return
	}

	// 子来源（目前作用于ETA表格，2024-3-26 14:12:09）
	if req.Source == 6 && (req.SubSource <= utils.EXCEL_DEFAULT || req.SubSource > utils.CUSTOM_ANALYSIS_TABLE) {
		br.Msg = "错误的子来源"
		br.IsSendEmail = false
		return
	}

	if !req.IsSelectAll && len(req.DataIdList) <= 0 {
		br.Msg = "请勾选数据项"
		br.IsSendEmail = false
		return
	}
	if req.NewUserId <= 0 {
		br.Msg = "请选择新的创建人"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data_manage_permission.MoveEdbChart(req.Source, req.SubSource, req.UserId, req.NewUserId, req.IsSelectAll, req.DataIdList, req.NoDataIdList, req.Keyword, req.ClassifyId, sysUser.AdminId)
	if err != nil {
		//br.Success = true
		br.Msg = "移动失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "移动失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.IsAddLog = true
	br.Success = true
	br.Msg = "修改成功"
}

// MoveAllEdbChartUser
// @Title 通过原创建人转移指标/图表创建人接口
// @Description 通过原创建人转移指标/图表创建人接口
// @Param request body data_manage_permission.MoveAllEdbChartReq true "type json string"
// @Success 200 {object} data_manage.ChartListResp
// @router /edb_chart/all/change_user [post]
func (c *DataMangePermissionController) MoveAllEdbChartUser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req data_manage_permissionModel.MoveAllEdbChartReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if len(req.Source) <= 0 {
		br.Msg = "请选择来源"
		br.IsSendEmail = false
		return
	}

	if len(req.OldUserId) <= 0 {
		br.Msg = "请选择旧的创建人"
		br.IsSendEmail = false
		return
	}

	if req.NewUserId <= 0 {
		br.Msg = "请选择新的创建人"
		br.IsSendEmail = false
		return
	}

	err, errMsg := data_manage_permission.MoveAllEdbChart(req.Source, req.OldUserId, req.NewUserId, sysUser.AdminId)
	if err != nil {
		//br.Success = true
		br.Msg = "移动失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "移动失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.IsAddLog = true
	br.Success = true
	br.Msg = "移动成功"
}

// MoveEdbChartCount
// @Title 获取指标/图表创建人汇总数据接口
// @Description 获取指标/图表创建人汇总数据接口
// @Param   UserId   query   int  false       "创建人id"
// @Param   CountType   query   int  false       "来源 ：1：设置资产权限；2：设置数据权限"
// @Success 200 {object} data_manage.ChartListResp
// @router /edb_chart/count [get]
func (c *DataMangePermissionController) MoveEdbChartCount() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	userId, _ := c.GetInt("UserId")
	countType, _ := c.GetInt("CountType", 1)

	// 没有传入条件，那就默认自动返回
	if userId <= 0 {
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		//br.Data = resp
		return
	}

	resp, err := data_manage_permission.GetMoveEdbChartCount(userId, countType)
	if err != nil {
		//br.Success = true
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
