package english_report

import (
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/utils"
	"fmt"
	"strings"
)

// EnPermissionController 英文权限
type EnPermissionController struct {
	controllers.BaseAuthController
}

// List
// @Title 品种列表
// @Description 品种列表
// @Param   Keyword  query  string  false  "关键词"
// @Param   ReportId  query  int  false  "报告ID-用于邮件推送时过滤掉无权限的品种"
// @Param   VideoId  query  int  false  "路演视频ID-用于邮件推送时过滤掉无权限的品种"
// @Success 200 Ret=200 操作成功
// @router /list [get]
func (this *EnPermissionController) List() {
	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
	}
	keyword := this.GetString("Keyword", "")
	keyword = strings.TrimSpace(keyword)

	// 禁用指定报告、指定路演无权限的品种
	reportId, _ := this.GetInt("ReportId", 0)
	videoId, _ := this.GetInt("VideoId", 0)
	limitIds := make([]int, 0)
	if reportId > 0 {
		ps, e := models.GetEnPermissionIdsByEnglishReportId(reportId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取报告权限品种失败, Err: " + e.Error()
			return
		}
		limitIds = ps
	}
	if videoId > 0 {
		ps, e := models.GetEnPermissionIdsByEnglishVideoId(videoId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取视频权限品种失败, Err: " + e.Error()
			return
		}
		limitIds = ps
	}

	cond := ``
	pars := make([]interface{}, 0)
	if keyword != "" {
		k := fmt.Sprint("%", keyword, "%")
		cond += fmt.Sprintf(` AND %s LIKE ?`, models.EnPermissionColumns.EnPermissionName)
		pars = append(pars, k)
	}
	list, e := models.GetEnPermissionUnionList(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取品种Union列表失败, Err: " + e.Error()
		return
	}

	// 品种树
	resp := make([]*models.EnPermissionItem, 0)
	childMap := make(map[int][]*models.EnPermissionItem)
	for _, v := range list {
		t := new(models.EnPermissionItem)
		t.EnPermissionId = v.EnPermissionId
		t.EnPermissionName = v.EnPermissionName
		t.CnPermissionName = v.CnPermissionName
		t.ParentId = v.ParentId
		t.Sort = v.Sort
		t.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		t.Child = make([]*models.EnPermissionItem, 0)
		if v.ParentId == 0 {
			resp = append(resp, t)
			continue
		}
		if v.ParentId > 0 {
			if childMap[v.ParentId] == nil {
				childMap[v.ParentId] = make([]*models.EnPermissionItem, 0)
			}
			// 无权限则隐藏
			if (reportId > 0 || videoId > 0) && !utils.InArrayByInt(limitIds, t.EnPermissionId) {
				continue
			}
			childMap[v.ParentId] = append(childMap[v.ParentId], t)
		}
	}
	for _, r := range resp {
		r.Child = childMap[r.EnPermissionId]
	}

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