package com.zcloud.personnel.positioning.command.query;

import com.zcloud.personnel.positioning.command.convertor.OpenapiConfigCoConvertor;
import com.zcloud.personnel.positioning.dto.OpenapiConfigPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.OpenapiConfigCO;
import com.zcloud.personnel.positioning.persistence.dataobject.OpenapiConfigDO;
import com.zcloud.personnel.positioning.persistence.repository.OpenapiConfigRepository;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

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

/**
 * web-app
 *
 * @Author fangjiakai
 * @Date 2026-07-07
 */
@Component
@AllArgsConstructor
public class OpenapiConfigQueryExe {
    private final OpenapiConfigRepository openapiConfigRepository;
    private final OpenapiConfigCoConvertor openapiConfigCoConvertor;

    public PageResponse<OpenapiConfigCO> execute(OpenapiConfigPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<OpenapiConfigDO> pageResponse = openapiConfigRepository.listPage(params);
        List<OpenapiConfigCO> data = openapiConfigCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<OpenapiConfigCO> listAll() {
        QueryWrapper<OpenapiConfigDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return openapiConfigCoConvertor.converDOsToCOs(openapiConfigRepository.list(queryWrapper));
    }

    public OpenapiConfigCO queryById(Long id) {
        QueryWrapper<OpenapiConfigDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        applyCorpinfo(queryWrapper);
        OpenapiConfigDO dataObject = openapiConfigRepository.getOne(queryWrapper, false);
        return openapiConfigCoConvertor.converDOToCO(dataObject);
    }

    private void fillCorpinfo(Map<String, Object> params) {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser != null && ssoUser.getCompanyId() != null) {
            params.put("eqCorpinfoId", String.valueOf(ssoUser.getCompanyId()));
        }
    }

    private void applyCorpinfo(QueryWrapper<OpenapiConfigDO> queryWrapper) {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser != null && ssoUser.getCompanyId() != null) {
            queryWrapper.eq("corpinfo_id", String.valueOf(ssoUser.getCompanyId()));
        }
    }
}
