package com.zcloud.safetyDutyList.command.query.tasklist;

import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.safetyDutyList.dto.clientobject.tasklist.TaskExecutionCO;
import com.zcloud.safetyDutyList.dto.tasklist.TaskExecutionPageQry;
import com.zcloud.safetyDutyList.persistence.dataobject.tasklist.TaskExecutionDO;
import com.zcloud.safetyDutyList.persistence.repository.tasklist.TaskExecutionRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务执行记录查询执行器
 */
@Component
@AllArgsConstructor
public class TaskExecutionQueryExe {
    private final TaskExecutionRepository taskExecutionRepository;

    public PageResponse<TaskExecutionCO> listPage(TaskExecutionPageQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<TaskExecutionDO> pageResponse = taskExecutionRepository.listPage(params);
        List<TaskExecutionCO> coList = pageResponse.getData().stream().map(d -> {
            TaskExecutionCO co = new TaskExecutionCO();
            BeanUtils.copyProperties(d, co);
            return co;
        }).collect(Collectors.toList());
        return PageResponse.of(coList, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public SingleResponse<TaskExecutionCO> getByTaskExecutionId(String taskExecutionId) {
        TaskExecutionDO executionDO = taskExecutionRepository.getByTaskExecutionId(taskExecutionId);
        if (executionDO == null) {
            throw new BizException("任务执行记录不存在");
        }
        TaskExecutionCO co = new TaskExecutionCO();
        BeanUtils.copyProperties(executionDO, co);
        return SingleResponse.of(co);
    }
}
