package com.bawei.mall.search.controller;

import com.alibaba.fastjson2.JSONObject;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.search.domain.request.SearchReq;
import com.bawei.mall.search.es.instance.EsInstance;
import com.bawei.mall.search.service.SearchService;
import com.bawei.mall.search.utils.SearchResultUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author DongZl
 * @description: 搜索控制层
 * @Date 2022-10-24 下午 02:54
 */
@Controller
@RequestMapping("/search")
public class SearchController {

    private final static Logger log = LoggerFactory.getLogger(SearchController.class);

    @Autowired
    private SearchService searchService;

    /**
     * 1、查询到数据
     * 2、指定模板
     * 3、渲染模板
     * 4、返回页面
     *
     * @param searchReq
     * @param model
     * @return
     */
    @GetMapping
    public String search(SearchReq searchReq, Model model){
        log.info("搜索：[{}]", JSONObject.toJSONString(searchReq));
        if (StringUtils.isEmpty(searchReq.getKeyWord())){
            return "search";
        }

        searchService.search(searchReq);

        List<ProductInfoResponse> list = SearchResultUtils.getList();
        Long total = SearchResultUtils.getTotal();
        log.info(JSONObject.toJSONString(list));
        model.addAttribute("dataList", list);
        model.addAttribute("total", total);
        model.addAttribute("searchReq",searchReq);
        return "search";
    }
}
