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.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

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


/**
 * <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 OrgUsrServiceImpl orgUsrServiceImpl;

    public void init() throws Exception {
        //初始化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 list 警情信息列表
     */
    public void saveAll(List<OrgUsr> orgUsrs) throws Exception {

        if (!ValidationUtil.isEmpty(orgUsrs)) {
                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);
            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;
        Set<ESOrgUsrDto> list = new LinkedHashSet<>();
        //设置模糊搜索
        if (name != null) {

            queryBuilder = QueryBuilders.fuzzyQuery("bizOrgName", name);
            Iterable<ESOrgUsrDto> search = esOrgUsrDtoRepository.search(queryBuilder);

            search.forEach(esOrgUsrDto -> {
                list.add(esOrgUsrDto);
            });
        }


        return list;

    }


}
