package com.sw.mes.sap.task;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.sap.entity.ReportSapMblnrQuery;
import com.sw.mes.sap.service.ReportSapMblnrQueryService;
import com.sw.mes.utils.StringUtils;

import cc.cczn.matrix.commons.tasks.queue.Task;
import cc.cczn.matrix.commons.tasks.queue.TaskProcessor;
import lombok.extern.slf4j.Slf4j;

/**
 * 物料数据同步到线边仓的梳理
 *
 * @Author：liru @Date：2024/4/10 15:15
 */
@Slf4j
@Component
public class MblnrQueryHandler implements TaskProcessor<JSONArray> {
	
	@Autowired
	private ReportSapMblnrQueryService reportSapMblnrQueryService;

	private static final Logger logger = LoggerFactory.getLogger(MblnrQueryHandler.class);
	
	private static String[] bwarts = new String[] {"311","312","531","532","101","102","261","262","201","202"};

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void process(Task<JSONArray> task) {

		List<ReportSapMblnrQuery> datas = task.getData().toJavaList(ReportSapMblnrQuery.class);
		
		List<String> bwartsList = Arrays.asList(bwarts);
		
		for (ReportSapMblnrQuery reportSapMblnrQuery : datas) {
			//过滤掉非P仓数据
			if(reportSapMblnrQuery.getLgort()==null || reportSapMblnrQuery.getLgort().equals("") || !StringUtils.left(reportSapMblnrQuery.getLgort(), 1).equals("P")) {
				continue;
			}
			
			//过滤掉非P仓数据
			if(reportSapMblnrQuery.getUmlgo()!=null && !reportSapMblnrQuery.getUmlgo().equals("") && !StringUtils.left(reportSapMblnrQuery.getUmlgo(), 1).equals("P")) {
				continue;
			}
			
			if(reportSapMblnrQuery.getBwart()==null || !bwartsList.contains(reportSapMblnrQuery.getBwart())) {
				continue;
			}
			
			ReportSapMblnrQuery target = reportSapMblnrQueryService.getByMblnr(reportSapMblnrQuery.getMblnr());
			if(target==null) {
				target = reportSapMblnrQuery;
			}else {
				BeanUtil.copyProperties(reportSapMblnrQuery, target, "id");
			}
			
			reportSapMblnrQueryService.saveOrUpdate(target);
		}
	}
}
