package com.yeejoin.amos.boot.module.jcs.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jcs.api.dto.ESAlertCalledDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.ESAlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.ESCar;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertStatusEnum;
import com.yeejoin.amos.boot.module.jcs.api.service.IESCarService;
import com.yeejoin.amos.boot.module.jcs.biz.dao.ESCarRepository;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;


/**
 * @description:
 * @author: tw
 * @createDate: 2022/8/24
 */
@Service
public class ESCarService implements IESCarService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Autowired
    private ESCarRepository esCarRepository;

    @Override
    public ESCar saveESCar(ESCar Car) throws Exception
    {
        esCarRepository.save(Car);
        return Car;
    }

    @Override
    public Iterable<ESCar> findAllById(List<Long> ids) throws Exception {
        return esCarRepository.findAllById(ids);


    }

    @Override
    public ESCar findAllByCarId(Long id)   {
        MatchQueryBuilder matchQueryBuilder= QueryBuilders.matchQuery("sequenceNbr", id);
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(matchQueryBuilder)
                .withPageable(PageRequest.of(0, 1))
                .withSort(SortBuilders.fieldSort("Time").order(SortOrder.DESC));
        List<ESCar> list = new LinkedList<>();
        long totle = 0;
        try
        {
            SearchHits<ESCar> searchHits =elasticsearchTemplate.search(queryBuilder.build(), ESCar.class);

            for (SearchHit searchHit : searchHits.getSearchHits())
            {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(searchHit.getContent());
                ESCar eSCar =JSONObject.toJavaObject(jsonObject, ESCar.class);
                list.add(eSCar);
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


        return list!=null&&list.size()>0?list.get(0):null;
    }


}
