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

import com.zcloud.personnel.positioning.command.convertor.TerminalCoConvertor;
import com.zcloud.personnel.positioning.dto.TerminalPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalCO;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalDO;
import com.zcloud.personnel.positioning.persistence.repository.TerminalRepository;
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 TerminalQueryExe {
    private final TerminalRepository terminalRepository;
    private final TerminalCoConvertor terminalCoConvertor;

    public PageResponse<TerminalCO> execute(TerminalPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<TerminalDO> pageResponse = terminalRepository.listPage(params);
        List<TerminalCO> data = terminalCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<TerminalCO> listAll() {
        QueryWrapper<TerminalDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return terminalCoConvertor.converDOsToCOs(terminalRepository.list(queryWrapper));
    }

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