package services

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




// 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
}