package com.shanghaichengdi.ghjgitem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.shanghaichengdi.ghjgitem.cache.CrudService;
import com.shanghaichengdi.ghjgitem.constant.Constants;
import com.shanghaichengdi.ghjgitem.domain.SysDatashareServiceNew;
import com.shanghaichengdi.ghjgitem.mapper.SysDatashareAuthNewMapper;
import com.shanghaichengdi.ghjgitem.mapper.SysDatashareServiceNewMapper;
import com.shanghaichengdi.ghjgitem.service.RedisService;
import com.shanghaichengdi.ghjgitem.service.SysDatashareServiceNewService;
import com.shanghaichengdi.ghjgitem.vo.FrequencyInfoVo;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 14390
 * @description 针对表【SYS_DATASHARE_SERVICE_NEW】的数据库操作Service实现
 * @createDate 2024-05-27 16:54:24
 */
@Service
@Slf4j
public class SysDatashareServiceNewServiceImpl extends CrudService<SysDatashareServiceNew>
    implements SysDatashareServiceNewService {

  @Resource
  private SysDatashareAuthNewMapper datashareAuthNewMapper;

  @Resource
  private SysDatashareServiceNewServiceImpl datashareServiceNewService;
  @Resource
  private RedisService redisService;

  String redisKeyDir = Constants.FREQUENCY_LIMIT + Constants.SPLIT;
  @Autowired
  private SysDatashareServiceNewMapper sysDatashareServiceNewMapper;


  @Override
  public void initCacheAuthService() {
    List<FrequencyInfoVo> infoVoList = datashareAuthNewMapper.selectAllFrequencyInfo();
    log.info("初始化的接口限制频率为:{}", infoVoList);
    infoVoList.forEach(x -> {
      redisService.setStringCache(redisKeyDir, x.getUserAndUrl(), JSONObject.toJSONString(x));
    });
  }

  @Override
  public FrequencyInfoVo getFrequencyInfoFromCache(String client, String url) {
    String value = redisService.getValue(redisKeyDir + client + Constants.SPLIT + url);
    return JSONObject.parseObject(value, FrequencyInfoVo.class);
  }

  @Override
  public void setNewLastRequestTime(FrequencyInfoVo frequencyInfoVo) {
    String redisKey = redisKeyDir + frequencyInfoVo.getUserAndUrl();
    redisService.setStringCache(redisKey, JSONObject.toJSONString(frequencyInfoVo));
  }

  @Override
  public List<SysDatashareServiceNew> list(Wrapper<SysDatashareServiceNew> queryWrapper) {
    return sysDatashareServiceNewMapper.selectList(queryWrapper);
  }

  @Override
  public void refreshFrequency(List<String> clientList) {
    List<FrequencyInfoVo> infoVoList = datashareAuthNewMapper.selectFrequencyInfoByClient(clientList);
    clientList.forEach(x -> {
      redisService.deleteKeys(redisKeyDir + x);
    });
    infoVoList.forEach(x -> {
      redisService.setStringCache(redisKeyDir, x.getUserAndUrl(), JSONObject.toJSONString(x));
    });
  }
}




