package services

import (
	"encoding/json"
	"eta_gn/eta_api/models/bi_dashboard"
	"eta_gn/eta_api/models/knowledge"
	"eta_gn/eta_api/utils"
	"fmt"
	"strconv"
	"time"

	"github.com/go-redis/redis/v8"
)

func SaveBiDashboardKnowledgeResource(dashboardId, adminId int) (msg string, err error) {
	ids, err := bi_dashboard.GetBiDashboardDetailIdByBidashboardIdAndType(dashboardId, 3)
	if err != nil {
		return
	}
	if len(ids) == 0 {
		return
	}

	data, er := utils.Rc.RedisBytes(utils.CACHE_KEY_BI_DASHBOARD_PREPARE_RESOURCE + strconv.Itoa(adminId))
	req := new(knowledge.BiDashboardResourceAddReq)
	if er != nil {
		if er == redis.Nil {
			msg = "暂无知识库"
			err = nil
			return
		}
		msg = "知识资源库添加失败"
		return
	}
	if err = json.Unmarshal(data, &req); err != nil {
		msg = "知识资源库添加失败"
	}
	defer func() {
		if err == nil {
			utils.Rc.Delete(utils.CACHE_KEY_BI_DASHBOARD_PREPARE_RESOURCE + strconv.Itoa(adminId))
		}
	}()
	insertMapping := make([]*knowledge.KnowledgeResourceBiDashboardDetail, 0, len(req.KnowledgeResourceList))
	for _, v := range req.KnowledgeResourceList {
		tmp := new(knowledge.KnowledgeResourceBiDashboardDetail)
		tmp.BiDashboardDetailId = ids[0]
		tmp.KnowledgeResourceId = v.KnowledgeResourceId
		tmp.KnowledgeResourceType = 3
		tmp.CreateTime = time.Now()
		insertMapping = append(insertMapping, tmp)
	}
	obj := new(knowledge.KnowledgeResourceBiDashboardDetail)
	err = obj.BatchAdd(insertMapping)
	if err != nil {
		msg = "知识资源库添加失败"
	}
	return
}

// UpdateBiDashboardEditing 更新看板编辑状态
func UpdateBiDashboardEditing(boardId, status, userId int, userName string) (ret bi_dashboard.BiDashboardEditingCache, err error) {
	if boardId <= 0 {
		return
	}
	cacheKey := ""
	cacheKey = fmt.Sprint(utils.CACHE_BI_DASHBOARD_EDITING, boardId)

	// 完成编辑
	if status == 2 {
		_ = utils.Rc.Delete(cacheKey)
		return
	}

	// 读取缓存中的结果
	var editor bi_dashboard.BiDashboardEditingCache
	strCache, _ := utils.Rc.RedisString(cacheKey)
	fmt.Println(strCache)
	if strCache != "" {
		e := json.Unmarshal([]byte(strCache), &editor)
		if e != nil {
			err = fmt.Errorf("解析缓存内容失败: %s", e.Error())
			return
		}
	}

	// 标记编辑中
	if status == 1 {
		// 无人编辑, 写入缓存
		if !editor.IsEditing {
			ret.IsEditing = true
			ret.AdminId = userId
			ret.Editor = userName
			ret.Tips = fmt.Sprintf("当前%s正在编辑看板", userName)
			b, _ := json.Marshal(ret)
			utils.Rc.SetNX(cacheKey, string(b), 3*time.Minute)
			return
		}

		// 有人编辑
		if editor.IsEditing {
			// 编辑用户与当前用户不一致, 返回编辑用户, 一致则更新缓存
			if userId == editor.AdminId {
				b, _ := json.Marshal(editor)
				utils.Rc.Do("SETEX", cacheKey, int64(180), string(b))
			}
			ret = editor
			return
		}
	} else {
		// 默认查询
		ret = editor
	}
	return
}