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

import com.zcloud.personnel.positioning.command.convertor.AlarmDisposeRecordCoConvertor;
import com.zcloud.personnel.positioning.dto.AlarmDisposeRecordPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.AlarmDisposeRecordCO;
import com.zcloud.personnel.positioning.persistence.dataobject.AlarmDisposeRecordDO;
import com.zcloud.personnel.positioning.persistence.repository.AlarmDisposeRecordRepository;
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 AlarmDisposeRecordQueryExe {
    private final AlarmDisposeRecordRepository alarmDisposeRecordRepository;
    private final AlarmDisposeRecordCoConvertor alarmDisposeRecordCoConvertor;

    public PageResponse<AlarmDisposeRecordCO> execute(AlarmDisposeRecordPageQry qry) {
        Map<String, Object> params = qry.toHashMap();
        fillCorpinfo(params);
        PageResponse<AlarmDisposeRecordDO> pageResponse = alarmDisposeRecordRepository.listPage(params);
        List<AlarmDisposeRecordCO> data = alarmDisposeRecordCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<AlarmDisposeRecordCO> listAll() {
        QueryWrapper<AlarmDisposeRecordDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return alarmDisposeRecordCoConvertor.converDOsToCOs(alarmDisposeRecordRepository.list(queryWrapper));
    }

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