package data_manage

import (
	"eta_gn/eta_api/models"
	"eta_gn/eta_api/models/data_manage"
	"eta_gn/eta_api/models/data_manage/response"
	"eta_gn/eta_api/models/system"
	"eta_gn/eta_api/services/data"
	"eta_gn/eta_api/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"sort"
)

// WindClassify
// @Title wind指标分类
// @Description wind指标分类
// @Success 200 {object} data_manage.BaseFromYongyiClassify
// @router /wind/classify [get]
func (this *EdbInfoController) WindClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	// 默认查一级分类和一级分类下的指标信息,
	// 如果是 子级分类,查询该子级分类的下一级分类和指标信息
	// 增加标识判断是文件夹还是指标列表
	parentId, _ := this.GetInt("ParentId")
	// 特殊处理顶级分类
	rootList, err := data_manage.GetEdbClassifyByParentId(parentId, 0, 0)
	if err != nil && !utils.IsErrNoRow(err) {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}
	realRootMap := make(map[int]struct{})
	if parentId == 0 {
		// 查询wind指标的所有一级分类
		classifyIdList, e := data_manage.GetEdbClassifyIdListBySource(utils.DATA_SOURCE_WIND)
		if e != nil && !utils.IsErrNoRow(e) {
			br.Msg = "获取失败"
			br.ErrMsg = "获取分类列表失败,Err:" + e.Error()
			return
		}
		if len(classifyIdList) == 0 {
			resp := new(data_manage.EdbClassifyListResp)
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			br.Data = resp
			return
		}
		// 查询wind指标的所有一级分类下的指标信息
		rootIds, e := data_manage.GetEdbClassifyRootIdsByClassifyIds(classifyIdList)
		if e != nil && !utils.IsErrNoRow(e) {
			br.Msg = "获取失败"
			br.ErrMsg = "获取分类列表失败,Err:" + e.Error()
			return
		}
		for _, v := range rootIds {
			realRootMap[v] = struct{}{}
		}
	}
	nodeAll := make([]*data_manage.EdbClassifyItems, 0)

	var sortList data_manage.EdbClassifyItemList
	if parentId > 0 {
		// 查询挂在当前分类上的指标列表
		// 获取当前账号的不可见指标
		obj := data_manage.EdbInfoNoPermissionAdmin{}
		confList, err := obj.GetAllListByAdminId(this.SysUser.AdminId)
		if err != nil && !utils.IsErrNoRow(err) {
			br.Msg = "获取失败"
			br.ErrMsg = "获取不可见指标配置数据失败,Err:" + err.Error()
			return
		}
		noPermissionEdbInfoIdMap := make(map[int]bool)
		for _, v := range confList {
			noPermissionEdbInfoIdMap[v.EdbInfoId] = true
		}
		allEdbInfo, err := data_manage.GetEdbInfoByClassifyIdAndSource(parentId, 0, utils.DATA_SOURCE_WIND)
		if err != nil {
			br.Msg = "获取指标数据失败"
			br.ErrMsg = "获取指标数据失败,Err:" + err.Error()
			return
		}

		if len(allEdbInfo) > 0 {
			// 查询当前子分类信息
			/*currClassify, err := data_manage.GetEdbClassifyById(parentId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取当前分类信息失败,Err:" + err.Error()
				return
			}
			// 获取所有有权限的指标和分类
			permissionEdbIdList, permissionClassifyIdList, err := data_manage_permission.GetUserEdbAndClassifyPermissionList(this.SysUser.AdminId, 0, 0)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取所有有权限的指标和分类失败,Err:" + err.Error()
				return
			}*/
			for _, v := range allEdbInfo {
				// 如果指标不可见,那么就不返回该指标
				if _, ok := noPermissionEdbInfoIdMap[v.EdbInfoId]; ok {
					continue
				}
				//v.HaveOperaAuth = data_manage_permission.CheckEdbPermissionByPermissionIdList(v.IsJoinPermission, currClassify.IsJoinPermission, v.EdbInfoId, v.ClassifyId, permissionEdbIdList, permissionClassifyIdList)
				/*button := data.GetEdbOpButton(this.SysUser, v.SysUserId, v.EdbType, utils.EDB_INFO_TYPE, v.HaveOperaAuth)
				button.AddButton = false //不管有没有权限,指标都是没有添加按钮的
				v.Button = button*/
				v.Children = make([]*data_manage.EdbClassifyItems, 0)
				v.ParentId = parentId
				nodeAll = append(nodeAll, v)
			}
		}

	}
	if len(rootList) > 0 {
		// 已授权分类id
		/*permissionClassifyIdList, err := data_manage_permission.GetUserEdbClassifyPermissionList(this.SysUser.AdminId, 0)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取已授权分类id数据失败,Err:" + err.Error()
			return
		}*/

		for _, v := range rootList {
			// 数据权限
			/*v.HaveOperaAuth = data_manage_permission.CheckEdbClassifyPermissionByPermissionIdList(v.IsJoinPermission, v.ClassifyId, permissionClassifyIdList)
			// 按钮权限
			button := data.GetEdbClassifyOpButton(this.SysUser, v.SysUserId, v.HaveOperaAuth)
			v.Button = button*/
			if _, ok := realRootMap[v.ClassifyId]; !ok && parentId == 0 { //查询一级分类时,过滤
				continue
			}
			v.Children = make([]*data_manage.EdbClassifyItems, 0)
			nodeAll = append(nodeAll, v)
		}
	}
	if len(nodeAll) > 0 {
		//根据sort值排序
		sortList = nodeAll
		sort.Sort(sortList)
	}

	language := `CN`
	// 指标显示的语言
	{
		configDetail, _ := system.GetConfigDetailByCode(this.SysUser.AdminId, system.EdbLanguageVar)
		if configDetail != nil {
			language = configDetail.ConfigValue
		} else {
			configDetail, _ = system.GetDefaultConfigDetailByCode(system.EdbLanguageVar)
			if configDetail != nil {
				language = configDetail.ConfigValue
			}
		}
	}

	resp := new(data_manage.EdbClassifyListResp)
	resp.AllNodes = sortList
	resp.Language = language
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// WindEdbInfoList
// @Title wind指标列表接口
// @Description wind指标列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Param   ClassifyId   query   int  true       "分类id"
// @Success 200 {object} response.EdbInfoChartListResp
// @router /wind/index [get]
func (this *EdbInfoController) WindEdbInfoList() {
	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"
		br.Ret = 408
		return
	}

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

	// wind基础指标
	var condition string
	var pars []interface{}
	condition += ` AND edb_info_type = ? AND source =? AND edb_type=?`
	pars = append(pars, 0, utils.DATA_SOURCE_WIND, 1)

	// 分类筛选
	classifyId, _ := this.GetInt("ClassifyId")
	edbInfoId, _ := this.GetInt("EdbInfoId")
	if classifyId > 0 {
		childClassify, e, _ := data.GetChildClassifyByClassifyId(classifyId)
		if e != nil && !utils.IsErrNoRow(e) {
			br.Msg = "获取失败"
			br.ErrMsg = "获取分类信息失败, GetEdbClassify,Err:" + e.Error()
			return
		}
		var classifyIds []int
		for _, v := range childClassify {
			classifyIds = append(classifyIds, v.ClassifyId)
		}
		condition += fmt.Sprintf(` AND classify_id IN (%s) `, utils.GetOrmInReplace(len(classifyIds)))
		pars = append(pars, classifyIds)
	}
	if edbInfoId > 0 {
		condition += ` AND edb_info_id = ?`
		pars = append(pars, edbInfoId)
	}

	// 获取当前账号的不可见指标
	obj := data_manage.EdbInfoNoPermissionAdmin{}
	confList, e := obj.GetAllListByAdminId(this.SysUser.AdminId)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取不可见指标配置数据失败,Err:" + e.Error()
		return
	}
	noPermissionEdbInfoIdList := make([]int, 0)
	for _, v := range confList {
		noPermissionEdbInfoIdList = append(noPermissionEdbInfoIdList, v.EdbInfoId)
	}
	noPermissionEdbInfoIdNum := len(noPermissionEdbInfoIdList)
	if noPermissionEdbInfoIdNum > 0 {
		condition += ` AND edb_info_id NOT IN (` + utils.GetOrmInReplace(noPermissionEdbInfoIdNum) + `) `
		pars = append(pars, noPermissionEdbInfoIdList)
	}
	list := make([]*data_manage.WindEdbInfoList, 0)
	// 获取指标信息
	dataCount, edbList, e := data_manage.GetEdbInfoFilterList(condition, pars, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取普通指标列表失败, Err:" + e.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, int(dataCount))
	if len(edbList) > 0 {
		classifyMap := make(map[int]*data_manage.EdbClassify)
		targetClassifyList := make([]*data_manage.EdbClassifyItems, 0)
		if edbInfoId > 0 && classifyId == 0 {
			classifyId = edbList[0].ClassifyId
		}
		if classifyId > 0 { // todo 当没有传入分类ID时,如何处理 同一个分类ID,顶级分类是一样的
			targetClassify, err := data_manage.GetEdbClassifyById(classifyId)
			if err != nil {
				if utils.IsErrNoRow(err) {
					br.Msg = "当前分类不存在"
					return
				}
				br.Msg = "获取失败"
				br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
				return
			}
			targetClassifyList, err = data_manage.GetEdbClassifyByRootIdLevel(targetClassify.RootId, targetClassify.ClassifyType, "")
			if err != nil && !utils.IsErrNoRow(err) {
				br.Msg = "获取失败"
				br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
				return
			}
			classifyIds := make([]int, 0)
			for _, v := range edbList {
				classifyIds = append(classifyIds, v.ClassifyId)
			}
			//查询分类信息
			classifyList, err := data_manage.GetEdbClassifyByIdList(classifyIds)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
				return
			}
			for _, v := range classifyList {
				classifyMap[v.ClassifyId] = v
			}
		}
		for _, v := range edbList {
			//查询目录
			targetClassify, ok := classifyMap[v.ClassifyId]
			if !ok {
				br.Msg = "当前分类不存在"
				return
			}
			classifyList, err, errMsg := data.GetFullClassifyByRootId(targetClassify, targetClassifyList)
			if err != nil {
				br.Msg = err.Error()
				br.ErrMsg = errMsg
				return
			}
			tmp := &data_manage.WindEdbInfoList{
				EdbInfoList:  v,
				ClassifyList: classifyList,
			}
			list = append(list, tmp)
		}
	}

	resp := response.WindEdbInfoListResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}