package nckd.jxccl.hr.hstu.business.algo;

import kd.bos.algo.DataType;
import kd.bos.algo.Field;
import kd.bos.algo.MapFunction;
import kd.bos.algo.Row;
import kd.bos.algo.RowMeta;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.hr.hstu.common.HonorStudentConstant;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
* 【优秀生】-综合评测排名计算（按评价活动维度排名）
* @author W.Y.C
* @date 2025/8/11 12:06
* @version 1.0
*/
public class RankMapFunction extends MapFunction {
    private final RowMeta rowMeta;

    /**记录每个评价活动的排名*/
    private Map<Long, AtomicInteger> rankMap = new HashMap<>();


    public RankMapFunction(RowMeta sourceMeta) {
        // 新增排名字段
        Field[] fields = sourceMeta.getFields();
        Field[] newFields = Arrays.copyOf(fields, fields.length + 1);
        newFields[newFields.length - 1] = new Field("rank", DataType.IntegerType);
        this.rowMeta = new RowMeta(newFields);
    }
    @Override
    public Object[] map(Row row) {
        Long evaluationRuleId = row.getLong(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+ FormConstant.ID_KEY);
        //根据不同的评价活动维度排名
        AtomicInteger rank = rankMap.computeIfAbsent(evaluationRuleId, k -> new AtomicInteger(1));

        // 先返回当前值，然后递增
        int currentRank = rank.getAndIncrement();

        Object[] newRow = new Object[rowMeta.getFieldCount()];
        for (int i = 0; i < rowMeta.getFieldCount() - 1; i++) {
            newRow[i] = row.get(i);
        }
        newRow[newRow.length - 1] = currentRank;
        return newRow;
    }

    @Override
    public RowMeta getResultRowMeta() {
        return rowMeta;
    }
}
