package controllers

import (
	"encoding/json"
	"errors"
	"eta/eta_api/models"
	"eta/eta_api/models/bi_dashboard"
	"eta/eta_api/models/system"
	"eta/eta_api/services"
	"eta/eta_api/utils"
	"fmt"
	"strconv"
	"strings"
	"time"
)

type BIDaShboardController struct {
	BaseAuthController
}

// GroupList
// @Title 获取我的列表
// @Description 获取我的列表接口
// @Success 200 {object} models.RespGroupList
// @router /my_list [get]
func (this *BIDaShboardController) MyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	// 获取我的看板列表
	privateCond := ` AND sys_admin_id = ? `
	privatePars := []interface{}{this.SysUser.AdminId}
	privateList, err := bi_dashboard.GetBiDashboardList(privateCond, privatePars)
	if err != nil {
		err = errors.New("我的看板列表查询出错:" + err.Error())
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = privateList
	return
}

// AddDashboard
// @Title 新增看板
// @Description 新增看板接口
// @Param	request	body models.AddDashboardReq true "type json string"
// @Success 200 Ret=200 新增成功
// @router /add [post]
func (this *BIDaShboardController) AddDashboard() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.AddDashboardReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.BiDashboardName == "" {
		br.Msg = "名称不能为空"
		return
	}
	nameItem, err := bi_dashboard.GetDashboardByName(req.BiDashboardName, this.SysUser.AdminId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败,Err:" + err.Error()
		return
	}
	if nameItem != nil && nameItem.BiDashboardId > 0 {
		br.Msg = "名称重复"
		return
	}

	item := &bi_dashboard.BiDashboard{
		//BiDashboardClassifyId: req.ClassifyId,
		BiDashboardName: req.BiDashboardName,
		SysAdminId:      this.SysUser.AdminId,
		SysAdminName:    this.SysUser.RealName,
		//Sort:                  0,
		CreateTime: time.Now(),
		ModifyTime: time.Now(),
		State:      1,
	}
	id, e := bi_dashboard.AddBiDashboard(item)
	if e != nil {
		err = e
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败,Err:" + e.Error()
		return
	}
	detailList := make([]*bi_dashboard.BiDashboardDetail, 0)
	for i, v := range req.List {
		item := &bi_dashboard.BiDashboardDetail{
			BiDashboardId: int(id),
			Type:          v.Type,
			UniqueCode:    v.UniqueCode,
			Sort:          i + 1,
			CreateTime:    time.Now(),
			ModifyTime:    time.Now(),
		}
		detailList = append(detailList, item)
	}
	err = bi_dashboard.AddBiDashboardDetailMulti(detailList)
	if err != nil {
		br.Msg = "新增详情失败"
		br.ErrMsg = "新增详情失败,Err:" + err.Error()
		return
	}

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

// EditPpt
// @Title 编辑看板
// @Description 编辑看板接口
// @Param	request	body bi_dashboard.EditDashboardReq true "type json string"
// @Success 200 Ret=200 编辑成功
// @router /edit [post]
func (this *BIDaShboardController) EditDashboard() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.EditDashboardReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.BiDashboardName == "" {
		br.Msg = "标题不能为空"
		return
	}
	item, err := bi_dashboard.GetDashboardById(req.BiDashboardId)
	if err != nil {
		br.Msg = "获取数据异常!"
		br.ErrMsg = "获取数据异常,Err:" + err.Error()
		return
	}
	
	// 修改
	item.BiDashboardName = req.BiDashboardName
	item.ModifyTime = time.Now()

	err = bi_dashboard.EditDashboard(item)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}

	err = bi_dashboard.DeleteBiDashboardDetail(req.BiDashboardId)
	if err != nil {
		br.Msg = "删除详情失败"
		br.ErrMsg = "删除详情失败,Err:" + err.Error()
		return
	}

	detailList := make([]*bi_dashboard.BiDashboardDetail, 0)
	for _, v := range req.List {
		item := &bi_dashboard.BiDashboardDetail{
			BiDashboardId: req.BiDashboardId,
			Type:          v.Type,
			UniqueCode:    v.UniqueCode,
			Sort:          v.Sort,
			CreateTime:    time.Now(),
			ModifyTime:    time.Now(),
		}
		detailList = append(detailList, item)
	}
	err = bi_dashboard.AddBiDashboardDetailMulti(detailList)
	if err != nil {
		br.Msg = "新增详情失败"
		br.ErrMsg = "新增详情失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}

// DeleteDashboard
// @Title 删除看板
// @Description 删除看板接口
// @Param	request	body bi_dashboard.DelDashboardReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /delete [post]
func (this *BIDaShboardController) DeleteDashboard() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.DelDashboardReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.BiDashboardId <= 0 {
		br.Msg = "参数错误"
		return
	}
	item, err := bi_dashboard.GetDashboardById(req.BiDashboardId)
	if err != nil {
		br.Msg = "获取数据异常!"
		br.ErrMsg = "获取数据异常,Err:" + err.Error()
		return
	}
	if item.SysAdminId != this.SysUser.AdminId {
		br.Msg = "无权删除"
		return
	}
	err = bi_dashboard.DelDashboard(req.BiDashboardId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}

	//如果该看板存在共享记录,则删除共享
	err = bi_dashboard.DeleteDashboardGrant(req.BiDashboardId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

// DeleteDashboard
// @Title 删除看板详情
// @Description 删除看板详情接口
// @Param	request	body bi_dashboard.DelDashboardDetailReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /detail/delete [post]
func (this *BIDaShboardController) DeleteDashboardDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.DelDashboardDetailReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.BiDashboardDetailId <= 0 {
		br.Msg = "参数错误"
		return
	}

	err = bi_dashboard.DeleteBiDashboardDetailByDetailId(req.BiDashboardDetailId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

// DetailDashboard
// @Title 获取看板详情
// @Description 获取看板详情接口
// @Param   PptId   query   int  true       "PptId"
// @Success 200 {object} models.PptV2
// @router /detail [get]
func (this *BIDaShboardController) DetailDashboard() {
	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
	}
	dashboardId, _ := this.GetInt("DashboardId")
	resp := new(bi_dashboard.DashboardDetailResp)
	dashboardItem, err := bi_dashboard.GetDashboardById(dashboardId)
	if err != nil {
		err = errors.New("我的看板列表查询出错:" + err.Error())
		br.Msg = "我的看板列表查询出错"
		br.ErrMsg = err.Error()
		return
	}

	grantInfoList, err := bi_dashboard.GetDashboardGrantInfo(dashboardId)
	if err != nil {
		br.Msg = "信息获取失败"
		br.ErrMsg = "共享信息获取失败,Err:" + err.Error()
		return
	}
	if len(grantInfoList) > 0 {
		resp.IsGrant = 1
	}

	detailList, err := bi_dashboard.GetBiDashboardDetailById(dashboardId)
	if err != nil {
		br.Msg = "详情获取失败"
		br.ErrMsg = "详情获取失败,Err:" + err.Error()
		return
	}

	editor, e := services.UpdateBiDashboardEditing(dashboardId, 0, sysUser.AdminId, sysUser.RealName)
	if e != nil {
		br.Msg = "编辑状态更新失败"
		br.ErrMsg = "编辑状态更新失败,Err:" + e.Error()
		return
	}

	resp.Editor = editor
	resp.BiDashboard = dashboardItem
	resp.List = detailList

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

// MoveDashboard
// @Title 移动看板详情
// @Description 移动看板详情接口
// @Param	request	body bi_dashboard.MoveDashboardDetailReq true "type json string"
// @Success 200 Ret=200 移动成功
// @router /detail/move [post]
func (this *BIDaShboardController) MoveDashboard() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.MoveDashboardDetailReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	if req.BiDashboardId <= 0 {
		br.Msg = "参数错误"
		return
	}
	if req.BiDashboardDetailId == req.OtherDetailId || req.BiDashboardDetailId <= 0 || req.OtherDetailId <= 0 {
		br.Msg = "看板Id有误"
		return
	}
	if req.Sort < 0 || req.OtherSort < 0 || req.Sort == req.OtherSort {
		br.Msg = "排序有误"
		return
	}

	item, err := bi_dashboard.GetDashboardById(req.BiDashboardId)
	if err != nil {
		br.Msg = "获取数据异常!"
		br.ErrMsg = "获取数据异常,Err:" + err.Error()
		return
	}

	// 判断权限
	if item.SysAdminId != this.SysUser.AdminId {
		br.Msg = `无权移动`
		return
	}

	// 修改
	detailItem := &bi_dashboard.BiDashboardDetail{
		BiDashboardDetailId: req.BiDashboardDetailId,
		Sort:                req.OtherSort,
		ModifyTime:          time.Now(),
	}
	err = bi_dashboard.EditBiDashboardDetail(detailItem)
	if err != nil {
		br.Msg = "编辑详情失败"
		br.ErrMsg = "编辑详情失败,Err:" + err.Error()
		return
	}

	otherItem := &bi_dashboard.BiDashboardDetail{
		BiDashboardDetailId: req.OtherDetailId,
		Sort:                req.Sort,
		ModifyTime:          time.Now(),
	}
	err = bi_dashboard.EditBiDashboardDetail(otherItem)
	if err != nil {
		br.Msg = "编辑详情失败"
		br.ErrMsg = "编辑详情失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}

// ShareList
// @Title 获取共享列表
// @Description 获取共享列表接口
// @Success 200 {object} models.RespGroupList
// @router /share_list [get]
func (this *BIDaShboardController) ShareList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	//myPptList := make([]*bi_dashboard.BiDashboard, 0)
	//otherPptList := make([]*bi_dashboard.BiDashboard, 0)
	grantList := bi_dashboard.RespGroupList{}

	// 获取我的看板列表
	ShareList, err := bi_dashboard.GetAllMyShareList(this.SysUser.AdminId)
	if err != nil {
		err = errors.New("我的看板列表查询出错:" + err.Error())
		br.ErrMsg = err.Error()
		br.Msg = "查询失败"
		return
	}
	grantList.MyList = ShareList

	//dashboardMap := make(map[int]*bi_dashboard.BiDashboard)
	adminIdList := make([]int, 0)   //需要查询的创建人admin_id列表集合
	adminIdMap := make(map[int]int) //需要查询的创建人admin_id集合,用来去重的,避免重复id
	grantDashboardList, err := bi_dashboard.GetAllGrantList(this.SysUser.AdminId)
	if err != nil {
		err = errors.New("我的看板列表查询出错:" + err.Error())
		br.ErrMsg = err.Error()
		br.Msg = "查询失败"
		return
	}

	publicAdminIdList := make([]int, 0)
	publicDashboardListMap := make(map[int][]*bi_dashboard.BiDashboard)
	for _, v := range grantDashboardList {
		publicDashboardList, ok := publicDashboardListMap[v.SysAdminId]
		if !ok {
			publicDashboardList = make([]*bi_dashboard.BiDashboard, 0)
			publicAdminIdList = append(publicAdminIdList, v.SysAdminId)
			if _, ok := adminIdMap[v.SysAdminId]; !ok {
				adminIdList = append(adminIdList, v.SysAdminId) //需要查询的创建人admin_id列表集合
				adminIdMap[v.SysAdminId] = v.SysAdminId         //需要查询的创建人admin_id集合,用来去重的,避免重复id
			}
		}

		tmp := &bi_dashboard.BiDashboard{
			BiDashboardId:   v.BiDashboardId,
			BiDashboardName: v.BiDashboardName,
			CreateTime:      v.CreateTime,
			ModifyTime:      v.ModifyTime,
			Sort:            v.Sort,
			State:           v.State,
			SysAdminId:      v.SysAdminId,
			SysAdminName:    v.SysAdminName,
		}
		publicDashboardList = append(publicDashboardList, tmp)
		publicDashboardListMap[v.SysAdminId] = publicDashboardList
	}
	// 创建人信息
	systemAdminMap := make(map[int]*system.Admin)
	systemAdminList, err := system.GetAdminListByIdList(adminIdList)
	if err != nil {
		return
	}
	for _, v := range systemAdminList {
		systemAdminMap[v.AdminId] = v
	}

	for _, v := range publicAdminIdList {
		systemAdmin, ok := systemAdminMap[v]
		if !ok {
			continue
		}

		// 看板 列表信息
		respGroupNameListItemList, ok := publicDashboardListMap[v]
		if !ok {
			respGroupNameListItemList = make([]*bi_dashboard.BiDashboard, 0)
		}

		// ppt 分组信息
		tmpRespGroupListItem := &bi_dashboard.RespOtherGroupListItem{
			GroupId:       int64(systemAdmin.AdminId),
			GroupName:     systemAdmin.RealName,
			AdminId:       systemAdmin.AdminId,
			DashboardList: respGroupNameListItemList,
		}
		grantList.OtherList = append(grantList.OtherList, tmpRespGroupListItem)
	}
	//if len(dashboradIds) > 0 {
	//	// 通过dashboradIds列表字段获取所有的看板信息
	//	dashboradList, tmpErr := bi_dashboard.GetDashboradByIds(dashboradIds)
	//	if tmpErr != nil {
	//		err = errors.New("查询dashborad详情出错:" + err.Error())
	//		br.Msg = "查询dashborad详情出错"
	//		br.ErrMsg = err.Error()
	//		return
	//	}
	//	for _, v := range dashboradList {
	//		dashboardMap[v.BiDashboardId] = v
	//	}
	//}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = grantList
	return
}

// PublicList
// @Title 获取公共列表
// @Description 获取公共列表接口
// @Success 200 {object} models.RespGroupList
// @router /public_list [get]
func (this *BIDaShboardController) PublicList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	resp := make([]*bi_dashboard.RespPublicGroupListItem, 0)
	// 获取公共看板列表
	publicCond := ` AND state = 6 `
	publicPars := make([]interface{}, 0)
	publicList, err := bi_dashboard.GetBiDashboardList(publicCond, publicPars)
	if err != nil {
		err = errors.New("我的看板列表查询出错:" + err.Error())
		return
	}

	//dashboardMap := make(map[int]*bi_dashboard.BiDashboard)
	adminIdList := make([]int, 0)   //需要查询的创建人admin_id列表集合
	adminIdMap := make(map[int]int) //需要查询的创建人admin_id集合,用来去重的,避免重复id

	publicAdminIdList := make([]int, 0)
	publicDashboardListMap := make(map[int][]*bi_dashboard.BiDashboard)
	publicDashboardClassifyIdMap := make(map[int]int)
	for _, v := range publicList {
		publicDashboardList, ok := publicDashboardListMap[v.SysAdminId]
		if !ok {
			publicDashboardList = make([]*bi_dashboard.BiDashboard, 0)
			publicAdminIdList = append(publicAdminIdList, v.SysAdminId)
			if _, ok := adminIdMap[v.SysAdminId]; !ok {
				adminIdList = append(adminIdList, v.SysAdminId) //需要查询的创建人admin_id列表集合
				adminIdMap[v.SysAdminId] = v.SysAdminId         //需要查询的创建人admin_id集合,用来去重的,避免重复id
			}
		}

		tmp := &bi_dashboard.BiDashboard{
			BiDashboardId:         v.BiDashboardId,
			BiDashboardClassifyId: v.BiDashboardClassifyId,
			BiDashboardName:       v.BiDashboardName,
			CreateTime:            v.CreateTime,
			ModifyTime:            v.ModifyTime,
			Sort:                  v.Sort,
			State:                 v.State,
			SysAdminId:            v.SysAdminId,
			SysAdminName:          v.SysAdminName,
		}
		publicDashboardList = append(publicDashboardList, tmp)
		publicDashboardListMap[v.SysAdminId] = publicDashboardList
		publicDashboardClassifyIdMap[v.BiDashboardClassifyId] = v.BiDashboardClassifyId
	}
	// 创建人信息
	systemAdminMap := make(map[int]*system.Admin)
	systemAdminList, err := system.GetAdminListByIdList(adminIdList)
	if err != nil {
		return
	}
	for _, v := range systemAdminList {
		systemAdminMap[v.AdminId] = v
	}

	for _, v := range adminIdList {
		systemAdmin, ok := systemAdminMap[v]
		if !ok {
			continue
		}

		// 看板 列表信息
		respGroupNameListItemList, ok := publicDashboardListMap[v]
		if !ok {
			respGroupNameListItemList = make([]*bi_dashboard.BiDashboard, 0)
		}

		// ppt 分组信息
		tmpRespGroupListItem := &bi_dashboard.RespPublicGroupListItem{
			GroupId:       int64(systemAdmin.AdminId),
			GroupName:     systemAdmin.RealName,
			AdminId:       systemAdmin.AdminId,
			DashboardList: make([]*bi_dashboard.BiDashboard, 0),
		}

		for _, vv := range respGroupNameListItemList {
			tmpRespGroupListItem.DashboardList = append(tmpRespGroupListItem.DashboardList, vv)
		}
		resp = append(resp, tmpRespGroupListItem)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = resp
	return
}

// AddDashboardClassify
// @Title 新增看板分类
// @Description 新增看板分类接口
// @Param	request	body bi_dashboard.AddDashboardClassifyReq true "type json string"
// @Success 200 Ret=200 新增成功
// @router /classify/add [post]
func (this *BIDaShboardController) AddDashboardClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.AddDashboardClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.ClassifyName == "" {
		br.Msg = "名称不能为空"
		return
	}
	maxSort, err := bi_dashboard.GetBiDashboardClassifyMaxSort()
	if err != nil {
		br.Msg = "获取最大排序值失败"
		br.ErrMsg = "获取最大排序值失败,Err:" + err.Error()
		return
	}
	count, err := bi_dashboard.GetBiDashboardClassifyByName(req.ClassifyName)
	if err != nil {
		br.Msg = "获取分类名称失败"
		br.ErrMsg = "获取分类名称失败,Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "分类名称已存在"
		return
	}

	item := &bi_dashboard.BiDashboardClassify{
		BiDashboardClassifyName: req.ClassifyName,
		Sort:                    maxSort + 1,
		CreateTime:              time.Now(),
		ModifyTime:              time.Now(),
	}
	_, e := bi_dashboard.AddBiDashboardClassify(item)
	if e != nil {
		err = e
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败,Err:" + e.Error()
		return
	}

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

// EditDashboardClassify
// @Title 编辑看板分类
// @Description 编辑看板分类接口
// @Param	request	body bi_dashboard.EditDashboardReq true "type json string"
// @Success 200 Ret=200 编辑成功
// @router /classify/edit [post]
func (this *BIDaShboardController) EditDashboardClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.EditDashboardClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.ClassifyName == "" {
		br.Msg = "标题不能为空"
		return
	}
	if req.BiDashboardClassifyId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, BiDashboardClassifyId: %d", req.BiDashboardClassifyId)
		return
	}
	item, err := bi_dashboard.GetBiDashboardClassifyById(req.BiDashboardClassifyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据异常!"
		br.ErrMsg = "获取数据异常,Err:" + err.Error()
		return
	}

	// 修改
	item.BiDashboardClassifyName = req.ClassifyName
	item.ModifyTime = time.Now()

	err = bi_dashboard.EditDashboardClassify(item)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}

// Grant
// @Title 分配看板权限
// @Description 分配看板权限接口
// @Param	request	body models.GrantPptReq true "type json string"
// @Success 200 Ret=200 分配成功
// @router /grant [post]
func (this *BIDaShboardController) Grant() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.GrantDashboardReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.AdminIdStr == "" {
		br.Msg = "参数错误"
		return
	}
	if req.BiDashboardId <= 0 {
		br.Msg = "参数错误"
		return
	}

	dashboardItem, err := bi_dashboard.GetDashboardById(req.BiDashboardId)
	if err != nil {
		err = errors.New("我的看板列表查询出错:" + err.Error())
		br.Msg = "我的看板列表查询出错"
		br.ErrMsg = err.Error()
		return
	}
	if dashboardItem.SysAdminId != this.SysUser.AdminId {
		br.Msg = "无权配置"
		return
	}

	list := make([]*bi_dashboard.BiDashboardGrant, 0)

	grantAdminIdStrList := strings.Split(req.AdminIdStr, ",")
	lenGrantAdminIdStrList := len(grantAdminIdStrList) //指定用户的人数
	for _, v := range grantAdminIdStrList {
		grantAdminId, tmpErr := strconv.Atoi(v)
		if tmpErr != nil {
			br.Msg = "参数有误"
			br.ErrMsg = fmt.Sprintf("参数有误,Err:%s", tmpErr.Error())
			return
		}

		//如果只选择了自己作为指定的人,那么就提示他报错。如果多人,那么就过滤自己
		if grantAdminId == this.SysUser.AdminId {
			if lenGrantAdminIdStrList == 1 {
				br.Msg = "不能指定自己为权限用户"
				br.ErrMsg = fmt.Sprintf("参数有误,Err:%s", tmpErr.Error())
				return
			}
			continue
		}
		tmpV := &bi_dashboard.BiDashboardGrant{
			BiDashboardId: req.BiDashboardId,
			GrantAdminId:  grantAdminId,
			CreateTime:    time.Now(),
		}
		list = append(list, tmpV)
	}

	if len(list) <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误,Err:%s", "指定用户为空")
		return
	}

	err = bi_dashboard.MultiAddDashboardGrant(req.BiDashboardId, list)
	if err != nil {
		br.Msg = "分配失败"
		br.ErrMsg = fmt.Sprintf("分配失败,Err:%s", err.Error())
		return
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "分配成功"
}

// Public
// @Title
// @Description 设置公共看板
// @Param	request	body models.GrantPptReq true "type json string"
// @Success 200 Ret=200 分配成功
// @router /public [post]
func (this *BIDaShboardController) Public() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.PublicDashboardReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	item, err := bi_dashboard.GetDashboardById(req.BiDashboardId)
	if err != nil {
		br.Msg = "获取数据异常!"
		br.ErrMsg = "获取数据异常,Err:" + err.Error()
		return
	}

	item.State = 6

	err = bi_dashboard.EditDashboard(item)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "分配成功"
}

// GroupList
// @Title 获取分类列表
// @Description 获取分类列表接口
// @Success 200 {object} models.RespGroupList
// @router /classify/list [get]
func (this *BIDaShboardController) ClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	classifyList, err := bi_dashboard.GetBiDashboardClassifyAllList()
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = classifyList
	return
}

// CancelGrant
// @Title 取消分配看板权限
// @Description 取消分配看板权限
// @Param	request	body bi_dashboard.DelDashboardReq true "type json string"
// @Success 200 Ret=200 分配成功
// @router /grant/cancel [post]
func (this *BIDaShboardController) CancelGrant() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.DelDashboardReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.BiDashboardId <= 0 {
		br.Msg = "参数错误"
		return
	}

	item, err := bi_dashboard.GetDashboardById(req.BiDashboardId)
	if err != nil {
		br.Msg = "数据不存在"
		br.ErrMsg = "数据不存在,Err:" + err.Error()
		return
	}
	if item.SysAdminId != this.SysUser.AdminId {
		br.Msg = "无权配置"
		return
	}

	// 分配
	err = bi_dashboard.DeleteDashboardGrant(req.BiDashboardId)
	if err != nil {
		br.Msg = "取消失败"
		br.ErrMsg = "取消失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "取消成功"
}

// GrantInfo
// @Title 获取分配ppt权限详情
// @Description 获取分配ppt权限详情接口
// @Param    BiDashboardId   query   int  true       "看板的id"
// @Success 200 {object} models.GrantInfoResp
// @router /grant/info [get]
func (this *BIDaShboardController) GrantInfo() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	biDashboardId, _ := this.GetInt("BiDashboardId")
	if biDashboardId <= 0 {
		br.Msg = "参数错误"
		return
	}

	item, err := bi_dashboard.GetDashboardById(biDashboardId)
	if err != nil {
		br.Msg = "数据不存在"
		br.ErrMsg = "数据不存在,Err:" + err.Error()
		return
	}
	if item.SysAdminId != this.SysUser.AdminId {
		br.Msg = "无权配置"
		return
	}

	grantInfoList, err := bi_dashboard.GetDashboardGrantInfo(biDashboardId)
	if err != nil {
		br.Msg = "信息获取失败"
		br.ErrMsg = "信息获取失败,Err:" + err.Error()
		return
	}

	if len(grantInfoList) <= 0 {
		br.Msg = "未配置"
		br.IsSendEmail = false
		br.Success = true
		br.Ret = 200
		return
	}

	var adminIdStr string

	adminIdsList := make([]string, 0)
	for _, v := range grantInfoList {
		adminIdsList = append(adminIdsList, strconv.Itoa(int(v.GrantAdminId)))
	}
	adminIdStr = strings.Join(adminIdsList, ",")

	br.Ret = 200
	br.Success = true
	br.Data = adminIdStr
	br.Msg = "查询成功"
}

// Public
// @Title
// @Description 撤销公共看板
// @Param	request	body models.GrantPptReq true "type json string"
// @Success 200 Ret=200 分配成功
// @router /public/cancel [post]
func (this *BIDaShboardController) PublicCancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.DelDashboardReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	item, err := bi_dashboard.GetDashboardById(req.BiDashboardId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据异常!"
		br.ErrMsg = "获取数据异常,Err:" + err.Error()
		return
	}

	item.State = 1

	err = bi_dashboard.EditDashboard(item)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "撤销成功"
}

// GroupList
// @Title 获取我的首页看板
// @Description 获取我的首页看板接口
// @Success 200 {object} models.RespGroupList
// @router /home_page [get]
func (this *BIDaShboardController) HomePage() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	item, err := bi_dashboard.GetBiDashboardHomePageById(this.SysUser.AdminId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "数据不存在"
		br.ErrMsg = "数据不存在,Err:" + err.Error()
		return
	}

	publicCond := ` AND state = 6 AND bi_dashboard_classify_id > 0 `
	publicPars := []interface{}{this.SysUser.AdminId}
	publicList, err := bi_dashboard.GetBiDashboardList(publicCond, publicPars)
	if err != nil {
		err = errors.New("我的看板列表查询出错:" + err.Error())
		return
	}

	if item.BiDashboardHomePageId == 0 && len(publicList) > 0 {
		item = &bi_dashboard.BiDashboardHomePage{
			AdminId:       publicList[0].SysAdminId,
			BiDashboardId: publicList[0].BiDashboardId,
			FromType:      3,
		}
	}

	if item.BiDashboardId == 0 {
		item = nil
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = item
	return
}

// GroupList
// @Title 保存我的看板首页
// @Description保存我的看板首页接口
// @Success 200 {object} models.RespGroupList
// @router /home_page/save [post]
func (this *BIDaShboardController) HomePageSave() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req bi_dashboard.SaveHomePageReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	if req.BiDashboardId <= 0 {
		br.Msg = "参数错误"
		return
	}

	item, err := bi_dashboard.GetBiDashboardHomePageById(this.SysUser.AdminId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "首页看板查询失败"
		br.ErrMsg = "首页看板查询失败,Err:" + err.Error()
		return
	}

	homePageItem := &bi_dashboard.BiDashboardHomePage{
		BiDashboardId: req.BiDashboardId,
		AdminId:       this.SysUser.AdminId,
		CreateTime:    time.Now(),
		ModifyTime:    time.Now(),
		FromType:      req.FromType,
	}

	if item.BiDashboardHomePageId > 0 {
		homePageItem.BiDashboardHomePageId = item.BiDashboardHomePageId
	}

	err = bi_dashboard.SaveBiDashboardHomePage(homePageItem)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	return
}

// Editing
// @Title 标记/查询编辑状态
// @Description 标记/查询编辑状态
// @Param	request	body models.PPTEditingReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /editing [post]
func (this *BIDaShboardController) Editing() {
	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
	}
	var req bi_dashboard.BiDashboardEditingReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.BiDashboardId <= 0 {
		br.Msg = "参数有误"
		return
	}
	if req.Status < 0 {
		br.Msg = "标记状态异常"
		return
	}

	editor, e := services.UpdateBiDashboardEditing(req.BiDashboardId, req.Status, sysUser.AdminId, sysUser.RealName)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新编辑状态失败, err: " + e.Error()
		return
	}

	br.Data = editor
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// GroupList
// @Title 获取我拥有的图库表格菜单权限
// @Description 获取我拥有的图库表格菜单权限接口
// @Success 200 {object} models.RespGroupList
// @router /chart_excel_permission [get]
func (this *BIDaShboardController) ChartExcelPermission() {
	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
	}

	roleId := sysUser.RoleId
	//roleId=1
	if roleId <= 0 {
		br.Msg = "参数错误"
		return
	}
	roleIds := strconv.Itoa(roleId)
	//查询账号绑定的其他角色
	otherRoles, err := system.GetRoleIdsByAdminId(sysUser.AdminId)
	if err != nil {
		br.Msg = "获取其他角色失败"
		br.ErrMsg = "获取其他角色失败,Err:" + err.Error()
		return
	}
	if len(otherRoles) > 0 {
		for _, v := range otherRoles {
			roleIds += "," + strconv.Itoa(v.RoleId)
		}
	}
	groupId := 0
	if utils.RunMode == "release" {
		groupId = 37
	} else {
		groupId = 61
	}
	//共享客户组下的用户
	shareSellerMap := make(map[int]bool, 0)
	subAdmins, err := system.GetAdminByGroupId(groupId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取销售失败"
		br.ErrMsg = "获取销售失败,Err:" + err.Error()
		return
	}
	for _, admin := range subAdmins {
		shareSellerMap[admin.AdminId] = true
	}

	list, err := system.GetMenuByRoleIds(roleIds)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	lenList := len(list)

	menuList := make([]*system.SysMenuSimple, 0)

	chartExcelTypes, e := models.GetBusinessConfByKey("ChartExcelType")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取商家配置失败, Err: " + e.Error()
		return
	}
	types := strings.Split(chartExcelTypes.ConfVal, ",")
	typeMap := map[string]bool{}
	for _, v := range types {
		typeMap[v] = true
	}

	for i := 0; i < lenList; i++ {
		item := list[i]
		if !typeMap[item.LevelPath] && !typeMap[item.Path] {
			continue
		}
		newItem := &system.SysMenuSimple{
			MenuId:   item.MenuId,
			ParentId: item.ParentId,
			Name:     item.Name,
			Sort:     item.Sort,
			Path:     item.Path,
			NameEn:   item.NameEn,
		}
		if item.IsLevel == 1 {
			newItem.Path = item.LevelPath
		}
		menuList = append(menuList, newItem)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = menuList
	return
}