package com.sw.mes.sap.task;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.sap.service.ReportSapWorkinghoursService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author：liru @Date：2024/4/12 12:15
 */
@Slf4j
@Component
public class SapWorkinghoursDataAsyncService {

	@Autowired
	private ReportSapWorkinghoursService reportSapWorkinghoursService;

	@Async("sapWorkinghoursThreadTaskExecutor") // 使用ListenerAsyncConfiguration定义的单线程执行器
	public void sapWorkinghoursDataHandler() {
		while (true) {
			SapWorkinghoursQueueCache cache = SapWorkinghoursQueueCache.getInstance();

			if (cache.getCacheSize() > 0) {
				// Workinghourssmvt 记录ID
				Long id = cache.get(0);
				
				log.info("报工时内存缓存记录剩余记录数:{}", cache.getCacheSize());
				log.info("处理报工时内存缓存记录:{}", id);

				if (id == null) {
					theadSleep(1000);
					continue;
				}

				if (reportSapWorkinghoursService.get(id) == null) {
					log.error("{}缓存记录报工时异常:{}对象在数据库中查询为空,缓存记录剩余大小:{}", "executeSendWorkinghourssmvt", id,cache.getCacheSize());
					theadSleep(1000);
					continue;
				}

				try {
					List<Result> results = reportSapWorkinghoursService.sendReportWord(new Long[] { id }, "AUTO");
					for (Result result : results) {
						if (result.getCode().equals(ResultCode.FAIL.getCode())) {
							log.error("异步自动报工时失败:{}", result.getMessage());
						}
					}
				} catch (Exception e) {
					log.error("异步自动报工时异常(" + id + "):", e);
				}

				// 移除第一条不为空的缓存记录
				cache.remove(0);
			}

			theadSleep(1000);
		}
	}

	private void theadSleep(long millis) {
		try {
			Thread.currentThread().sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
