package services

import (
	"errors"
	"fmt"
	"eta/eta_api/models"
	"eta/eta_api/models/yb"
	"strconv"
	"strings"
)

// TagTreeItem 标签树
type TagTreeItem struct {
	ClassifyId   int        `json:"classify_id" description:"分类ID"`
	ClassifyName string     `json:"classify_name" description:"分类名称"`
	TagId        int        `json:"tag_id" description:"分类ID(用于前端组件)"`
	TagName      string     `json:"tag_name" description:"分类名称(用于前端组件)"`
	Sort         int        `json:"sort" description:"排序"`
	Tags         []*TagItem `json:"tags" description:"标签"`
}

// TagItem 标签
type TagItem struct {
	TagId             int              `json:"tag_id" description:"标签ID"`
	TagName           string           `json:"tag_name" description:"标签名称"`
	Sort              int              `json:"sort" description:"排序"`
	ClassifyId        int              `json:"classify_id" description:"分类ID"`
	ChartPermissionId int              `json:"chart_permission_id" description:"品种权限ID"`
	PriceDrivenState  int              `json:"price_driven_state" description:"价格驱动状态：0-关闭 1-开启"`
	ResearcherList    []*TagResearcher `json:"researcher_list" description:"研究员列表"`
}

// TagResearcher 研究员信息
type TagResearcher struct {
	AdminId     int    `json:"admin_id"`
	AdminName   string `json:"admin_name"`
	AllowSelect bool   `json:"allow_select" description:"是否允许选中"`
}

// GetTagTree 获取标签树
func GetTagTree(hasResearcher, include, questionId int) (respList []*TagTreeItem, err error) {
	respList = make([]*TagTreeItem, 0)
	var hasForbiddenTag bool
	if include == 1 { //如果包含被禁用的研究员，也要包含状态被禁用的分类
		hasForbiddenTag = true
	}
	// 获取标签分类
	classifyList, e := models.GetEnableVarietyClassifyList(hasForbiddenTag)
	if e != nil {
		err = errors.New("获取标签分类列表失败, Err: " + e.Error())
		return
	}
	classifyLen := len(classifyList)
	if classifyLen == 0 {
		return
	}

	tagList, e := models.GetEnableVarietyTagList(hasForbiddenTag)
	if e != nil {
		err = errors.New("获取标签列表失败, Err: " + e.Error())
		return
	}
	// 标签研究员组
	var relationList []*models.ResearchVarietyTagRelationItem
	if hasResearcher == 1 {
		relationList, e = models.GetResearchVarietyTagRelationList(include)
		if e != nil {
			err = errors.New("获取研究员标签关系失败, Err:" + e.Error())
			return
		}
	}

	// 价格驱动标签
	priceTagList, e := yb.GetPriceDrivenTagList()
	if e != nil {
		err = errors.New("获取价格驱动标签列表失败, Err:" + e.Error())
		return
	}
	priceTagLen := len(priceTagList)
	priceTagMap := make(map[int]int, 0)
	for i := 0; i < priceTagLen; i++ {
		priceTagMap[priceTagList[i].VarietyTagId] = priceTagList[i].State
	}

	// 问答社区-研究员是否允许被二次选中
	processMap := make(map[string]bool)
	if questionId > 0 {
		processList, e := yb.GetCommunityQuestionProcessItemList(questionId)
		if e != nil {
			err = errors.New("获取问答流程列表失败, Err:" + e.Error())
			return
		}
		for i := range processList {
			k := fmt.Sprintf("%d-%d", processList[i].VarietyTagId, processList[i].ReplierAdminId)
			processMap[k] = true
		}
	}

	// 标签成员、价格驱动状态
	tagsArr := make([]*TagItem, 0)
	tagLen := len(tagList)
	for i := 0; i < tagLen; i++ {
		item := tagList[i]
		// 价格驱动
		priceState := priceTagMap[item.VarietyTagId]
		tmp := &TagItem{
			TagId:             item.VarietyTagId,
			TagName:           item.TagName,
			Sort:              item.Sort,
			ClassifyId:        item.VarietyClassifyId,
			ChartPermissionId: item.ChartPermissionId,
			PriceDrivenState:  priceState,
		}
		members := make([]*TagResearcher, 0)
		if hasResearcher == 1 {
			for _, r := range relationList {
				if item.VarietyTagId == r.VarietyTagId {
					k := fmt.Sprintf("%d-%d", item.VarietyTagId, r.AdminId)
					as := true
					if processMap[k] {
						as = false
					}
					members = append(members, &TagResearcher{
						AdminId:     r.AdminId,
						AdminName:   r.AdminName,
						AllowSelect: as,
					})
				}
			}
			if len(members) > 0 {
				tmp.ResearcherList = members
				tagsArr = append(tagsArr, tmp)
			}
		} else {
			tagsArr = append(tagsArr, tmp)
		}
	}
	// 分类标签
	for i := 0; i < classifyLen; i++ {
		classifyItem := new(TagTreeItem)
		classifyItem.ClassifyId = classifyList[i].VarietyClassifyId
		classifyItem.ClassifyName = classifyList[i].ClassifyName
		classifyItem.TagId = classifyList[i].VarietyClassifyId
		classifyItem.TagName = classifyList[i].ClassifyName
		classifyItem.Sort = classifyList[i].Sort
		classifyItem.Tags = make([]*TagItem, 0)
		for _, t := range tagsArr {
			if classifyItem.ClassifyId == t.ClassifyId {
				classifyItem.Tags = append(classifyItem.Tags, t)
			}
		}
		if hasResearcher == 1 {
			if len(classifyItem.Tags) > 0 {
				respList = append(respList, classifyItem)
			}
		} else {
			respList = append(respList, classifyItem)
		}
	}
	return
}

// UpdateResearcherTagGroup 更新研究员标签分组
func UpdateResearcherTagGroup(adminId int, groupIds string) (err error) {
	if adminId == 0 {
		return
	}
	items := make([]*models.ResearchVarietyTagRelation, 0)
	groupIdArr := strings.Split(groupIds, ",")
	if groupIds != "" {
		for _, v := range groupIdArr {
			groupId, e := strconv.Atoi(v)
			if e != nil {
				err = errors.New("分组ID有误")
				return
			}
			items = append(items, &models.ResearchVarietyTagRelation{
				VarietyTagId: groupId,
				AdminId:      adminId,
			})
		}
	}
	if e := models.UpdateAdminVarietyTagRelation(adminId, items); e != nil {
		err = errors.New("更新研究员标签分组失败, Err:" + e.Error())
	}
	return
}
