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 org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import lombok.extern.slf4j.Slf4j;

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

	@Autowired
	private ReportSapGoodsmvtService reportSapGoodsmvtService;

//	@Async("sapGoodsmvtThreadTaskExecutor") // 使用ListenerAsyncConfiguration定义的单线程执行器
//    public void sapGoodsmvtDataHandler(ReportSapGoodsmvtService reportSapGoodsmvtService,Long id) {
//		try {
//			Thread.currentThread().sleep(100);
//			
//			List<Result> results = reportSapGoodsmvtService.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);
//		}
//    }

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

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

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

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

				try {
					List<Result> results = reportSapGoodsmvtService.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();
		}
	}
}
