package com.sw.mes.sap.dao.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sw.mes.sap.dto.WarehouseStatisticsDto;
import com.sw.mes.utils.StringUtils;

@Repository
public class LogSapStockDaoImpl {
	@Autowired
	private EntityManager entityManager;

	// 实时对账库存页面增加物料号、批次号、库位码搜索条件，库位码和批次号可多选
	public List<Map<Object, Object>> realTimeReconciliationOfInventory(WarehouseStatisticsDto dto) {
		String sql = "SELECT * FROM sap_store_comparison";

		String where = " where 1=1";

		if (StringUtils.isNotBlank(dto.getMatnr())) {
			where = where + " and `料号` like '%" + dto.getMatnr() + "%'";
		}

		if (dto.getLgorts().size() > 0) {
			where = where + " and `库位` in (:lgorts)";
		}

		if (dto.getChargs().size() > 0) {
			where = where + " and `批次` in (:chargs)";
		}

		StringBuffer bf = new StringBuffer(sql);

		bf.append(where);
		Query query = entityManager.createNativeQuery(bf.toString());

		if (dto.getLgorts().size() > 0) {
			query.setParameter("lgorts", dto.getLgorts());
		}

		if (dto.getChargs().size() > 0) {
			query.setParameter("chargs", dto.getChargs());
		}
		
		query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List list = query.getResultList();
		return list;
	}
	
	
	public List<String> realTimeReconciliationOfInventoryLgorts() {
		String sql = "SELECT `库位` FROM sap_store_comparison group by `库位`";
		Query query = entityManager.createNativeQuery(sql);
		query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.TO_LIST);
		List list = query.getResultList();
		return list;
	}
	
	public List<String> realTimeReconciliationOfInventoryChargs() {
		String sql = "SELECT `批次` FROM sap_store_comparison group by `批次`";
		Query query = entityManager.createNativeQuery(sql);
		query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.TO_LIST);
		List list = query.getResultList();
		return list;
	}

}
