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

import com.zcloud.personnel.positioning.command.convertor.SyncTaskCoConvertor;
import com.zcloud.personnel.positioning.dto.SyncTaskPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.SyncTaskCO;
import com.zcloud.personnel.positioning.persistence.dataobject.SyncTaskDO;
import com.zcloud.personnel.positioning.persistence.repository.SyncTaskRepository;
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 SyncTaskQueryExe {
    private final SyncTaskRepository syncTaskRepository;
    private final SyncTaskCoConvertor syncTaskCoConvertor;

    public PageResponse<SyncTaskCO> execute(SyncTaskPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<SyncTaskDO> pageResponse = syncTaskRepository.listPage(params);
        List<SyncTaskCO> data = syncTaskCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<SyncTaskCO> listAll() {
        QueryWrapper<SyncTaskDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return syncTaskCoConvertor.converDOsToCOs(syncTaskRepository.list(queryWrapper));
    }

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