package com.syjy.calculate.function;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;
import com.googlecode.aviator.runtime.type.Sequence;
import com.syjy.calculate.entity.CalculateResult;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 将根据每15分钟时间 list数据转为List<List<Map<>>> 格式
 *
 * @author zcl
 * @version 1.0
 * @since 2022/9/8 9:30
 */
public class DoubleList extends AbstractFunction {
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
        // 获取参数
        Object first = arg1.getValue(env);
        // 将参数转为集合
        Sequence seq = CommonUtil.getSeq(first,env);
        // 获取当天开始0时时间和当前时间15分钟节点
        long startTime = DateUtil.beginOfDay(DateTime.now()).getTime();
        // 获取当前时间
        long nowTime = DateTime.now().getTime();
        long moment15 = 900000L;
        BigDecimal nowTimeBig = new BigDecimal(String.valueOf(nowTime));
        BigDecimal moment15Big = new BigDecimal(String.valueOf(moment15));
        BigDecimal queryTimeBig = nowTimeBig.divideAndRemainder(moment15Big)[0].multiply(moment15Big);
        long endTime = queryTimeBig.longValue();
        List<List<Map<String,Object>>> lastList = new ArrayList<>();
        for(long stepTime = startTime;stepTime<=endTime;stepTime=stepTime+moment15){
            List<Map<String,Object>> list = new ArrayList<>();
            for (Object obj : seq) {
                Map<String, Object> map = (Map<String, Object>) obj;
                long time = (long)map.get(CalculateResult.TIME);
                if(stepTime== time){
                    list.add(map);
                }
            }
            if(list!=null && list.size()>0){
                lastList.add(list);
            }
        }
        env.put("list",lastList);
        return AviatorRuntimeJavaType.valueOf(lastList);
    }
    @Override
    public String getName() {
        return "doubleList";
    }

}
