package jnpf.personnels.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.model.personnels.vo.analysis.PersonnelDataAnalysisListVO;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 人事数据分析工具类
 */
@Slf4j
public class PersonnelDataAnalysisUtil {

    /**
     * 将 PageListVO 数据封装到 PersonnelDataAnalysisListVO
     * @param pageListVO 分页数据
     * @return PersonnelDataAnalysisListVO
     */
    public static <T> PersonnelDataAnalysisListVO encapsulatePageData(PageListVO<T> pageListVO,Class<?> clazz) {

        // 提取列信息（只处理一次）
        List<PersonnelDataAnalysisListVO.Column> columns = extractColumns(clazz);
        if (CollUtil.isEmpty(columns)) {
            throw new RuntimeException("没有字段存在@ExcelProperty 注解!");
        }
        // 参数校验
        if (pageListVO == null || CollUtil.isEmpty(pageListVO.getList())) {
            assert pageListVO != null;
            return createEmptyResult(columns,pageListVO.getPagination());
        }
        // 构建列名到 Column 的映射，提高查找效率
        Map<String, PersonnelDataAnalysisListVO.Column> columnMap = columns.stream()
                .collect(Collectors.toMap(
                        PersonnelDataAnalysisListVO.Column::getProp,
                        col -> col,
                        (k1, k2) -> k1,
                        LinkedHashMap::new
                ));
        List<T> list = pageListVO.getList();
        // 转换数据列表
        List<List<PersonnelDataAnalysisListVO.ListItem>> listItems = convertToListItems(list, columnMap);
        
        // 组装结果
        PersonnelDataAnalysisListVO result = new PersonnelDataAnalysisListVO();
        result.setColumns(columns);
        result.setList(listItems);
        result.setPagination(pageListVO.getPagination());
        
        return result;
    }
    
    /**
     * 创建空结果
     */
    private static PersonnelDataAnalysisListVO createEmptyResult(List<PersonnelDataAnalysisListVO.Column> columns, PaginationVO pagination) {
        PersonnelDataAnalysisListVO result = new PersonnelDataAnalysisListVO();
        result.setColumns(columns);
        result.setList(new ArrayList<>());
        result.setPagination(pagination);
        return result;
    }
    
    /**
     * 提取类的列信息（带 ExcelProperty 注解的字段）
     */
    private static List<PersonnelDataAnalysisListVO.Column> extractColumns(Class<?> clazz) {
        // 缓存未命中，通过反射获取
        Field[] declaredFields = clazz.getDeclaredFields();
        List<Field> validFields = new ArrayList<>();
        
        for (Field field : declaredFields) {
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                validFields.add(field);
            }
        }
        return buildColumnsFromFields(validFields);
    }
    
    /**
     * 从字段列表构建 Column 列表
     */
    private static List<PersonnelDataAnalysisListVO.Column> buildColumnsFromFields(List<Field> fields) {
        List<PersonnelDataAnalysisListVO.Column> columns = new ArrayList<>(fields.size());
        
        for (Field field : fields) {
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            String[] values = excelProperty.value();
            
            PersonnelDataAnalysisListVO.Column column = new PersonnelDataAnalysisListVO.Column();
            column.setLabel(values.length > 0 ? values[0] : field.getName());
            column.setProp(field.getName());
            
            columns.add(column);
        }
        
        return columns;
    }
    
    /**
     * 转换数据列表为 ListItem 列表
     */
    private static <T> List<List<PersonnelDataAnalysisListVO.ListItem>> convertToListItems(
            List<T> list, Map<String, PersonnelDataAnalysisListVO.Column> columnMap) {
        
        List<List<PersonnelDataAnalysisListVO.ListItem>> result = new ArrayList<>(list.size());
        
        for (T data : list) {
            if (data == null) {
                result.add(new ArrayList<>());
                continue;
            }
            
            List<PersonnelDataAnalysisListVO.ListItem> itemList = new ArrayList<>(columnMap.size());
            Class<?> dataClass = data.getClass();
            
            // 遍历 columnMap 而不是字段，确保顺序一致且高效
            for (Map.Entry<String, PersonnelDataAnalysisListVO.Column> entry : columnMap.entrySet()) {
                String fieldName = entry.getKey();
                PersonnelDataAnalysisListVO.ListItem item = new PersonnelDataAnalysisListVO.ListItem();
                item.setName(fieldName);
                item.setValue(getFieldValueAsString(data, dataClass, fieldName));
                itemList.add(item);
            }
            
            result.add(itemList);
        }
        
        return result;
    }
    
    /**
     * 安全地获取字段值并转换为字符串
     */
    private static String getFieldValueAsString(Object obj, Class<?> objClass, String fieldName) {
        try {
            Field field = objClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            Object value = field.get(obj);
            return ObjectUtil.isNotEmpty(value) ? String.valueOf(value) : "";
        } catch (NoSuchFieldException e) {
            log.warn("字段不存在：{}", fieldName, e);
            return "";
        } catch (IllegalAccessException e) {
            log.error("无法访问字段：{}", fieldName, e);
            return "";
        }
    }
}