package com.icomsys.main_vm.db.jpa.repo.system.dsl;


import com.icomsys.main_vm.biz.common.system.vo.SystemIcsCustInfoReq;
import com.icomsys.main_vm.biz.common.system.vo.SystemIcsCustInfoRes;
import com.icomsys.main_vm.db.jpa.entity.system.QTbIcsCustInfo;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;

@Aspect
@Slf4j
@RequiredArgsConstructor
public class TbIcsCustInfoRepoDslImpl implements TbIcsCustInfoRepoDsl {
    private final JPAQueryFactory queryFactory;
    private QTbIcsCustInfo qTbIcsCustInfo = QTbIcsCustInfo.tbIcsCustInfo;

    @Override
    public QueryResults<SystemIcsCustInfoRes> SelectCustInfo(SystemIcsCustInfoReq dto) {
        QueryResults<SystemIcsCustInfoRes> result =
                queryFactory.select(
                                Projections.fields(
                                        SystemIcsCustInfoRes.class,
                                        qTbIcsCustInfo.custCode,
                                        qTbIcsCustInfo.custName,
                                        qTbIcsCustInfo.custTel,
                                        qTbIcsCustInfo.custServiceMent,
                                        qTbIcsCustInfo.useYn,
                                        qTbIcsCustInfo.registId,
                                        qTbIcsCustInfo.registDate,
                                        qTbIcsCustInfo.updateId,
                                        qTbIcsCustInfo.updateDate
                                )
                        )
                        .from(qTbIcsCustInfo)
                        .where(custNameeq(dto))
                        .orderBy(qTbIcsCustInfo.registDate.desc())
                        .limit(dto.getSize())
                        .offset(dto.getSize() * dto.getPage())
                        .fetchResults();
        return result;
    }

    private BooleanExpression custNameeq(SystemIcsCustInfoReq dto){
        if (dto.getCodeText() == null || dto.getCodeText().equals("")) {
            return null;
        } else {
            return qTbIcsCustInfo.custName.upper().contains(dto.getCodeText().toUpperCase());
        }
    }

}
