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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.safetyDutyList.domain.util.FeedbackCycleUtil;
import com.zcloud.safetyDutyList.dto.clientobject.tasklist.TaskExecutionCO;
import com.zcloud.safetyDutyList.dto.tasklist.TaskExecutionPageQry;
import com.zcloud.safetyDutyList.persistence.dataobject.tasklist.FeedbackDO;
import com.zcloud.safetyDutyList.persistence.dataobject.tasklist.TaskExecutionDO;
import com.zcloud.safetyDutyList.persistence.repository.tasklist.FeedbackRepository;
import com.zcloud.safetyDutyList.persistence.repository.tasklist.TaskExecutionRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    public PageResponse<TaskExecutionCO> listPage(TaskExecutionPageQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<TaskExecutionDO> pageResponse = taskExecutionRepository.listPage(params);
        if (pageResponse.isEmpty()) {
            return PageResponse.of(new ArrayList <>(), pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }

        // 获取所有的反馈
        List<String> executionIds = pageResponse.getData().stream().map(d -> d.getTaskExecutionId()).collect(Collectors.toList());
        Map<String, List<FeedbackDO>>  feedbackMap = ObtainFeedback(executionIds);

        List<TaskExecutionCO> coList = pageResponse.getData().stream().map(d -> {
            TaskExecutionCO co = new TaskExecutionCO();
            BeanUtils.copyProperties(d, co);
            co.setFeedbackCount(0);
            co.setCurrentPeriodFeedback(0);
            List<FeedbackDO> feedbackDOList = feedbackMap.get(d.getTaskExecutionId());
            if (feedbackDOList != null && feedbackDOList.size() > 0) {
                co.setFeedbackCount(feedbackDOList.size());
                String periodFlag = FeedbackCycleUtil.generatePeriodFlag(co.getFeedbackCycleType(), LocalDateTime.now());
                long matchNum = feedbackDOList.stream()
                        .filter(item -> periodFlag.equals(item.getFeedbackPeriodFlag()))
                        .count();
                co.setCurrentPeriodFeedback(matchNum > 0 ? 1 : 0);
            }
            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);
    }

    private Map<String, List<FeedbackDO>> ObtainFeedback(List<String> executionIds) {
        // 获取所有的反馈
        Map<String, List<FeedbackDO>> feedbackMap = new HashMap <>();

        QueryWrapper<FeedbackDO> feedbackQueryWrapper = new QueryWrapper<>();
        feedbackQueryWrapper.in("task_execution_id", executionIds);
        List<FeedbackDO> feedbackList = feedbackRepository.list(feedbackQueryWrapper);
        if (feedbackList != null && feedbackList.size() > 0) {
            feedbackMap = feedbackList.stream().collect(Collectors.groupingBy(FeedbackDO::getTaskExecutionId));
        }

        return feedbackMap;
    }

}
