package com.tmerclub.cloud.search.builder;

import com.tmerclub.cloud.api.dto.EsPageDTO;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.local.vo.CueProductSearchVO;
import com.tmerclub.cloud.common.util.Json;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

/**
 * 本地生活-球杆商品搜索结果构建
 *
 * @author: frank
 * @create: 2025-04-13
 **/
@Component
public class LocalCueProductSearchResponseBuilder {
    private static final Logger log = LoggerFactory.getLogger(LocalCueProductSearchResponseBuilder.class);


    /**
     * 获取搜索结果列表
     *
     * @param response 搜索结果
     * @return 搜索结果列表
     */
    public List<CueProductSearchVO> getProductSearchList(SearchResponse response) {

        // 1、返回的所有查询到的商品
        List<CueProductSearchVO> cueProductSearchVOList = new ArrayList<>();
        //===============列表信息====================//
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            CueProductSearchVO cueProductSearchVO = Json.parseObject(json, CueProductSearchVO.class);
            cueProductSearchVOList.add(cueProductSearchVO);
        }
        return cueProductSearchVOList;
    }

    /**
     * 构建分页数据
     *
     * @param pageDTO  分页参数
     * @param esPageVO 分页返回对象
     * @param response 搜索结果
     */
    public void buildSearchPage(EsPageDTO pageDTO, EsPageVO<?> esPageVO, SearchResponse response) {
        //总记录数
        long total = response.getHits().getTotalHits().value;
        esPageVO.setTotal(total);
        // 总页码
        int totalPages = (int) total % pageDTO.getPageSize() == 0 ?
                (int) total / pageDTO.getPageSize() : ((int) total / pageDTO.getPageSize() + 1);
        esPageVO.setPages(totalPages);
    }
}