package com.erp.service;

import com.erp.common.BaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
@Slf4j
public class AnalyticsReportService extends BaseService {

    private static final String NS = "analyticsReport.";

    public Map<String, Object> getProductionReportData(Map<String, Object> params) {
        List<Map<String, Object>> rows = sqlSession.selectList(NS + "getProductionReportData", params);
        Map<String, Object> filterOptions = new LinkedHashMap<>();
        filterOptions.put("processes", extractFilterSet(rows, "process"));
        filterOptions.put("equipment", extractFilterSet(rows, "equipment"));
        filterOptions.put("items", extractFilterSet(rows, "item"));
        filterOptions.put("workers", extractFilterSet(rows, "worker"));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("rows", rows);
        result.put("filter_options", filterOptions);
        result.put("total_count", rows.size());
        return result;
    }

    public Map<String, Object> getInventoryReportData(Map<String, Object> params) {
        List<Map<String, Object>> rows = sqlSession.selectList(NS + "getInventoryReportData", params);
        Map<String, Object> filterOptions = new LinkedHashMap<>();
        filterOptions.put("items", extractFilterSet(rows, "item"));
        filterOptions.put("warehouses", extractFilterSet(rows, "warehouse"));
        filterOptions.put("categories", List.of(
            Map.of("value", "원자재", "label", "원자재"),
            Map.of("value", "부자재", "label", "부자재"),
            Map.of("value", "반제품", "label", "반제품"),
            Map.of("value", "완제품", "label", "완제품"),
            Map.of("value", "일반", "label", "일반")
        ));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("rows", rows);
        result.put("filter_options", filterOptions);
        result.put("total_count", rows.size());
        return result;
    }

    public Map<String, Object> getPurchaseReportData(Map<String, Object> params) {
        List<Map<String, Object>> rows = sqlSession.selectList(NS + "getPurchaseReportData", params);
        Map<String, Object> filterOptions = new LinkedHashMap<>();
        filterOptions.put("suppliers", extractFilterSet(rows, "supplier"));
        filterOptions.put("items", extractFilterSet(rows, "item"));
        filterOptions.put("managers", extractFilterSet(rows, "manager"));
        filterOptions.put("statuses", extractFilterSet(rows, "status"));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("rows", rows);
        result.put("filter_options", filterOptions);
        result.put("total_count", rows.size());
        return result;
    }

    public Map<String, Object> getQualityReportData(Map<String, Object> params) {
        List<Map<String, Object>> rows = sqlSession.selectList(NS + "getQualityReportData", params);
        Map<String, Object> filterOptions = new LinkedHashMap<>();
        filterOptions.put("items", extractFilterSet(rows, "item"));
        filterOptions.put("defect_types", List.of(
            Map.of("value", "외관불량", "label", "외관불량"),
            Map.of("value", "치수불량", "label", "치수불량"),
            Map.of("value", "기능불량", "label", "기능불량"),
            Map.of("value", "재질불량", "label", "재질불량"),
            Map.of("value", "일반검사", "label", "일반검사")
        ));
        filterOptions.put("processes", extractFilterSet(rows, "process"));
        filterOptions.put("inspectors", extractFilterSet(rows, "inspector"));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("rows", rows);
        result.put("filter_options", filterOptions);
        result.put("total_count", rows.size());
        return result;
    }

    public Map<String, Object> getEquipmentReportData(Map<String, Object> params) {
        List<Map<String, Object>> rows = sqlSession.selectList(NS + "getEquipmentReportData", params);
        Map<String, Object> filterOptions = new LinkedHashMap<>();
        filterOptions.put("equipment", extractFilterSet(rows, "equipment"));
        filterOptions.put("equip_types", extractFilterSet(rows, "equip_type"));
        filterOptions.put("lines", extractFilterSet(rows, "line"));
        filterOptions.put("managers", extractFilterSet(rows, "manager"));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("rows", rows);
        result.put("filter_options", filterOptions);
        result.put("total_count", rows.size());
        return result;
    }

    public Map<String, Object> getMoldReportData(Map<String, Object> params) {
        List<Map<String, Object>> rows = sqlSession.selectList(NS + "getMoldReportData", params);
        Map<String, Object> filterOptions = new LinkedHashMap<>();
        filterOptions.put("molds", extractFilterSet(rows, "mold"));
        filterOptions.put("mold_types", extractFilterSet(rows, "mold_type"));
        filterOptions.put("items", extractFilterSet(rows, "item"));
        filterOptions.put("makers", extractFilterSet(rows, "maker"));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("rows", rows);
        result.put("filter_options", filterOptions);
        result.put("total_count", rows.size());
        return result;
    }

    private List<Map<String, Object>> extractFilterSet(List<Map<String, Object>> rows, String field) {
        Map<String, String> seen = new LinkedHashMap<>();
        for (Map<String, Object> row : rows) {
            Object val = row.get(field);
            if (val == null) continue;
            String valStr = val.toString();
            if (!valStr.isEmpty() && !"미지정".equals(valStr)) {
                seen.putIfAbsent(valStr, valStr);
            }
        }
        return seen.entrySet().stream()
            .map(e -> {
                Map<String, Object> m = new LinkedHashMap<>();
                m.put("value", e.getKey());
                m.put("label", e.getValue());
                return m;
            })
            .collect(Collectors.toList());
    }
}
