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

import com.zcloud.personnel.positioning.command.convertor.AlarmRecordTargetCoConvertor;
import com.zcloud.personnel.positioning.dto.AlarmRecordTargetPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.AlarmRecordTargetCO;
import com.zcloud.personnel.positioning.persistence.dataobject.AlarmRecordTargetDO;
import com.zcloud.personnel.positioning.persistence.repository.AlarmRecordTargetRepository;
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 AlarmRecordTargetQueryExe {
    private final AlarmRecordTargetRepository alarmRecordTargetRepository;
    private final AlarmRecordTargetCoConvertor alarmRecordTargetCoConvertor;

    public PageResponse<AlarmRecordTargetCO> execute(AlarmRecordTargetPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<AlarmRecordTargetDO> pageResponse = alarmRecordTargetRepository.listPage(params);
        List<AlarmRecordTargetCO> data = alarmRecordTargetCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<AlarmRecordTargetCO> listAll() {
        QueryWrapper<AlarmRecordTargetDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return alarmRecordTargetCoConvertor.converDOsToCOs(alarmRecordTargetRepository.list(queryWrapper));
    }

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