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

import com.zcloud.personnel.positioning.command.convertor.FencePointCoConvertor;
import com.zcloud.personnel.positioning.dto.FencePointPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.FencePointCO;
import com.zcloud.personnel.positioning.persistence.dataobject.FencePointDO;
import com.zcloud.personnel.positioning.persistence.repository.FencePointRepository;
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 FencePointQueryExe {
    private final FencePointRepository fencePointRepository;
    private final FencePointCoConvertor fencePointCoConvertor;

    public PageResponse<FencePointCO> execute(FencePointPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<FencePointDO> pageResponse = fencePointRepository.listPage(params);
        List<FencePointCO> data = fencePointCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<FencePointCO> listAll() {
        QueryWrapper<FencePointDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return fencePointCoConvertor.converDOsToCOs(fencePointRepository.list(queryWrapper));
    }

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