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

import com.zcloud.personnel.positioning.command.convertor.TerminalBindCoConvertor;
import com.zcloud.personnel.positioning.dto.TerminalBindPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalBindCO;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalBindDO;
import com.zcloud.personnel.positioning.persistence.repository.TerminalBindRepository;
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 TerminalBindQueryExe {
    private final TerminalBindRepository terminalBindRepository;
    private final TerminalBindCoConvertor terminalBindCoConvertor;

    public PageResponse<TerminalBindCO> execute(TerminalBindPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<TerminalBindDO> pageResponse = terminalBindRepository.listPage(params);
        List<TerminalBindCO> data = terminalBindCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<TerminalBindCO> listAll() {
        QueryWrapper<TerminalBindDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return terminalBindCoConvertor.converDOsToCOs(terminalBindRepository.list(queryWrapper));
    }

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