package com.zcloud.personnel.positioning.persistence.repository.impl;

import com.zcloud.personnel.positioning.persistence.dataobject.AlarmRuleDO;
import com.zcloud.personnel.positioning.persistence.mapper.AlarmRuleMapper;
import com.zcloud.personnel.positioning.persistence.repository.AlarmRuleRepository;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.gbscommon.utils.Query;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jjb.saas.framework.repository.common.PageHelper;
import com.jjb.saas.framework.repository.repo.impl.BaseRepositoryImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * web-infrastructure
 *
 * @Author fangjiakai
 * @Date 2026-07-07
 */
@Service
@RequiredArgsConstructor
public class AlarmRuleRepositoryImpl extends BaseRepositoryImpl<AlarmRuleMapper, AlarmRuleDO> implements AlarmRuleRepository {
    private final AlarmRuleMapper alarmRuleMapper;

    @Override
    public PageResponse<AlarmRuleDO> listPage(Map<String, Object> params) {
        IPage<AlarmRuleDO> iPage = new Query<AlarmRuleDO>().getPage(params);
        QueryWrapper<AlarmRuleDO> queryWrapper = new QueryWrapper<>();
        queryWrapper = PageQueryHelper.createPageQueryWrapper(queryWrapper, params);
        Object corpinfoMatchId = params.get("corpinfoMatchId");
        String corpinfoMatchName = (String) params.get("corpinfoMatchName");
        if (corpinfoMatchId != null && corpinfoMatchName != null && !corpinfoMatchName.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper.eq("corpinfo_id", corpinfoMatchId)
                    .or(fallback -> fallback.isNull("corpinfo_id").eq("corpinfo_name", corpinfoMatchName)));
        }
        queryWrapper.orderByDesc("create_time");
        IPage<AlarmRuleDO> result = alarmRuleMapper.selectPage(iPage, queryWrapper);
        return PageHelper.pageToResponse(result, result.getRecords());
    }
}
