package com.jay.monitor.data.server.store.es;

import com.jay.monitor.data.core.model.response.PageResponseModel;
import com.jay.monitor.data.server.componts.ElasticSearchPartition;
import com.jay.monitor.data.server.enums.StoreType;
import com.jay.monitor.data.server.store.TraceSearchProcess;
import com.jay.monitor.data.server.utils.ESUtils;
import com.jay.monitor.data.server.utils.JayDataUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.zxp.esclientrhl.repository.PageList;
import org.zxp.esclientrhl.repository.Sort;
import org.zxp.esclientrhl.util.IndexTools;
import org.zxp.esclientrhl.util.MetaData;

import java.util.List;

public abstract class AbstractTraceElasticSearch<T, R, I> extends TraceSearchProcess<T, R> {

    @Autowired
    private ElasticSearchPartition elasticSearchPartition;

    /**
     * 对应的索引实体对象
     *
     * @return
     */
    public abstract Class getIndexClass();

    @Override
    public StoreType storeType() {
        return StoreType.ES;
    }

    public abstract List<R> builderResponseList(List<I> list);

    protected QueryBuilder builderQuery(I query) throws Exception {
        return ESUtils.beanToQueryBuilder(query);
    }

    @Override
    public PageResponseModel<R> searchDataByList(String date, Integer pageNo, Integer pageSize, T query)
        throws Exception {
        MetaData metaData = IndexTools.getIndexType(getIndexClass());
        String indexname = metaData.getIndexname();
        String partitionIndexName = JayDataUtils.getTableName(indexname, date);
        Object indexEntity = getIndexClass().newInstance();
        BeanUtils.copyProperties(query, indexEntity);
        QueryBuilder queryBuilder = builderQuery((I)indexEntity);
        PageList pageList = elasticSearchPartition
            .searchPartitionPage(partitionIndexName, queryBuilder, pageNo, pageSize, getIndexClass(),
                new Sort.Order[] {new Sort.Order(SortOrder.DESC, "createDate")});
        PageResponseModel<R> pageResponseModel = JayDataUtils
            .builderPageResponseModel(pageNo, pageSize, pageList.getTotalPages(),
                builderResponseList(pageList.getList()));
        return pageResponseModel;
    }
}
