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


import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.module.common.api.dto.ESOrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.dao.ESOrgUsrDtoRepository;


/**
 *
 * <pre>
 * 警情信息ES检索服务
 * </pre>
 *
 * @author gwb
 * @version $Id: ESAlertCalledService.java, v 0.1 2021年6月19日 下午5:12:01 gwb Exp $
 */
@Service
public class ESOrgUsrService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Autowired
    private ESOrgUsrDtoRepository esOrgUsrDtoRepository;

    @Autowired
    private  OrgUsrServiceImpl orgUsrServiceImpl;
    
	@PostConstruct
	public void init() throws Exception
	{
//		elasticsearchTemplate.deleteIndex(ESOrgUsrDto.class);
//        elasticsearchTemplate.createIndex(ESOrgUsrDto.class);
//	    elasticsearchTemplate.putMapping(ESOrgUsrDto.class);
	 //初始化ES，重建索引
		initEs();
	}

    /**
     * 重建索引
     */
    public Boolean initEs() throws Exception {
    	 esOrgUsrDtoRepository.deleteAll();
    	//获取所有单位
    	  QueryWrapper<OrgUsr> wrapper = new QueryWrapper<>();
    	  
    	  wrapper.in("biz_org_type", "DEPARTMENT","COMPANY");
    	  wrapper.eq("is_delete", 0);
    	  List<OrgUsr>  list = orgUsrServiceImpl.list(wrapper);
    	
    	  saveAll(list);
    	
        return true;
    }

    /**
     *
     * <pre>
     * 批量保存
     * </pre>
     *
     * @param list 警情信息列表
     */
    public void saveAll( List<OrgUsr> orgUsrs) throws Exception{

    	if (!ValidationUtil.isEmpty(orgUsrs))
		{
			for (OrgUsr orgUsr : orgUsrs)
			{
				this.saveAlertCalledToES(orgUsr);
			}
		}
    }

    
    public ESOrgUsrDto saveAlertCalledToES(OrgUsr orgUsr) throws Exception
    {
    	ESOrgUsrDto esOrgUsrDto = new ESOrgUsrDto();
    	String seqStr = String.valueOf(orgUsr.getSequenceNbr());
    	try {
			Long seq = Long.parseLong(seqStr);
			esOrgUsrDto.setSequenceNbr(seq);
			esOrgUsrDto.setBizOrgName(orgUsr.getBizOrgName());
			esOrgUsrDtoRepository.save(esOrgUsrDto);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return esOrgUsrDto;
    }

	public ESOrgUsrDto saveAlertCalledToESNew(OrgUsr orgUsr) throws Exception
	{
		ESOrgUsrDto esOrgUsrDto = new ESOrgUsrDto();
		String seqStr = String.valueOf(orgUsr.getSequenceNbr());
		try {
			Long seq = Long.parseLong(seqStr);
			esOrgUsrDto.setSequenceNbr(seq);
			MatchQueryBuilder queryBuilder  =null;
			//设置模糊搜索
			if(orgUsr.getBizOrgName()!=null) {
				queryBuilder =QueryBuilders.matchQuery("bizOrgName", orgUsr.getBizOrgName());
			}
			Iterable<ESOrgUsrDto> search = esOrgUsrDtoRepository.search(queryBuilder);
			if(!search.iterator().hasNext()) {
				esOrgUsrDto.setBizOrgName(orgUsr.getBizOrgName());
				esOrgUsrDtoRepository.save(esOrgUsrDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return esOrgUsrDto;
	}

    /**
     *
     * <pre>
     *  从ES库批量删除
     * </pre>
     */
    public Boolean deleteById(Long sequenceNbr) throws Exception{
       
        		if (esOrgUsrDtoRepository.existsById(sequenceNbr)) {
        			esOrgUsrDtoRepository.deleteById(sequenceNbr);
        	
        }

        return true;
    }

    /**
     * 根据关键字查询文档，关键字
     *
     */
    @SuppressWarnings({ "rawtypes" })
	public Set<ESOrgUsrDto> queryByKeys(String name)
    {
    	 //创建builder
    	FuzzyQueryBuilder queryBuilder =null;
        //设置模糊搜索
        if(name!=null) {
         
        	queryBuilder =QueryBuilders.fuzzyQuery("bizOrgName", name);
       }
         Iterable<ESOrgUsrDto> search = esOrgUsrDtoRepository.search(queryBuilder);
        Set<ESOrgUsrDto> list = new LinkedHashSet<>();
			search.forEach(esOrgUsrDto->{				
				list.add(esOrgUsrDto);
			});
			
        return list;

    }

    

}
