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

import com.zcloud.personnel.positioning.command.convertor.AlarmRuleItemCoConvertor;
import com.zcloud.personnel.positioning.dto.AlarmRuleItemPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.AlarmRuleItemCO;
import com.zcloud.personnel.positioning.persistence.dataobject.AlarmRuleItemDO;
import com.zcloud.personnel.positioning.persistence.repository.AlarmRuleItemRepository;
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 AlarmRuleItemQueryExe {
    private final AlarmRuleItemRepository alarmRuleItemRepository;
    private final AlarmRuleItemCoConvertor alarmRuleItemCoConvertor;

    public PageResponse<AlarmRuleItemCO> execute(AlarmRuleItemPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<AlarmRuleItemDO> pageResponse = alarmRuleItemRepository.listPage(params);
        List<AlarmRuleItemCO> data = alarmRuleItemCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<AlarmRuleItemCO> listAll() {
        QueryWrapper<AlarmRuleItemDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return alarmRuleItemCoConvertor.converDOsToCOs(alarmRuleItemRepository.list(queryWrapper));
    }

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