package com.njcn.influx.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.njcn.influx.base.InfluxDbBaseMapper;
import com.njcn.influx.service.InfluxDBBaseService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.ListUtils;
import org.influxdb.InfluxDB;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Date: 2024/1/15  11:44【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class InfluxDBBaseServiceImpl<T> implements InfluxDBBaseService<T> {

    private final InfluxDB influxDb;

    private final static String PACKAGE_PREFIX = "com.njcn.influx.imapper.InfluxDB";
    private final static String PACKAGE_SUFFIX = "Mapper";

    @Value("${spring.influx.database}")
    private String database;

    @Override
    public void insertBatchBySlice(String tableName, List<T> data, int size) {
        int totalCount = data.size();
        int idxLimit = Math.min(size, totalCount);
        List<List<T>> partition = ListUtils.partition(data, idxLimit);
        //根据表名找到mapper，执行批量插入
        InfluxDbBaseMapper mapper;
        try {
            mapper = (InfluxDbBaseMapper) SpringUtil.getBean(Class.forName(PACKAGE_PREFIX + tableName + PACKAGE_SUFFIX));
            System.out.println(PACKAGE_PREFIX + tableName + PACKAGE_SUFFIX);
            for (List<T> sliceList : partition) {
                List<T> sublistAsOriginalListType = new ArrayList<>(sliceList);
                mapper.insertBatch(sublistAsOriginalListType);
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
//
//
//        partition.forEach(temp -> {
//            if (!data.isEmpty()) {
//                Object firstObj = data.get(0);
//                Class<?> domainClass = firstObj.getClass();
//                List<Point> pointList = new ArrayList<>();
//                for (Object o : data) {
//                    Point point = Point
//                            .measurementByPOJO(domainClass)
//                            .addFieldsFromPOJO(o)
//                            .build();
//                    pointList.add(point);
//                }
//                //获取数据库名和rp
//                Measurement measurement = firstObj.getClass().getAnnotation(Measurement.class);
//                String retentionPolicy = measurement.retentionPolicy();
//                BatchPoints batchPoints = BatchPoints
//                        .builder()
//                        .points(pointList)
//                        .retentionPolicy(retentionPolicy).build();
//                influxDb.setDatabase(database);
//                influxDb.write(batchPoints);
//            }
//        });


    }
}
