package cn.reghao.tnb.search.esapp.controller;

import cn.reghao.jutil.jdk.web.db.PageList;
import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.search.esapp.es.QueryService;
import cn.reghao.tnb.search.esapp.model.po.Wenshu;
import cn.reghao.tnb.search.esapp.model.vo.ElasticQuery;
import cn.reghao.tnb.search.esapp.model.vo.WenshuResult;
import cn.reghao.tnb.search.esapp.service.WenshuSearchService;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 裁判文书搜索接口
 *
 * @author reghao
 * @date 2025-05-02 16:44:46
 */
@RestController
@RequestMapping("/api/search1/wenshu")
public class WenshuSearchController {
    private final WenshuSearchService wenshuSearchService;
    private final QueryService<Wenshu> queryService;

    public WenshuSearchController(WenshuSearchService wenshuSearchService, QueryService<Wenshu> queryService) {
        this.wenshuSearchService = wenshuSearchService;
        this.queryService = queryService;
    }

    @GetMapping(value = "/query", produces = MediaType.APPLICATION_JSON_VALUE)
    public String searchWenshu(@RequestParam(value = "pn") int pn, @RequestParam(value = "keyword") String keyword) {
        int pageSize = 10;
        String indexName = "";
        PageList<WenshuResult> pageList1 = wenshuSearchService.search(pn, keyword);
        ElasticQuery elasticQuery = new ElasticQuery.Builder()
                .pageSize(pageSize)
                .pageNumber(pn)
                .indexName(indexName)
                .highlightFiledNames(List.of("caseName"))
                //.otherFiledNames(List.of("caseName", "cause", "parties"))
                .queryString(keyword)
                .build();

        Page<Wenshu> page = queryService.queryWithHighlight(elasticQuery, Wenshu.class);
        int pageNumber = page.getNumber();
        //int pageSize = page.getSize();
        int total = (int) page.getTotalElements();
        List<WenshuResult> list = page.getContent().stream().map(WenshuResult::new).collect(Collectors.toList());
        PageList<WenshuResult> pageList = PageList.pageList(pageNumber, pageSize, total, list);
        return WebResult.success(pageList1);
    }

    @GetMapping(value = "/detail", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getWenshuDetail(@RequestParam("id") String id, @RequestParam("keyword") String keyword) {
        Wenshu wenshu = wenshuSearchService.queryById(id, keyword);
        return WebResult.success(wenshu);
    }
}
