package com.yn.bftl.thirdparty.modules.secret.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yn.bftl.common.common.util.ByxRouteUtil;
import com.yn.bftl.common.common.util.RouteUtil;
import com.yn.bftl.thirdparty.modules.chinaums.util.ByxChinaumsUtil;
import com.yn.bftl.thirdparty.modules.secret.service.RandomKeyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
@Service
public class RandomKeyServiceImpl implements RandomKeyService {

    //申请随机因子数量
    private final Integer applyCount = 100;

    // 创建一个容量为10的阻塞队列
    private final BlockingQueue<String> queue = new LinkedBlockingQueue<>(applyCount);

    private LocalDateTime markedDate = LocalDateTime.now();

    @Resource
    private ByxChinaumsUtil byxChinaumsUtil;

    public String getOneKey() {
        try {
            if (queue.size() < 1 || this.checkExpireTime()) {
                synchronized (this) {
                    if (queue.size() > 0 && !this.checkExpireTime()) {
                        return queue.take();
                    }
                    // 发送请求去获取随机因子
                    // TODO: send
                    JSONObject params = new JSONObject();
                    params.put("applyCount", applyCount);
                    JSONObject result = byxChinaumsUtil.execute(ByxRouteUtil.ROUTE_GET_RANDOM_KEY, params, JSONObject.class);
                    if (result == null) {
                        log.error("随机因子创建失败，请联系管理员");
                        throw new RuntimeException("随机因子创建失败，请联系管理员");
                    }
                    JSONArray jsonArray = result.getJSONArray("list");
                    this.addDataToQueue(jsonArray);

                    //更新markedDate
                    markedDate = LocalDateTime.now();
                    return queue.take();
                }
            }
            return queue.take();
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            throw new RuntimeException("随机因子创建失败，请联系管理员");
        }
    }

    private void addDataToQueue(JSONArray jsonArray) throws InterruptedException{
        if (jsonArray == null) {
            throw new RuntimeException("获取随机因子失败，请联系管理员");
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            String randomKey = jsonArray.getJSONObject(i).get("plugRandomKey").toString();
            queue.put(randomKey);
        }
    }

    private boolean checkExpireTime() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算两个LocalDateTime之间的Duration
        Duration duration = Duration.between(markedDate, now);
        // 24 ---- 表示24小时，文档中限制的是24小时内未验证就会失效，
        long daysBetween = duration.toHours() / 24;
        if (daysBetween >= 1) {
            return true;
        }
        return false;
    }
}
