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


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;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * <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 ESOrgUsrDtoRepository esOrgUsrDtoRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    @Lazy
    private OrgUsrServiceImpl orgUsrServiceImpl;

    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",  "COMPANY");
        wrapper.eq("is_delete", 0);
        List<OrgUsr> list = orgUsrServiceImpl.list(wrapper);

        saveAll(list);

        return true;
    }

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

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

                this.saveAlertCalledToES(orgUsrs);

        }
    }


    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 List<ESOrgUsrDto> saveAlertCalledToES(List<OrgUsr> orgUsrs) throws Exception {
        List<ESOrgUsrDto> listes=new ArrayList<>();
        try {

        for (OrgUsr orgUsr : orgUsrs) {
            ESOrgUsrDto esOrgUsrDto = new ESOrgUsrDto();
            String seqStr = String.valueOf(orgUsr.getSequenceNbr());

            Long seq = Long.parseLong(seqStr);
            esOrgUsrDto.setSequenceNbr(seq);
            esOrgUsrDto.setBizOrgName(orgUsr.getBizOrgName());
            listes.add(esOrgUsrDto);
        }
            esOrgUsrDtoRepository.saveAll(listes);


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




    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);
            // 使用 ElasticsearchRestTemplate 进行查询
            if (orgUsr.getBizOrgName() != null) {
                MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("bizOrgName", orgUsr.getBizOrgName());
                NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(queryBuilder).build();
                List<ESOrgUsrDto> results = elasticsearchRestTemplate.search(searchQuery, ESOrgUsrDto.class)
                    .stream()
                    .map(SearchHit::getContent)
                    .collect(Collectors.toList());
                if (results.isEmpty()) {
                    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);
        }
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(queryBuilder).build();
        List<ESOrgUsrDto> results = elasticsearchRestTemplate.search(searchQuery, ESOrgUsrDto.class)
            .stream()
            .map(SearchHit::getContent)
            .collect(Collectors.toList());
        Set<ESOrgUsrDto> list = new LinkedHashSet<>(results);

        return list;

    }


}
