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

import com.zcloud.personnel.positioning.command.convertor.AlarmRuleFenceRelCoConvertor;
import com.zcloud.personnel.positioning.dto.AlarmRuleFenceRelPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.AlarmRuleFenceRelCO;
import com.zcloud.personnel.positioning.persistence.dataobject.AlarmRuleFenceRelDO;
import com.zcloud.personnel.positioning.persistence.repository.AlarmRuleFenceRelRepository;
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 AlarmRuleFenceRelQueryExe {
    private final AlarmRuleFenceRelRepository alarmRuleFenceRelRepository;
    private final AlarmRuleFenceRelCoConvertor alarmRuleFenceRelCoConvertor;

    public PageResponse<AlarmRuleFenceRelCO> execute(AlarmRuleFenceRelPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<AlarmRuleFenceRelDO> pageResponse = alarmRuleFenceRelRepository.listPage(params);
        List<AlarmRuleFenceRelCO> data = alarmRuleFenceRelCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<AlarmRuleFenceRelCO> listAll() {
        QueryWrapper<AlarmRuleFenceRelDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return alarmRuleFenceRelCoConvertor.converDOsToCOs(alarmRuleFenceRelRepository.list(queryWrapper));
    }

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