package org.jeecg.module.custom.ocr.api.thread;


import com.google.common.collect.Sets;
import org.jeecg.module.custom.ocr.api.entity.FormRecord;
import org.jeecg.module.custom.ocr.base.constant.PrevailCloudConstant;
import org.jeecg.module.custom.ocr.dataobject.OcrPrevailCloudLog;
import org.jeecg.module.custom.ocr.service.OcrPrevailCloudLogService;

import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 任务队列，不同任务可创建不同队列
 *
 * @author hugh(shuli.yao) 1397940314@qq.com
 * @version 1.0
 * @date 2024/03/14 3:08
 */
public class TaskQueue {

    /**
     * 无量云接口数据处理 任务队列
     */
    public static LinkedBlockingQueue pictureDisposeQueue = new LinkedBlockingQueue();

    /**
     * picture图片转储到本地 任务队列
     */
    public static LinkedBlockingQueue pictureImgToLocalQueue = new LinkedBlockingQueue();

    public static volatile Set<String> resultSet = Sets.newConcurrentHashSet();

    /**
     * 无量云接口数据处理 push 队列值
     *
     * @param formRecord //三方拉取 获取到的图片对象
     * @return
     */
    public static boolean pictureDisposePushData(FormRecord formRecord, OcrPrevailCloudLogService ocrPrevailCloudLogService) {
        try {
            Long taskId = formRecord.getTaskId();

            //添加日志
            OcrPrevailCloudLog ocrPrevailCloudLog = OcrPrevailCloudLog.builder()
                    .formId(formRecord.getTaskId())
                    .responseParam(formRecord.toString())
                    .type(PrevailCloudConstant.DISPOSE_PICTURE_SOURCE)
                    .status(100)
                    .time(0)
                    .build();
            ocrPrevailCloudLogService.save(ocrPrevailCloudLog);
            resultSet.add(String.valueOf(taskId));
            pictureDisposeQueue.put(formRecord);
        } catch (InterruptedException e) {
            OcrPrevailCloudLog ocrPrevailCloudLog = OcrPrevailCloudLog.builder()
                    .formId(formRecord.getTaskId())
                    .responseParam(formRecord.toString())
                    .type(PrevailCloudConstant.DISPOSE_PICTURE_SOURCE)
                    .status(500)
                    .time(0)
                    .build();
            ocrPrevailCloudLogService.save(ocrPrevailCloudLog);
            return false;
        }
        return true;
    }

    /**
     * 图片缓存本地队列 push 队列值
     *
     * @param formRecord //图片下载对象
     * @return
     */
    public static boolean pictureImgToLocalPushData(FormRecord formRecord) {
        try {
            pictureImgToLocalQueue.put(formRecord);
        } catch (InterruptedException e) {
            return false;
        }
        return true;
    }

    /**
     * 无量云接口数据处理 拉取队列值
     *
     * @return
     */
    public static FormRecord pictureDisposePullData() {
        return (FormRecord) pictureDisposeQueue.poll();
    }

    /**
     * 无量云接口图片数据处理 拉取队列值
     *
     * @return
     */
    public static FormRecord pictureImgToLocalPullData() {
        return (FormRecord) pictureImgToLocalQueue.poll();
    }

}
