package com.ximai.mes.report.service.impl;

import com.ximai.mes.pro.domain.ProProcess;
import com.ximai.mes.pro.mapper.ProFeedbackMapper;
import com.ximai.mes.pro.mapper.ProProcessMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.report.request.FeedbackRequest;
import com.ximai.mes.report.request.ProgressReportRequest;
import com.ximai.mes.report.response.*;
import com.ximai.mes.report.service.FeedbackService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FeedbackServiceImp implements FeedbackService {
    @Autowired
    ProFeedbackMapper proFeedbackMapper;
    @Autowired
    ProWorkorderMapper proWorkorderMapper;
    @Autowired
    ProProcessMapper proProcessMapper;
    @Override
    public List<String> getProgressReportProcessNames() {
        // 进度报表表头：使用全部工序（不限制启用），保证与工序完工数据能对应
        ProProcess query = new ProProcess();
        List<ProProcess> list = proProcessMapper.selectProProcessList(query);
        if (list == null) return Collections.emptyList();
        return list.stream()
                .sorted(Comparator.comparing(ProProcess::getProcessId, Comparator.nullsLast(Long::compareTo)))
                .map(ProProcess::getProcessName)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    public ProgressReportListResult getProgressReportList(ProgressReportRequest request) {
        List<ProgressReportRowDto> rows = proWorkorderMapper.getProgressReportList(request);
        long total = new PageInfo<>(rows).getTotal();
        if (rows == null || rows.isEmpty()) {
            return new ProgressReportListResult(Collections.emptyList(), total);
        }

        List<Long> workorderIds = rows.stream()
                .map(ProgressReportRowDto::getWorkorderId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        Map<String, Map<String, BigDecimal>> batchProcessMap = new HashMap<>();
        if (!workorderIds.isEmpty()) {
            List<ProgressReportProcessQtyDto> processQtys = proWorkorderMapper.getProgressReportProcessQuantities(workorderIds);
            for (ProgressReportProcessQtyDto dto : processQtys) {
                if (dto.getWorkorderId() == null) {
                    continue;
                }
                batchProcessMap
                        .computeIfAbsent(progressReportRowKey(dto.getWorkorderId(), dto.getTaskBatch()), k -> new LinkedHashMap<>())
                        .put(dto.getProcessName(), dto.getQuantityProduced() != null ? dto.getQuantityProduced() : BigDecimal.ZERO);
            }
        }

        // 仅保留本次查询实际用到的工序列（按工序ID顺序过滤）
        List<String> allProcessNames = getProgressReportProcessNames();
        Set<String> usedProcessNames = batchProcessMap.values().stream()
                .flatMap(m -> m.entrySet().stream())
                .filter(e -> e.getValue() != null) // 有数据的工序
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());
        List<String> processNames = allProcessNames.stream()
                .filter(usedProcessNames::contains)
                .collect(Collectors.toList());
        List<ProgressReportResponse> result = new ArrayList<>();
        for (ProgressReportRowDto row : rows) {
            BigDecimal progressPercent = row.getProgressPercent() != null ? row.getProgressPercent() : BigDecimal.ZERO;

            ProgressReportResponse resp = new ProgressReportResponse();
            resp.setScheduleTime(row.getScheduleTime());
            resp.setOrderCode(row.getOrderCode());
            resp.setLineName(row.getLineName());
            resp.setWorkorderCode(row.getWorkorderCode());
            resp.setTaskBatch(row.getTaskBatch());
            resp.setOrderSerial(row.getOrderSerial());
            resp.setWorkorderType(row.getWorkorderType());
            resp.setProductCode(row.getProductCode());
            resp.setProductName(row.getProductName());
            resp.setPlanQuantity(row.getPlanQuantity());
            resp.setProgressPercent(progressPercent);
            resp.setRequestDate(row.getRequestDate());

            Map<String, BigDecimal> rowProcess = batchProcessMap.getOrDefault(
                    progressReportRowKey(row.getWorkorderId(), row.getTaskBatch()), new LinkedHashMap<>());
            for (String pname : processNames) {
                // 只响应该工单实际有数据的工序；没有记录则不放入 processQuantities
                BigDecimal val = rowProcess.get(pname);
                if (val != null) {
                    resp.getProcessQuantities().put(pname, val);
                }
            }
            result.add(resp);
        }
        return new ProgressReportListResult(result, total);
    }

    private static String progressReportRowKey(Long workorderId, String taskBatch) {
        return workorderId + "|" + (taskBatch != null ? taskBatch : "");
    }

    @Override
    public List<FeedbackResponse> getList(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getList(feedbackRequest);
    }
    @Override
    public List<FeedbackResponseExportByList> export(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.export(feedbackRequest);
    }


    @Override
    public List<FeedbackResponse> getListByWorkOrder(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getListByWorkOrder(feedbackRequest);
    }

    @Override
    public List<FeedbackResponseExportByWorkOrder> getListByWorkOrderExport(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.getListByWorkOrderExport(feedbackRequest);
    }

    @Override
    public List<FeedbackResponse> getListByWorkshop(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getListByWorkshop(feedbackRequest);
    }
    @Override
    public List<FeedbackResponseExportByWorkshop> getListByWorkshopExport(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.getListByWorkshopExport(feedbackRequest);
    }

    @Override
    public List<FeedbackResponse> getListByWorkstation(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getListByWorkstation(feedbackRequest);
    }
    @Override
    public List<FeedbackResponseExportByWorkstation> getListByWorkstationExport(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.getListByWorkstationExport(feedbackRequest);
    }

    @Override
    public List<FeedbackResponse> getListByWorkunit(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getListByWorkunit(feedbackRequest);
    }
    @Override
    public List<FeedbackResponseExportByWorkunit> getListByWorkunitExport(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.getListByWorkunitExport(feedbackRequest);
    }

    @Override
    public List<FeedbackResponse> getListByProcess(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getListByProcess(feedbackRequest);
    }

    @Override
    public  List<FeedbackResponseExportByProcess> getListByProcessExport(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.getListByProcessExport(feedbackRequest);
    }

    @Override
    public List<FeedbackResponse> getListByUser(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getListByUser(feedbackRequest);
    }

    @Override
    public List<FeedbackResponseExportByUser> getListByUserExport(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.getListByUserExport(feedbackRequest);
    }

    @Override
    public List<FeedbackResponse> getListByDefect(FeedbackRequest feedbackRequest) {
        return proFeedbackMapper.getListByDefect(feedbackRequest);
    }



    @Override
    public List<FeedbackResponseExportByDefect> getListByDefectExport(FeedbackRequest feedbackRequest){
        return proFeedbackMapper.getListByDefectExport(feedbackRequest);
    }

}
