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

import com.zcloud.personnel.positioning.command.convertor.SyncLogCoConvertor;
import com.zcloud.personnel.positioning.dto.SyncLogPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.SyncLogCO;
import com.zcloud.personnel.positioning.persistence.dataobject.SyncLogDO;
import com.zcloud.personnel.positioning.persistence.repository.SyncLogRepository;
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 SyncLogQueryExe {
    private final SyncLogRepository syncLogRepository;
    private final SyncLogCoConvertor syncLogCoConvertor;

    public PageResponse<SyncLogCO> execute(SyncLogPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<SyncLogDO> pageResponse = syncLogRepository.listPage(params);
        List<SyncLogCO> data = syncLogCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<SyncLogCO> listAll() {
        QueryWrapper<SyncLogDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return syncLogCoConvertor.converDOsToCOs(syncLogRepository.list(queryWrapper));
    }

    public SyncLogCO queryById(Long id) {
        QueryWrapper<SyncLogDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        applyCorpinfo(queryWrapper);
        SyncLogDO dataObject = syncLogRepository.getOne(queryWrapper, false);
        return syncLogCoConvertor.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<SyncLogDO> queryWrapper) {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser != null && ssoUser.getCompanyId() != null) {
            queryWrapper.eq("corpinfo_id", String.valueOf(ssoUser.getCompanyId()));
        }
    }
}
