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

import com.eactive.apim.portal.approval.entity.Approval;
import com.eactive.apim.portal.approval.entity.ApprovalStatusUserType;
import com.eactive.apim.portal.approval.entity.ApprovalType;
import com.eactive.apim.portal.approval.entity.QApproval;
import com.eactive.apim.portal.approval.repository.ApprovalRepository;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.BooleanBuilder;
import lombok.RequiredArgsConstructor;
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;

@Service(value = "approvalService")
@Transactional(transactionManager = "transactionManagerForEMS")
@RequiredArgsConstructor
public class ApprovalService extends AbstractEMSDataSerivce<Approval, String, ApprovalRepository> {

    public Page<Approval> findAll(Pageable pageable, PortalApprovalUISearch portalApprovalUISearch) {
        QApproval qApproval = QApproval.approval;

        BooleanBuilder predicate = new BooleanBuilder();

        if(StringUtils.isNotEmpty(portalApprovalUISearch.getSearchApprovalType())) {
            predicate.and(qApproval.approvalType.eq(ApprovalType.valueOf(portalApprovalUISearch.getSearchApprovalType())));
        }

        if(StringUtils.isNotEmpty(portalApprovalUISearch.getSearchApprovalStatus())) {
            predicate.and(qApproval.approvalStatus.eq(
                    ApprovalStatusUserType.createState(portalApprovalUISearch.getSearchApprovalStatus())
            ));
        }

        if(StringUtils.isNotEmpty(portalApprovalUISearch.getSearchApprovalSubject())) {
            predicate.and(qApproval.approvalSubject.containsIgnoreCase(portalApprovalUISearch.getSearchApprovalSubject()));
        }

        return repository.findAll(predicate, pageable);
    }

    public long countByRequesterId(String userId) {
        return getJPAQueryFactory().selectFrom(QApproval.approval)
                .where(QApproval.approval.requester.id.eq(userId))
                .fetchCount();
    }
}
