package com.ruoyi.system.wechatUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.wechat.AccessTokenUtils;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

@Slf4j
public class UserQueue {

    //存放用户的openid的阻塞队列
    public static final BlockingDeque<String> ATTENTIONQUEUE = new LinkedBlockingDeque<>();
    //取关用户的openid的阻塞队列
    public static final BlockingDeque<String> CHECKOFFQUEUE = new LinkedBlockingDeque<>();
    //监听阻塞队列的线程数量
    private static final int THREAD_COUNT = 10;
    //监听取关阻塞队列的线程数量
    private static final int CHECKOFF_COUNT = 5;
    //获取用户信息的接口地址（通过UID机制）
    public static String userInfoUrl;
    //数据库层组件
    public static SysUserServiceImpl sysUserService;

    /**
     * 监听阻塞队列，异步执行任务
     */
    public static void listen() {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        // 监听新增用户
        for (int i = 0; i < THREAD_COUNT; i++) {
            final int index = i;
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            //从队列拉取数据
                            String openId = ATTENTIONQUEUE.take();
                            //access_token
                            String accessToken = AccessTokenUtils.getToken();
                            //声明客户端
                            OkHttpClient client = new OkHttpClient();
                            //构建Request
                            Request request = new Request.Builder().url(userInfoUrl + "?access_token=" + accessToken + "&openid=" + openId +
                                    "&lang=zh_CN").build();
                            Response response = client.newCall(request).execute();
                            //如果请求成功，解析数据
                            if (response.isSuccessful()) {
                                String body = response.body().string();
                                //得到一个JSON对象
                                JSONObject object = JSON.parseObject(body);
                                System.out.println("获取公众号唯数据：" + object.toString());
                                //声明系统用户
                                SysUser sysUser = new SysUser();
                                sysUser.setOpenId(object.getString("openid"));
                                sysUser.setUnionId(object.getString("unionid"));
                                sysUser.setImgSrc(object.getString("headimgurl"));
                                //信息入库
                                sysUserService.attention(sysUser);
                            }
                        }
                    } catch (Exception e) {
                        log.error("异步处理业务时失败..." + e);
                    }
                }
            });
        }
        ExecutorService checkOffThreadExecutor = Executors.newSingleThreadExecutor();
        // 监听取关用户
        for (int f = 0; f < CHECKOFF_COUNT; f++) {
            final int index = f;
            checkOffThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            //从队列拉取数据
                            String openId = CHECKOFFQUEUE.take();
                            //access_token
                            String accessToken = AccessTokenUtils.getToken();
                            //声明客户端
                            OkHttpClient client = new OkHttpClient();
                            //构建Request
                            Request request = new Request.Builder().url(userInfoUrl + "?access_token=" + accessToken + "&openid=" + openId +
                                    "&lang=zh_CN").build();
                            Response response = client.newCall(request).execute();
                            //如果请求成功，解析数据
                            if (response.isSuccessful()) {
                                String body = response.body().string();
                                //得到一个JSON对象
                                JSONObject object = JSON.parseObject(body);
                                //声明系统用户
                                SysUser user = new SysUser();
                                user.setUnionId(object.getString("unionid"));
                                //信息入库
                                sysUserService.unsubscribe(user);
                            }
                        }
                    } catch (Exception e) {
                        log.error("异步处理业务时失败..." + e);
                    }
                }
            });
        }
        System.out.println("开始监听。。。");
    }
}