package services

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/system"
	"eta/eta_api/utils"
	"fmt"
	"time"
)

// UpdateExcelEditMark 更新表格当前更新状态
// status 枚举值 1：编辑中，0：完成编辑, 2：只做查询
func UpdateExcelEditMark(excelInfoId, nowUserId, status int, nowUserName string) (ret models.MarkReportResp, err error) {
	//更新标记key
	key := fmt.Sprint(`crm:excel:edit:`, excelInfoId)
	opUserId, e := utils.Rc.RedisInt(key)
	var opUser models.MarkReportItem
	if e != nil {
		opUserInfoStr, tErr := utils.Rc.RedisString(key)
		if tErr == nil {
			tErr = json.Unmarshal([]byte(opUserInfoStr), &opUser)
			if tErr == nil {
				opUserId = opUser.AdminId
			}
		}
	}
	if opUserId > 0 && opUserId != nowUserId {
		editor := opUser.Editor
		if editor == "" {
			//查询账号的用户姓名
			otherInfo, e := system.GetSysAdminById(opUserId)
			if e != nil {
				err = fmt.Errorf("查询其他编辑者信息失败")
				return
			}
			editor = otherInfo.RealName
		}

		ret.Status = 1
		ret.Msg = fmt.Sprintf("当前%s正在编辑中", editor)
		ret.Editor = editor
		return
	}
	if status == 1 {
		nowUser := &models.MarkReportItem{AdminId: nowUserId, Editor: nowUserName}
		bt, e := json.Marshal(nowUser)
		if e != nil {
			err = fmt.Errorf("格式化编辑者信息失败")
			return
		}
		if opUserId > 0 {
			utils.Rc.Do("SETEX", key, int64(300), string(bt)) //3分钟缓存
		} else {
			utils.Rc.SetNX(key, string(bt), time.Second*60*3) //3分钟缓存
		}
	} else if status == 0 {
		//清除编辑缓存
		_ = utils.Rc.Delete(key)
	}
	return
}

