package com.eactive.eai.rms.data.entity.onl.apim.portalnotice;

import com.eactive.apim.portal.portalNotice.entity.PortalNotice;
import com.eactive.apim.portal.portalNotice.entity.QPortalNotice;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.List;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalNoticeService extends AbstractEMSDataSerivce<PortalNotice, String, PortalNoticeRepository> {

	public void deleteByIds(List<String> ids) {
		repository.deleteAllById(ids);
	}

	public Page<PortalNotice> findAll(Pageable pageable, PortalNoticeUISearch portalNoticeUISearch) {
		QPortalNotice qPortalNotice = QPortalNotice.portalNotice;

		BooleanBuilder predicate = new BooleanBuilder();

		if (StringUtils.isNotBlank(portalNoticeUISearch.getSearchNoticeType())) {
			predicate.and(qPortalNotice.noticeType.eq(portalNoticeUISearch.getSearchNoticeType()));
		}
		
		if (StringUtils.isNotBlank(portalNoticeUISearch.getSearchUseYn())) {
			predicate.and(qPortalNotice.useYn.eq(portalNoticeUISearch.getSearchUseYn()));
		}

		if (StringUtils.isNotBlank(portalNoticeUISearch.getSearchSubjectDetail())) {
			predicate.and(qPortalNotice.noticeSubject.containsIgnoreCase(portalNoticeUISearch.getSearchSubjectDetail())
					.or(qPortalNotice.noticeDetail.containsIgnoreCase(portalNoticeUISearch.getSearchSubjectDetail())));
		}

		//return repository.findAll(predicate, pageable);
		
		Sort fixYnFirst = Sort.by(Sort.Direction.DESC, "fixYn");
		Sort combinedSort = fixYnFirst.and(pageable.getSort());
		Pageable fixedPageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), combinedSort);
		return repository.findAll(predicate, fixedPageable);
	}

}