package com.sifang.modules.customer.utils;

import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Queue;

@Component
public class DealQueueThread implements Runnable {

    private static DealQueueThread dealQueueThread;

    @Autowired
    JedisPool jedisPool;

    private Jedis jedis;

    private Queue<Map<String,String>> buyqueue;

    @Autowired
    SfCacheService cacheService;

    public static boolean excute = false;//线程的默认执行标志为未执行,即空闲状态

    public DealQueueThread() {

    }

    public DealQueueThread(Queue<Map<String,String>> buyqueue) {
        this.buyqueue = buyqueue;
        jedis = dealQueueThread.jedisPool.getResource();
    }

    @PostConstruct
    public void init() {
        dealQueueThread = this;
/*        dealQueueThread.buyGoodService = this.buyGoodService;
        dealQueueThread.buyOrdersService = this.buyOrdersService;*/
        dealQueueThread.jedisPool = this.jedisPool;
    }

    @Override
    public void run() {
        try {
            excute = true;//修改线程的默认执行标志为执行状态
            //开始处理请求队列中的请求,按照队列的FIFO的规则,先处理先放入到队列中的请求
            while (buyqueue != null && buyqueue.size() > 0) {
                Map<String,String> buyreq = buyqueue.peek();//取出队列中的请求
               // dealWithQueue(buyreq);//处理请求
            }
        } catch (Exception e) {
            System.out.println("DealQueueThread:"+e);
        } finally {
            excute = false;
        }
    }

    public synchronized void dealWithQueue(Map<String,String> buyreq,String reportId) {
        try {
            //为了尽量确保数据的一致性,处理之前先从redis中获取当前抢购商品的剩余数量
            String residue = cacheService.get("residue" + reportId);
            if (StringUtil.isNotBlank(residue)) {//如果有,就直接返回

                return;
            }
            //取出验收报告的数据


        } catch (Exception e) {
           // buyreq.setResponse_status(2);//异常状态
           // BaseLog.error("DealQueueThread dealWithQueue:", e);
        }
    }

}