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.TaskListIssueCO;
import com.zcloud.safetyDutyList.dto.tasklist.TaskListIssuePageQry;
import com.zcloud.safetyDutyList.dto.tasklist.TaskListPageQry;
import com.zcloud.safetyDutyList.persistence.dataobject.tasklist.TaskListIssueDO;
import com.zcloud.safetyDutyList.persistence.repository.tasklist.TaskListIssueRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

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

/**
 * 清单下发记录查询执行器
 */
@Component
@AllArgsConstructor
public class TaskListIssueQueryExe {
    private final TaskListIssueRepository taskListIssueRepository;

    public PageResponse<TaskListIssueCO> listPage(TaskListIssuePageQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        String menuPath = qry.getMenuPath();
        PageResponse<TaskListIssueDO> pageResponse = taskListIssueRepository.listPage(params, menuPath);
        List<TaskListIssueCO> coList = pageResponse.getData().stream().map(d -> {
            TaskListIssueCO co = new TaskListIssueCO();
            BeanUtils.copyProperties(d, co);
            co.setPeriodStartTime(YearMonth.from(d.getPeriodStartTime()));
            co.setPeriodEndTime(YearMonth.from(d.getPeriodEndTime()));
            return co;
        }).collect(Collectors.toList());
        return PageResponse.of(coList, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public SingleResponse<TaskListIssueCO> getByTaskIssueId(String taskIssueId) {
        TaskListIssueDO issueDO = taskListIssueRepository.getByTaskIssueId(taskIssueId);
        if (issueDO == null) {
            throw new BizException("下发记录不存在");
        }
        TaskListIssueCO co = new TaskListIssueCO();
        BeanUtils.copyProperties(issueDO, co);
        return SingleResponse.of(co);
    }

    /**
     * 统计执行者为指定用户的下发记录数量
     *
     * @param executeUserId 执行用户ID
     * @return 数量
     */
    public SingleResponse<Long> countByExecuteUserId(Long executeUserId) {
        long count = taskListIssueRepository.countByExecuteUserId(executeUserId);
        return SingleResponse.of(count);
    }
}
