package com.zcloud.primeport.command.query;

import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.primeport.command.convertor.ClosedAreaCarApplyCoConvertor;
import com.zcloud.primeport.dto.ClosedAreaCarApplyPageQry;
import com.zcloud.primeport.dto.clientobject.ClosedAreaCarApplyCO;
import com.zcloud.primeport.persistence.dataobject.ClosedAreaCarApplyDO;
import com.zcloud.primeport.persistence.repository.ClosedAreaCarApplyRepository;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.alibaba.cola.dto.PageResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

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


/**
 * web-app
 *
 * @Author dearLin
 * @Date 2026-03-20 10:07:14
 */
@Component
@AllArgsConstructor
public class ClosedAreaCarApplyQueryExe {
    private final ClosedAreaCarApplyRepository closedAreaCarApplyRepository;
    private final ClosedAreaCarApplyCoConvertor closedAreaCarApplyCoConvertor;

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public ClosedAreaCarApplyCO queryById(Long id) {
        return closedAreaCarApplyCoConvertor.converDOToCO(closedAreaCarApplyRepository.getById(id));
    }

    /**
     * 分页
     *
     * @param closedAreaCarApplyPageQry
     * @return
     */
    public PageResponse<ClosedAreaCarApplyCO> execute(ClosedAreaCarApplyPageQry closedAreaCarApplyPageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(closedAreaCarApplyPageQry);
        PageResponse<ClosedAreaCarApplyDO> pageResponse = closedAreaCarApplyRepository.listPage(params);
        List<ClosedAreaCarApplyCO> examCenterCOS = closedAreaCarApplyCoConvertor.converDOsToCOs(pageResponse.getData());
        // 获取当前登录用户ID
        Long currentUserId = AuthContext.getUserId();
        // 设置当前用户是否能审核
        for (ClosedAreaCarApplyCO co : examCenterCOS) {
            // 审核中(1)且当前用户是审批人 → 能审核(1)，否则不能审核(2)
            if (co.getAuditFlag() != null && co.getAuditFlag() == 1 
                    && co.getAuditPersonUserId() != null 
                    && co.getAuditPersonUserId().equals(currentUserId)) {
                co.setCurrentUserCanAudit(1);
            } else {
                co.setCurrentUserCanAudit(2);
            }
        }
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }
}

