package task

import (
	"context"
	"go.uber.org/zap"
	"log-server/global"
	"log-server/model/rentComputer"
)

type ServiceRegularTask struct {
}

const OnlinePcCode = "Online:PcCode"

func (s *ServiceRegularTask) OnlinePcCodeUpdateCache() {
	ctx := context.Background()
	isNull, err := global.GVA_REDIS.Exists(ctx, OnlinePcCode).Result()
	mps := map[string]string{}
	if isNull != 0 {
		mps, err = global.GVA_REDIS.HGetAll(ctx, OnlinePcCode).Result()
		if err != nil {
			global.GVA_LOG.Error("OnlinePcCodeUpdateCache获取表失败", zap.Error(err))
			return
		}
	}
	var computers []*rentComputer.RentComputer
	err = global.GVA_DB.Where("is_off_shelf = ?", 0).Find(&computers).Error
	if err != nil {
		global.GVA_LOG.Error("OnlinePcCodeUpdateCache获取表失败", zap.Error(err))
		return
	}
	if len(computers) == 0 {
		return
	}
	var mp = map[string]string{}
	for _, pc := range computers {
		mp[pc.PcNum] = pc.DirectorName
		if _, ok := mps[pc.PcNum]; ok {
			delete(mps, pc.PcNum)
		}
	}
	err = global.GVA_REDIS.HSet(ctx, OnlinePcCode, mp).Err()
	if err != nil {
		global.GVA_LOG.Error("OnlinePcCodeUpdateCache更新缓存失败", zap.Error(err))
		return
	}
	if mps != nil {
		for code, _ := range mps {
			global.GVA_REDIS.HDel(ctx, OnlinePcCode, code)
		}
	}
	return
}
