package com.reptileclient.jlifeapp.service.impl;

import cn.hutool.core.date.DateUtil;
import com.reptileclient.jlifeapp.service.HmRequestService;
import com.reptileclient.jlifeapp.service.RetryService;
import com.reptileclient.jlifeapp.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author fuxubing
 */
@Service
public class RetryServiceImpl implements RetryService {
    private static final Logger logger = LoggerFactory.getLogger(RetryServiceImpl.class);

    @Autowired
    private HmRequestService hmRequestService;

    @Retryable(value = RestClientException.class, backoff = @Backoff(delay = 5000L, multiplier = 2))
    @Override
    public Map<String, Object> requestPost(String token, String parmJson, String url) {
        logger.info("发起远程API请求: {},请求地址:{}", DateUtil.now(), url);
        // check if current date time >=20:00 , rand   delay 1-20 seconds
        LocalDateTime now = LocalDateTime.now();
        if (now.getHour() >= 20) {
            Random random = new Random();
            int delay = random.nextInt(20) + 1;
            logger.info("当前时间大于20点，随机延迟{}秒", delay);
            try {
                Thread.sleep(delay * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        String yls="shuhe.hemaos.com/api/v1/queryData/metrics";
        if(url.contains(yls)) {
        	 if (hmRequestService.insert(yls) == 0) {
             	Map<String, Object> map=new HashMap<String, Object>();
             	map.put("success", "false");
                 logger.error("银联商交易及销售，超过当日最大请求数，请求中止");
                 return map;
             }
        }

        if (hmRequestService.insert(url) == 0) {
        	Map<String, Object> map=new HashMap<String, Object>();
        	map.put("success", "false");
            logger.error("超过当日最大请求数，请求中止");
            return map;
        }
        return HttpUtil.request(token, parmJson, url);
    }

}
