package com.eactive.eai.rms.data.entity.onl.inbound.error;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.entity.onl.inbound.error.InboundErrorInfo;
import com.eactive.eai.data.entity.onl.inbound.error.QInboundErrorInfo;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.jpa.impl.JPAQuery;

@Service
@Transactional
public class InboundErrorInfoService extends AbstractDataService<InboundErrorInfo, String, InboundErrorInfoRepository> {

	public Page<InboundErrorInfo> findAll(Pageable pageable, InboundErrorInfoSearch inboundErrorInfoSearch) {
		QInboundErrorInfo qInboundErrorInfo = QInboundErrorInfo.inboundErrorInfo;

		JPAQuery<?> query = getJPAQueryFactory().from(qInboundErrorInfo);

		if (StringUtils.isNotBlank(inboundErrorInfoSearch.getSearchEaiSvcSerNo())) {
			query.where(qInboundErrorInfo.eaisvcserno.equalsIgnoreCase(inboundErrorInfoSearch.getSearchEaiSvcSerNo()));
		}

		if (StringUtils.isNotBlank(inboundErrorInfoSearch.getSearchAdptrBzwkGroupName())) {
			query
					.where(qInboundErrorInfo.adptrbzwkgroupname
							.equalsIgnoreCase(inboundErrorInfoSearch.getSearchAdptrBzwkGroupName()));
		}

		if (StringUtils.isNotBlank(inboundErrorInfoSearch.getSearchEaiErrCd())) {
			query.where(qInboundErrorInfo.eaierrcd.equalsIgnoreCase(inboundErrorInfoSearch.getSearchEaiErrCd()));
		}

		if (StringUtils.isNotBlank(inboundErrorInfoSearch.getSearchEaiSevrInstncName())) {
			query
					.where(qInboundErrorInfo.eaisevrinstncname
							.equalsIgnoreCase(inboundErrorInfoSearch.getSearchEaiSevrInstncName()));
		}

		if (StringUtils.isNotBlank(inboundErrorInfoSearch.getSearchEndDate())) {
			query
					.where(qInboundErrorInfo.erroccurhms
							.between(inboundErrorInfoSearch.getSearchStartDate(),
									inboundErrorInfoSearch.getSearchEndDate()));
		}

		if (StringUtils.isNotBlank(inboundErrorInfoSearch.getSearchEaiSvcName())) {
			query.where(qInboundErrorInfo.eaisvcname.equalsIgnoreCase(inboundErrorInfoSearch.getSearchEaiSvcName()));
		}

		if (StringUtils.isNotBlank(inboundErrorInfoSearch.getSearchEaiErrDstcd())) {
			query.where(qInboundErrorInfo.eaierrdstcd.equalsIgnoreCase(inboundErrorInfoSearch.getSearchEaiErrDstcd()));
		}
		long totalCount = query.select(qInboundErrorInfo.count()).fetchOne();

		List<InboundErrorInfo> list = query
				.select(qInboundErrorInfo)
				.orderBy(qInboundErrorInfo.erroccurhms.desc())
				.fetch();

		return new PageImpl<>(list, pageable, totalCount);

	}
}
