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

import com.alibaba.cola.dto.MultiResponse;
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.*;
import com.zcloud.safetyDutyList.dto.tasklist.FeedbackListQry;
import com.zcloud.safetyDutyList.dto.tasklist.FeedbackPeriodGroupQry;
import com.zcloud.safetyDutyList.persistence.dataobject.tasklist.FeedbackDO;
import com.zcloud.safetyDutyList.persistence.dataobject.tasklist.TaskDetailDO;
import com.zcloud.safetyDutyList.persistence.repository.tasklist.FeedbackRepository;
import com.zcloud.safetyDutyList.persistence.repository.tasklist.TaskDetailRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
public class FeedbackQueryExe {
    private final FeedbackRepository feedbackRepository;
    private final TaskDetailRepository taskDetailRepository;

    public MultiResponse<FeedbackPeriodGroupCO> periodGroupList(FeedbackPeriodGroupQry qry) {
        List<FeedbackDO> feedbackList = feedbackRepository.listByTaskExecutionId(qry.getTaskExecutionId());
        if (feedbackList == null || feedbackList.isEmpty()) {
            return MultiResponse.of(new ArrayList<>());
        }

        // Filter by time range if provided
        if (qry.getFeedbackTimeStart() != null || qry.getFeedbackTimeEnd() != null) {

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            feedbackList = feedbackList.stream().filter(f -> {

                if (f.getFeedbackTime() == null) {
                    return false;
                }

                boolean match = true;
                if (qry.getFeedbackTimeStart() != null && !qry.getFeedbackTimeStart().isEmpty()) {
                    LocalDateTime startParse = LocalDateTime.parse(qry.getFeedbackTimeStart(), dateTimeFormatter);
                    LocalDateTime dayStart = startParse.with(LocalTime.MIN);
                    match = f.getFeedbackTime().isAfter(dayStart);
                }
                if (qry.getFeedbackTimeEnd() != null && !qry.getFeedbackTimeEnd().isEmpty()) {
                    LocalDateTime endParse = LocalDateTime.parse(qry.getFeedbackTimeEnd(), dateTimeFormatter);
                    LocalDateTime dayEnd = endParse.plusDays(1).with(LocalTime.MIN);
                    match = match && f.getFeedbackTime().isBefore(dayEnd);
                }
                return match;
            }).collect(Collectors.toList());

        }

        Map<String, List<FeedbackDO>> groupedByPeriod = feedbackList.stream()
                .filter(f -> f.getFeedbackPeriodFlag() != null)
                .collect(Collectors.groupingBy(FeedbackDO::getFeedbackPeriodFlag));

        List<FeedbackPeriodGroupCO> result = new ArrayList<>();
        groupedByPeriod.forEach((periodFlag, feedbacks) -> {
            FeedbackPeriodGroupCO co = new FeedbackPeriodGroupCO();
            co.setTaskExecutionId(qry.getTaskExecutionId());
            co.setFeedbackPeriodFlag(periodFlag);
            co.setFeedbackCount(feedbacks.size());
            if (!feedbacks.isEmpty()) {
                FeedbackDO first = feedbacks.get(0);
                co.setFeedbackPeriodStartTime(first.getFeedbackPeriodStartTime());
                co.setFeedbackPeriodEndTime(first.getFeedbackPeriodEndTime());
                co.setFeedbackUserName(first.getFeedbackUserName());
            }
            result.add(co);
        });
        return MultiResponse.of(result);
    }

    public PageResponse<FeedbackCO> feedbackPage(FeedbackListQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<FeedbackDO> pageResponse = feedbackRepository.feedbackPage(params);
        List<FeedbackDO> doList = pageResponse.getData();
        if (doList == null || doList.isEmpty()) {
            return PageResponse.of(new ArrayList<>(), pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        List<FeedbackCO> coList = doList.stream().map(feedbackDO -> {
            FeedbackCO co = new FeedbackCO();
            BeanUtils.copyProperties(feedbackDO, co);
            return co;
        }).collect(Collectors.toList());
        return PageResponse.of(coList, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public SingleResponse<FeedbackCO> getByFeedbackId(String feedbackId) {
        FeedbackDO feedbackDO = feedbackRepository.getByFeedbackId(feedbackId);
        if (feedbackDO == null) {
            throw new BizException("反馈记录不存在");
        }
        FeedbackCO co = new FeedbackCO();
        BeanUtils.copyProperties(feedbackDO, co);

        TaskDetailDO detailDO = taskDetailRepository.getByTaskDetailId(feedbackDO.getTaskDetailId());
        if (detailDO != null) {
            co.setExecuteContent(detailDO.getExecuteContent());
            co.setFeedbackCycleType(detailDO.getFeedbackCycleType());
        }
        return SingleResponse.of(co);
    }
}
